const Contact = () => {
  const [state, setState] = React.useState({ status: 'idle', error: '' });
  // status: idle | submitting | ok | error
  const formRef = React.useRef(null);
  const tsContainerRef = React.useRef(null);
  const tsWidgetIdRef = React.useRef(null);
  const tokenRef = React.useRef('');

  // Mount Turnstile widget once its script is ready
  React.useEffect(() => {
    let cancelled = false;
    let pollId;

    const mount = () => {
      if (cancelled || !tsContainerRef.current || tsWidgetIdRef.current != null) return;
      if (!window.turnstile) return;
      tsWidgetIdRef.current = window.turnstile.render(tsContainerRef.current, {
        sitekey: window.TURNSTILE_SITE_KEY,
        theme: 'dark',
        callback: (token) => { tokenRef.current = token; },
        'error-callback': () => { tokenRef.current = ''; },
        'expired-callback': () => { tokenRef.current = ''; },
      });
    };

    if (window.turnstile) mount();
    else pollId = setInterval(() => { if (window.turnstile) { clearInterval(pollId); mount(); } }, 100);

    return () => {
      cancelled = true;
      if (pollId) clearInterval(pollId);
      if (tsWidgetIdRef.current != null && window.turnstile) {
        try { window.turnstile.remove(tsWidgetIdRef.current); } catch (e) { /* noop */ }
        tsWidgetIdRef.current = null;
      }
    };
  }, []);

  const onSubmit = async (e) => {
    e.preventDefault();
    if (state.status === 'submitting') return;

    const form = formRef.current;
    const data = Object.fromEntries(new FormData(form).entries());
    const payload = {
      name: data.name || '',
      company: data.company || '',
      email: data.email || '',
      stage: data.stage || '',
      message: data.message || '',
      website: data.website || '', // honeypot
      turnstileToken: tokenRef.current,
    };

    if (!payload.turnstileToken) {
      setState({ status: 'error', error: 'Verifying you are human… try again in a moment.' });
      return;
    }

    setState({ status: 'submitting', error: '' });
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const body = await res.json().catch(() => ({}));
      if (!res.ok || !body.ok) {
        throw new Error(body.error || 'Something went wrong. Please try again.');
      }
      setState({ status: 'ok', error: '' });
      form.reset();
      if (tsWidgetIdRef.current != null && window.turnstile) {
        window.turnstile.reset(tsWidgetIdRef.current);
        tokenRef.current = '';
      }
    } catch (err) {
      setState({ status: 'error', error: err.message || 'Something went wrong.' });
      if (tsWidgetIdRef.current != null && window.turnstile) {
        window.turnstile.reset(tsWidgetIdRef.current);
        tokenRef.current = '';
      }
    }
  };

  const submitting = state.status === 'submitting';

  return (
    <section id="contact">
      <Container>
        <div className="contact__wrap">
          <div className="contact__grid">
            <div>
              <span className="eyebrow" style={{ color: '#F2863E' }}>Start a project</span>
              <h2 style={{ marginTop: 18 }}>Tell me what you're trying to make.</h2>
              <p>48-hour turnaround on a line-item feasibility quote. No NDA required for the first call. We'll sign one before anything sensitive changes hands.</p>

              <div className="contact__meta">
                <div className="row"><div className="k">Email</div><div className="v">paul@xlovation.com</div></div>
                <div className="row"><div className="k">Phone</div><div className="v">+84 28 3822 1100</div></div>
                <div className="row"><div className="k">Office</div><div className="v">Bình Thạnh District · Ho Chi Minh City</div></div>
                <div className="row"><div className="k">Hours</div><div className="v">Mon–Fri · 8:00–18:00 ICT</div></div>
              </div>
            </div>

            {state.status === 'ok' ? (
              <div className="form glass-dark" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', minHeight: 320 }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.55)', marginBottom: 12 }}>Message sent</div>
                <h3 style={{ color: '#fff', fontSize: 26, marginBottom: 12 }}>Thanks — I'll be in touch within 48 hours.</h3>
                <p style={{ color: 'rgba(255,255,255,0.8)', fontSize: 15 }}>Your message is in my inbox. If it's urgent, reply to the confirmation email and I'll jump to the front of the queue.</p>
                <button
                  type="button"
                  className="btn btn--ghost"
                  style={{ marginTop: 24, alignSelf: 'flex-start', color: '#fff', borderColor: 'rgba(255,255,255,0.3)' }}
                  onClick={() => setState({ status: 'idle', error: '' })}
                >
                  Send another
                </button>
              </div>
            ) : (
              <form ref={formRef} className="form glass-dark" onSubmit={onSubmit} noValidate>
                <div className="cols">
                  <div className="row"><label>Name</label><input name="name" placeholder="Your name" required disabled={submitting} /></div>
                  <div className="row"><label>Company</label><input name="company" placeholder="Brand / company" disabled={submitting} /></div>
                </div>
                <div className="cols">
                  <div className="row"><label>Email</label><input name="email" type="email" placeholder="you@company.com" required disabled={submitting} /></div>
                  <div className="row"><label>Stage</label>
                    <select name="stage" defaultValue="" disabled={submitting}>
                      <option value="" disabled>Select…</option>
                      <option>Napkin sketch</option>
                      <option>Have a prototype</option>
                      <option>Ready to tool</option>
                      <option>In production, need help</option>
                    </select>
                  </div>
                </div>
                <div className="row"><label>What are you making?</label><textarea name="message" placeholder="Product type, target price, target MOQ, launch date if you have one." required disabled={submitting} /></div>

                {/* Honeypot — hidden from humans */}
                <div aria-hidden="true" style={{ position: 'absolute', left: '-10000px', top: 'auto', width: 1, height: 1, overflow: 'hidden' }}>
                  <label>Website (leave empty)<input name="website" tabIndex="-1" autoComplete="off" /></label>
                </div>

                <div ref={tsContainerRef} style={{ marginBottom: 14, minHeight: 65 }} />

                {state.status === 'error' && (
                  <div style={{ marginBottom: 14, padding: '10px 12px', borderRadius: 10, background: 'rgba(242,134,62,0.15)', border: '1px solid rgba(242,134,62,0.4)', color: '#ffd3b2', fontSize: 13 }}>
                    {state.error}
                  </div>
                )}

                <button className="btn btn--primary" type="submit" style={{ width: '100%', justifyContent: 'center' }} disabled={submitting}>
                  {submitting ? 'Sending…' : <>Send inquiry <Arrow /></>}
                </button>
              </form>
            )}
          </div>
        </div>
      </Container>
    </section>
  );
};

window.Contact = Contact;
