function Inquiry(){
  const [form, setForm] = React.useState({
    name: '', email: '', phone: '',
    type: '', dateWhen: '', guests: '',
    message: ''
  });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [refNo] = React.useState(() => 'BY-' + Math.floor(10000 + Math.random()*90000));
  const [token, setToken] = React.useState('');
  const [submitError, setSubmitError] = React.useState('');
  const turnstileRef = React.useRef(null);
  const widgetIdRef = React.useRef(null);

  // Public Turnstile sitekey — safe to ship in client code. Replace with the
  // sitekey from your Cloudflare Turnstile widget (Dashboard → Turnstile).
  const TURNSTILE_SITEKEY = '0x4AAAAAADSjmlTn9Un1gZcg';

  const siteTheme = (typeof document !== 'undefined'
    && document.documentElement.getAttribute('data-theme')) === 'light' ? 'light' : 'dark';

  React.useEffect(() => {
    if (submitted) return; // form (and the widget container) isn't mounted on the success screen
    let cancelled = false;
    let intervalId = null;

    const tryRender = () => {
      if (cancelled) return false;
      if (!window.turnstile || !turnstileRef.current) return false;
      if (widgetIdRef.current !== null) return true;
      widgetIdRef.current = window.turnstile.render(turnstileRef.current, {
        sitekey: TURNSTILE_SITEKEY,
        theme: siteTheme,
        callback: (tok) => setToken(tok),
        'expired-callback': () => setToken(''),
        'error-callback': () => setToken(''),
      });
      return true;
    };

    // The Turnstile script loads async and this component mounts lazily on
    // route change, so window.turnstile may not exist yet — poll until it does.
    if (!tryRender()) {
      intervalId = setInterval(() => {
        if (tryRender() && intervalId) { clearInterval(intervalId); intervalId = null; }
      }, 150);
    }

    return () => {
      cancelled = true;
      if (intervalId) clearInterval(intervalId);
      if (window.turnstile && widgetIdRef.current !== null) {
        try { window.turnstile.remove(widgetIdRef.current); } catch (_) {}
      }
      widgetIdRef.current = null;
    };
  }, [submitted]);

  const types = ['Private', 'Corporate', 'Concert', 'Nightlife', 'Pop-up', 'Other'];

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

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Required';
    if (!form.email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Invalid email';
    if (!form.type) e.type = 'Choose one';
    if (!form.message.trim()) e.message = 'Tell us a little';
    return e;
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    setSubmitError('');
    const eMap = validate();
    setErrors(eMap);
    if (Object.keys(eMap).length) return;
    if (!token) { setSubmitError('Please complete the verification below.'); return; }

    setSubmitting(true);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, refNo, turnstileToken: token }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) {
        throw new Error(data.error || 'Something went wrong. Please try again or email austin@byace.events.');
      }
      setSubmitting(false);
      setSubmitted(true);
    } catch (err) {
      setSubmitting(false);
      setSubmitError(err.message || 'Network error. Please try again.');
      // Turnstile tokens are single-use and expire (~300s); force a fresh one.
      setToken('');
      if (window.turnstile && widgetIdRef.current !== null) {
        try { window.turnstile.reset(widgetIdRef.current); } catch (_) {}
      }
    }
  };

  return (
    <>
      <Marquee alt items={[
        "CUSTOM EVENTS NEAR & FAR ♠",
        "TACOS N' TEQUILA 5/5/26 ♥",
        "CUSTOM EVENTS NEAR & FAR ♠",
      ]} />

      <section className="container inquiry">
        <div className="inquiry-inner">
          <div className="inquiry-copy">
            <span className="eyebrow" style={{marginBottom:20, display:'inline-block'}}>§ Inquire · <span style={{color:'var(--accent)'}}>♥</span></span>
            <h2>Let's <em>party.</em></h2>
            <p>Get in touch.</p>
            <div className="socials">
              <a className="social" href="https://instagram.com/byace.events" target="_blank" rel="noreferrer">
                <span className="lbl">Instagram</span>
                <span className="val">@byace.events →</span>
              </a>
              <a className="social" href="mailto:austin@byace.events">
                <span className="lbl">Email</span>
                <span className="val">austin@byace.events →</span>
              </a>
              <a className="social" href="https://venmo.com/u/byace" target="_blank" rel="noreferrer">
                <span className="lbl">Venmo</span>
                <span className="val">@byace →</span>
              </a>
            </div>
          </div>

          <div className="ticket">
            {!submitted ? (
              <form onSubmit={onSubmit} noValidate>
                <div className="ticket-head">
                  <div className="t">Inquiry</div>
                  <div className="no">№ {refNo}</div>
                </div>

                <div className="field-row">
                  <div className={`field ${errors.name ? 'error' : ''}`}>
                    <label>Name <span className="hint">required</span></label>
                    <input type="text" value={form.name} onChange={e=>set('name', e.target.value)} placeholder="Your full name" />
                    <div className="err">{errors.name}</div>
                  </div>
                  <div className={`field ${errors.email ? 'error' : ''}`}>
                    <label>Email <span className="hint">required</span></label>
                    <input type="email" value={form.email} onChange={e=>set('email', e.target.value)} placeholder="you@domain.com" />
                    <div className="err">{errors.email}</div>
                  </div>
                </div>

                <div className="field-row">
                  <div className="field">
                    <label>Phone <span className="hint">optional</span></label>
                    <input type="tel" value={form.phone} onChange={e=>set('phone', e.target.value)} placeholder="(—) —" />
                  </div>
                  <div className="field">
                    <label>Preferred date <span className="hint">optional</span></label>
                    <input type="text" value={form.dateWhen} onChange={e=>set('dateWhen', e.target.value)} placeholder="Summer 2026, or flexible" />
                  </div>
                </div>

                <div className={`field ${errors.type ? 'error' : ''}`}>
                  <label>What is it <span className="hint">pick one</span></label>
                  <div className="chip-group" style={{marginTop:8}}>
                    {types.map(t => (
                      <button key={t} type="button"
                        className={`chip ${form.type === t ? 'on' : ''}`}
                        onClick={()=>set('type', t)}>
                        {t}
                      </button>
                    ))}
                  </div>
                  <div className="err" style={{marginTop:8}}>{errors.type}</div>
                </div>

                <div className="field">
                  <label>Guests <span className="hint">estimate is fine</span></label>
                  <input type="text" value={form.guests} onChange={e=>set('guests', e.target.value)} placeholder="~ 40" />
                </div>

                <div className={`field ${errors.message ? 'error' : ''}`}>
                  <label>The note <span className="hint">the more the better</span></label>
                  <textarea value={form.message} onChange={e=>set('message', e.target.value)} placeholder="What are we building? Venue in mind? Budget range? Music taste? Anything." />
                  <div className="err">{errors.message}</div>
                </div>

                <div className="field">
                  <div ref={turnstileRef} />
                  {submitError ? <div className="err" style={{display:'block', marginTop:8}}>{submitError}</div> : null}
                </div>

                <div className="submit-row">
                  <div className="note">We'll reply from austin@byace.events within 48h. Your info stays between us.</div>
                  <button type="submit" className="btn-submit" disabled={submitting || !token}>
                    {submitting ? 'Sending…' : <>Send inquiry <span className="arw">→</span></>}
                  </button>
                </div>
              </form>
            ) : (
              <>
                <div className="ticket-head">
                  <div className="t">Received</div>
                  <div className="no">№ {refNo}</div>
                </div>
                <div className="success">
                  <div className="stamp">Received ✓</div>
                  <h3>Thank you, <em>{form.name.split(' ')[0]}.</em></h3>
                  <p style={{fontFamily:'var(--serif)', fontSize:22, lineHeight:1.4, maxWidth:'32ch', textWrap:'balance', opacity:0.85}}>
                    Your message is in. We'll be in touch from <span style={{color:'var(--accent)'}}>austin@byace.events</span> within 48 hours.
                  </p>
                  <div className="refno">Reference № {refNo}</div>
                  <button type="button" className="cta-link" style={{marginTop:16}}
                    onClick={()=>{
                      setSubmitted(false);
                      setForm({name:'',email:'',phone:'',type:'',dateWhen:'',guests:'',message:''});
                      setErrors({});
                      setSubmitError('');
                      setToken('');
                    }}>
                    Send another <span className="arw">→</span>
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      </section>
    </>
  );
}
window.Inquiry = Inquiry;
