// Contact.jsx
const Contact = () => {
  const t = useT();
  const [topic, setTopic] = React.useState('mentoring');

  // 'idle' | 'sending' | 'failed' (success is handled by `sent` below)
  const [status, setStatus] = React.useState('idle');
  // mailto: fallback built from the form fields when the service is unreachable
  const [mailtoHref, setMailtoHref] = React.useState('');

  // After a successful FormSubmit round-trip, we come back with ?sent=1
  const [sent, setSent] = React.useState(false);
  React.useEffect(() => {
    try {
      const p = new URLSearchParams(window.location.search);
      if (p.get('sent') === '1') {
        setSent(true);
        // clean the URL so a refresh doesn't keep the state
        const clean = window.location.origin + window.location.pathname + '#contact';
        window.history.replaceState({}, '', clean);
      }
    } catch (e) {}
  }, []);

  const topicLabel = (t.contact.topics.find(([k]) => k === topic) || [, ''])[1];

  // redirect back to this same page (wherever it is hosted) with a success flag
  const nextUrl = (() => {
    try { return window.location.origin + window.location.pathname + '?sent=1'; }
    catch (e) { return ''; }
  })();

  // Web3Forms — reliable static-form backend (Amazon-powered, no server needed).
  // The access key is public by design (an alias for the inbox email).
  const WEB3FORMS_KEY = 'a3871556-0323-48b2-aac3-aadabd1c1403';
  const ENDPOINT = 'https://api.web3forms.com/submit';
  const FALLBACK_EMAIL = 'hello@beep-consult.com';

  // Build a pre-filled mailto: so a visitor is never blocked if the form service is down
  const buildMailto = (data) => {
    const subject = 'Contact — beep-consult.com (' + (data.topic || '') + ')';
    const body =
      'Name: ' + (data.name || '') + '\n' +
      'Email: ' + (data.email || '') + '\n' +
      'Topic: ' + (data.topic || '') + '\n\n' +
      (data.message || '');
    return 'mailto:' + FALLBACK_EMAIL +
      '?subject=' + encodeURIComponent(subject) +
      '&body=' + encodeURIComponent(body);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (status === 'sending') return;
    const form = e.target;
    const fd = new FormData(form);
    const data = {
      name: fd.get('name'), email: fd.get('email'),
      topic: fd.get('topic'), message: fd.get('message'),
    };
    // Honeypot — silently accept and pretend success
    if (fd.get('botcheck')) { setSent(true); return; }

    setStatus('sending');
    try {
      const res = await fetch(ENDPOINT, {
        method: 'POST',
        headers: { 'Accept': 'application/json' },
        body: fd,
      });
      // Web3Forms returns 200 with { success: true } on a delivered message
      if (!res.ok) throw new Error('HTTP ' + res.status);
      const json = await res.json().catch(() => ({}));
      if (json && (json.success === 'true' || json.success === true)) {
        setStatus('idle');
        setSent(true);
      } else {
        throw new Error('Unexpected response');
      }
    } catch (err) {
      // Service unreachable (e.g. Cloudflare 521) — fall back to email
      setMailtoHref(buildMailto(data));
      setStatus('failed');
    }
  };

  return (
    <section className="bp-section" id="contact">
      <div className="bp-contact">
        <div className="bp-contact__left">
          <span className="bp-eyebrow">{t.contact.eyebrow}</span>
          <h2 className="bp-section__title">{t.contact.title}</h2>
          <p className="bp-contact__sub">{t.contact.sub}</p>
          <ul className="bp-contact__list">
            <li><span className="bp-mono bp-mono--muted">{t.contact.lEmail}</span><a href="mailto:hello@beep-consult.com">hello@beep-consult.com</a></li>
            <li><span className="bp-mono bp-mono--muted">{t.contact.lInPerson}</span><span data-comment-anchor="cc-1">{t.contact.inPerson}</span></li>
            <li><span className="bp-mono bp-mono--muted">{t.contact.lLinkedIn}</span><a href="https://www.linkedin.com/in/fabrice-bouland-83032/" target="_blank" rel="noopener">/in/fabrice-bouland</a></li>
          </ul>
        </div>

        {sent ? (
          <div className="bp-form bp-form--sent">
            <span className="bp-pulse"></span>
            <h3 className="bp-form__sent-title">{t.contact.okTitle}</h3>
            <p className="bp-form__sent-body">{t.contact.okBody}</p>
            <button className="bp-btn bp-btn--ghost bp-btn--sm" type="button" onClick={() => setSent(false)}>{t.contact.again}</button>
          </div>
        ) : status === 'failed' ? (
          <div className="bp-form bp-form--sent">
            <h3 className="bp-form__sent-title">{t.contact.failTitle}</h3>
            <p className="bp-form__sent-body">{t.contact.failBody}</p>
            <a className="bp-btn bp-btn--primary" href={mailtoHref}>{t.contact.failCta} <span>→</span></a>
            <button className="bp-btn bp-btn--ghost bp-btn--sm" type="button" onClick={() => setStatus('idle')}>{t.contact.retry}</button>
          </div>
        ) : (
          <form className="bp-form" action={ENDPOINT} method="POST" onSubmit={handleSubmit}>
            {/* Web3Forms configuration */}
            <input type="hidden" name="access_key" value={WEB3FORMS_KEY} />
            <input type="hidden" name="subject" value="Nouveau message — beep-consult.com" />
            <input type="hidden" name="from_name" value="beep-consult.com" />
            <input type="checkbox" name="botcheck" style={{ display: 'none' }} tabIndex="-1" autoComplete="off" />
            <input type="hidden" name="topic" value={topicLabel} />

            <div className="bp-field">
              <label>{t.contact.fName}</label>
              <input type="text" name="name" className="bp-input" placeholder={t.contact.phName} required />
            </div>
            <div className="bp-field">
              <label>{t.contact.fEmail}</label>
              <input type="email" name="email" className="bp-input" placeholder={t.contact.phEmail} required />
            </div>
            <div className="bp-field">
              <label>{t.contact.fTopic}</label>
              <div className="bp-radio">
                {t.contact.topics.map(([k, v]) =>
                <button type="button" key={k} className={"bp-radio__btn " + (topic === k ? 'is-active' : '')} onClick={() => setTopic(k)}>{v}</button>
                )}
              </div>
            </div>
            <div className="bp-field">
              <label>{t.contact.fMsg}</label>
              <textarea name="message" className="bp-input bp-input--ta" rows="3" placeholder={t.contact.phMsg} required></textarea>
            </div>
            <button className="bp-btn bp-btn--primary" type="submit" disabled={status === 'sending'}>{status === 'sending' ? t.contact.sending : t.contact.send} <span>→</span></button>
          </form>
        )}
      </div>
    </section>);

};
window.Contact = Contact;
