// Contact.jsx — Delvecore Website UI Kit (responsive)
window.Contact = function Contact() {
  const mobile = useIsMobile();
  const endpoint = '/api/contact';
  const initialValues = {
    name: '',
    company: '',
    email: '',
    phone: '',
    plan: '',
    message: '',
  };
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');
  const [focused, setFocused] = React.useState(null);
  const [formValues, setFormValues] = React.useState(initialValues);
  const [touched, setTouched] = React.useState({});
  const formRef = React.useRef(null);

  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  function formatPhone(rawValue) {
    const digits = rawValue.replace(/\D/g, '').slice(0, 11);
    if (digits.length <= 3) return digits;
    if (digits.length <= 6) return `${digits.slice(0, 3)}-${digits.slice(3)}`;
    if (digits.length === 10) return `${digits.slice(0, 3)}-${digits.slice(3, 6)}-${digits.slice(6)}`;
    return `${digits.slice(0, 3)}-${digits.slice(3, 7)}-${digits.slice(7)}`;
  }

  function getErrors(values) {
    const nextErrors = {};
    if (!values.company.trim()) nextErrors.company = '会社名を入力してください';
    if (values.email && !emailPattern.test(values.email.trim())) {
      nextErrors.email = '正しいメールアドレスを入力してください';
    }
    return nextErrors;
  }

  const errors = getErrors(formValues);
  const canSubmit = Boolean(
    formValues.name.trim()
    && formValues.company.trim()
    && formValues.message.trim()
    && formValues.email.trim()
    && !errors.email
  );

  function handleInputChange(e) {
    const { name, value } = e.target;
    if (name === 'phone') {
      setFormValues((prev) => ({ ...prev, phone: formatPhone(value) }));
      return;
    }
    setFormValues((prev) => ({ ...prev, [name]: value }));
  }

  function handleFieldBlur(field) {
    setFocused(null);
    setTouched((prev) => ({ ...prev, [field]: true }));
  }

  const inputStyle = (name) => ({
    background: 'transparent', border: 'none',
    borderBottom: `1px solid ${focused === name ? '#0C0C0A' : '#E0DFD8'}`,
    padding: '12px 0', fontFamily: "'DM Sans', sans-serif", fontSize: 14,
    color: '#0C0C0A', outline: 'none', width: '100%',
    transition: 'border-color 0.3s ease',
  });

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setSending(true);
    const payload = {
      name: formValues.name.trim(),
      company: formValues.company.trim(),
      email: formValues.email.trim(),
      phone: formValues.phone.trim(),
      plan: formValues.plan,
      message: formValues.message.trim(),
    };

    try {
      const res = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        let detail = '';
        try {
          const payload = await res.json();
          detail = payload?.errors?.[0]?.message || payload?.error || '';
        } catch (_) {
          detail = '';
        }
        throw new Error(detail || 'submit_failed');
      }
      const form = formRef.current;
      form?.reset();
      setFormValues(initialValues);
      setTouched({});
      setSubmitted(true);
    } catch (err) {
      const maybeDetail = err?.message && err.message !== 'submit_failed' ? `（${err.message}）` : '';
      setError(`送信に失敗しました。時間をおいて再度お試しください。${maybeDetail}`);
    } finally {
      setSending(false);
    }
  }

  return (
    <section id="contact" style={{ padding: mobile ? '80px 24px' : '120px 48px' }}>
      <SectionHeader num="06" title="Contact" ja="お問い合わせ" />
      <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: mobile ? 48 : 120, alignItems: 'start', marginTop: 80 }}>
        <div>
          <p style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: mobile ? 'clamp(28px,7vw,44px)' : 'clamp(32px,4vw,52px)', fontWeight: 300, lineHeight: 1.4 }}>
            まず、気軽に<br />ご相談ください。
          </p>
          <p style={{ marginTop: 32, fontSize: 13, color: '#888884', lineHeight: 1.9 }}>
            1週間以内にご返信します。<br />サービス内容・料金・納期など、<br />お気軽にお問い合わせください。
          </p>
          <p style={{ marginTop: 14, fontSize: 12, color: '#888884' }}>
            送信後、自動受付メールをお送りします。
          </p>
        </div>
        <form ref={formRef} style={{ display: 'flex', flexDirection: 'column', gap: 32 }} onSubmit={handleSubmit}>
          {[['name','お名前','山田 太郎'],['company','会社名・屋号','株式会社〇〇'],['email','メールアドレス','hello@example.com'],['phone','電話番号','090-1234-5678']].map(([id, label, ph]) => (
            <div key={id} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <label style={{ fontSize: 11, letterSpacing: '0.15em', textTransform: 'uppercase', color: '#888884' }}>{label}</label>
              <input type={id === 'email' ? 'email' : 'text'} placeholder={ph} required={id === 'name' || id === 'email'}
                name={id}
                value={formValues[id]}
                style={inputStyle(id)}
                onChange={handleInputChange}
                onFocus={() => setFocused(id)}
                onBlur={() => handleFieldBlur(id)} />
              {touched[id] && errors[id] && <p style={{ color: '#8F1A1A', fontSize: 12 }}>{errors[id]}</p>}
            </div>
          ))}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <label style={{ fontSize: 11, letterSpacing: '0.15em', textTransform: 'uppercase', color: '#888884' }}>ご希望プラン</label>
            <select
              name="plan"
              value={formValues.plan}
              style={{ ...inputStyle('plan'), paddingRight: 12 }}
              onChange={handleInputChange}
              onFocus={() => setFocused('plan')}
              onBlur={() => handleFieldBlur('plan')}
            >
              <option value="" disabled>選択してください（任意）</option>
              <option value="スターター（¥5〜15万）">スターター（¥5〜15万）</option>
              <option value="スタンダード（¥30〜50万）">スタンダード（¥30〜50万）</option>
              <option value="まずはご相談">まずはご相談</option>
              <option value="まだ決めていない">まだ決めていない</option>
            </select>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <label style={{ fontSize: 11, letterSpacing: '0.15em', textTransform: 'uppercase', color: '#888884' }}>ご相談内容</label>
            <textarea placeholder="サイト制作のご依頼、業務効率化のご相談など、お気軽にどうぞ。" required
              name="message"
              value={formValues.message}
              style={{ ...inputStyle('message'), resize: 'none', height: 120 }}
              onChange={handleInputChange}
              onFocus={() => setFocused('message')}
              onBlur={() => handleFieldBlur('message')} />
          </div>
          {error && <p style={{ color: '#8F1A1A', fontSize: 13 }}>{error}</p>}
          <SubmitButton submitted={submitted} sending={sending} canSubmit={canSubmit} />
        </form>
      </div>
    </section>
  );
};

function SubmitButton({ submitted, sending, canSubmit }) {
  const [hovered, setHovered] = React.useState(false);
  const disabled = submitted || sending || !canSubmit;
  return (
    <button type="submit" disabled={disabled}
      onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 16, background: '#0C0C0A', color: '#F8F7F5', border: 'none', padding: '16px 32px', fontFamily: "'DM Sans',sans-serif", fontSize: 12, letterSpacing: '0.15em', textTransform: 'uppercase', cursor: disabled ? 'default' : 'pointer', opacity: disabled ? 0.4 : hovered ? 0.7 : 1, transition: 'opacity 0.3s ease', alignSelf: 'flex-start' }}>
      <span>{submitted ? '送信しました ✓（1週間以内にご返信します）' : sending ? '送信中...' : '送信する'}</span>
      {!disabled && <span style={{ display: 'inline-block', transform: hovered ? 'translateX(4px)' : 'none', transition: 'transform 0.3s ease' }}>→</span>}
    </button>
  );
}
