// contact-modal.jsx — Modal contact form with validation

const VL_CONTACT_ENDPOINT = 'https://formsubmit.co/ajax/a2f753c7b7f67dad90e9f08d6b3b4535';

function ContactModal() {
  const [open, setOpen] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState('');
  const [form, setForm] = React.useState({ name: '', company: '', email: '', message: '', interest: 's1' });
  const [errors, setErrors] = React.useState({});

  React.useEffect(() => {
    window.__vlOpenContact = () => { setOpen(true); setSubmitted(false); setSubmitError(''); };
    return () => { delete window.__vlOpenContact; };
  }, []);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open]);

  if (!open) return null;

  const validate = () => {
    const er = {};
    if (!form.name.trim()) er.name = '必須';
    if (!form.company.trim()) er.company = '必須';
    if (!form.email.trim()) er.email = '必須';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) er.email = 'メール形式が正しくありません';
    if (!form.message.trim() || form.message.trim().length < 10) er.message = '10文字以上ご記入ください';
    setErrors(er);
    return Object.keys(er).length === 0;
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!validate()) return;
    if (submitting) return;
    setSubmitError('');
    setSubmitting(true);
    try {
      const interestLabel = VL_COPY.services.items.find(i => i.id === form.interest)?.title || form.interest;
      const res = await fetch(VL_CONTACT_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          _subject: `[VerdiaLink] お問い合わせ — ${form.company}`,
          _template: 'table',
          _captcha: 'false',
          _replyto: form.email,
          'お名前': form.name,
          '会社名': form.company,
          'メールアドレス': form.email,
          '関心のある領域': interestLabel,
          'ご相談内容': form.message,
        }),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json().catch(() => ({}));
      if (data && String(data.success) === 'false') {
        if (typeof data.message === 'string' && /activation/i.test(data.message)) {
          throw new Error('ACTIVATION_REQUIRED');
        }
        throw new Error(data.message || 'submit failed');
      }
      setSubmitted(true);
    } catch (err) {
      if (err && err.message === 'ACTIVATION_REQUIRED') {
        setSubmitError('お問い合わせフォームの初期設定（受信側のアクティベーション）が未完了です。設定完了までお手数ですが info@verdialink.com まで直接メールをお送りください。');
      } else {
        setSubmitError('送信に失敗しました。時間をおいて再度お試しいただくか、info@verdialink.com までメールをお送りください。');
      }
    } finally {
      setSubmitting(false);
    }
  };

  const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); if (errors[k]) setErrors(er => ({ ...er, [k]: undefined })); };

  const fieldStyle = (err) => ({
    width: '100%', padding: '12px 14px', fontSize: 14, fontFamily: 'var(--jp)',
    border: `1px solid ${err ? 'var(--warn)' : 'var(--rule-2)'}`,
    background: '#fff', color: 'var(--ink)', outline: 'none',
    transition: 'border-color .15s',
  });
  const labelStyle = { fontFamily: 'var(--jp)', fontSize: 11.5, color: 'var(--ink-3)', letterSpacing: '0.04em', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 8 };

  return (
    <div onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(10,20,40,0.4)',
        backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
        animation: 'vlfade .25s ease-out',
      }}>
      <style>{`@keyframes vlfade{from{opacity:0}to{opacity:1}}@keyframes vlrise{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}`}</style>
      <div style={{
        width: '100%', maxWidth: 580, background: 'var(--bg)', position: 'relative',
        animation: 'vlrise .35s cubic-bezier(.2,.7,.3,1)',
        boxShadow: '0 32px 80px rgba(10,31,68,0.22)',
        maxHeight: '92vh', overflow: 'auto',
      }}>
        <button onClick={() => setOpen(false)}
          style={{
            position: 'absolute', top: 16, right: 16, width: 32, height: 32,
            background: 'transparent', border: 'none', cursor: 'pointer',
            color: 'var(--ink-3)', fontSize: 22, lineHeight: 1,
          }}>×</button>

        {!submitted ? (
          <form onSubmit={submit} style={{ padding: '40px 44px 44px' }}>
            <EnKicker color="var(--ink)">CONTACT</EnKicker>
            <h3 style={{ fontFamily: 'var(--jp)', fontSize: 24, fontWeight: 500, color: 'var(--ink)', margin: '16px 0 8px', letterSpacing: '0.005em' }}>
              ご相談を承ります
            </h3>
            <p style={{ fontFamily: 'var(--jp)', fontSize: 13, lineHeight: 1.85, color: 'var(--ink-3)', margin: '0 0 32px' }}>
              業務に深く入り込む支援を、本気で求めている方へ。<br />
              通常2営業日以内にご返信いたします。
            </p>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
              <div>
                <div style={labelStyle}>お名前 {errors.name && <span style={{ color: 'var(--warn)' }}>· {errors.name}</span>}</div>
                <input style={fieldStyle(errors.name)} value={form.name} onChange={e => set('name', e.target.value)} />
              </div>
              <div>
                <div style={labelStyle}>会社名 {errors.company && <span style={{ color: 'var(--warn)' }}>· {errors.company}</span>}</div>
                <input style={fieldStyle(errors.company)} value={form.company} onChange={e => set('company', e.target.value)} />
              </div>
            </div>

            <div style={{ marginBottom: 16 }}>
              <div style={labelStyle}>メールアドレス {errors.email && <span style={{ color: 'var(--warn)' }}>· {errors.email}</span>}</div>
              <input style={fieldStyle(errors.email)} value={form.email} onChange={e => set('email', e.target.value)} type="email" />
            </div>

            <div style={{ marginBottom: 16 }}>
              <div style={labelStyle}>関心のある領域</div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {VL_COPY.services.items.map(it => (
                  <label key={it.id} style={{
                    display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
                    border: `1px solid ${form.interest === it.id ? 'var(--ink)' : 'var(--rule-2)'}`,
                    background: form.interest === it.id ? '#fff' : 'transparent',
                    cursor: 'pointer', fontFamily: 'var(--jp)', fontSize: 12.5,
                  }}>
                    <input type="radio" name="interest" checked={form.interest === it.id} onChange={() => set('interest', it.id)}
                      style={{ accentColor: 'var(--ink)' }} />
                    {it.title}
                  </label>
                ))}
              </div>
            </div>

            <div style={{ marginBottom: 28 }}>
              <div style={labelStyle}>ご相談内容 {errors.message && <span style={{ color: 'var(--warn)' }}>· {errors.message}</span>}</div>
              <textarea rows={5} style={{ ...fieldStyle(errors.message), resize: 'vertical', minHeight: 100 }}
                value={form.message} onChange={e => set('message', e.target.value)} />
            </div>

            {submitError && (
              <div style={{
                marginBottom: 16, padding: '10px 12px',
                border: '1px solid var(--warn)', background: 'rgba(180,90,44,0.06)',
                color: 'var(--warn)', fontFamily: 'var(--jp)', fontSize: 12.5, lineHeight: 1.7,
              }}>{submitError}</div>
            )}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontFamily: 'var(--jp)', fontSize: 11, color: 'var(--ink-4)' }}>
                送信により <a href="/privacy.html" target="_blank" rel="noopener" style={{ color: 'var(--ink-3)', textDecoration: 'underline' }}>プライバシーポリシー</a> に同意したとみなされます
              </div>
              <VlButton primary type="submit" disabled={submitting}>{submitting ? '送信中…' : '送信する'}</VlButton>
            </div>
          </form>
        ) : (
          <div style={{ padding: '60px 44px 56px', textAlign: 'center' }}>
            <div style={{ width: 56, height: 56, borderRadius: 28, border: '1px solid var(--ink)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24 }}>
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="var(--ink)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 11l4 4 8-8" /></svg>
            </div>
            <h3 style={{ fontFamily: 'var(--jp)', fontSize: 22, fontWeight: 500, color: 'var(--ink)', margin: '0 0 12px' }}>
              お問い合わせを受け付けました
            </h3>
            <p style={{ fontFamily: 'var(--jp)', fontSize: 13.5, lineHeight: 1.85, color: 'var(--ink-3)', margin: '0 0 32px' }}>
              {form.name} 様、ありがとうございます。<br />
              通常2営業日以内に {form.email} 宛にご返信いたします。
            </p>
            <VlButton onClick={() => setOpen(false)}>閉じる</VlButton>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ContactModal });
