/* ---------- Demo request form ----------
   Pulled out of <Waitlist> so the same form can render in two
   contexts:
     - Inline (desktop) — embedded in the waitlist section's right column
     - Modal (mobile)   — fullscreen overlay triggered by Book a demo CTAs
   The rotating placeholder for the production field lives here so it
   keeps animating wherever the form is mounted. */
function DemoForm({ onClose, idPrefix = 'wl' }) {
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');
  const [form, setForm] = React.useState({
    name: '',
    email: '',
    role: 'Line Producer',
    stage: 'Development',
    needs: '',
  });

  const onSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setError('');
    setSubmitting(true);
    try {
      const res = await fetch('/api/lead', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          company: form.role,
          message: `Stage: ${form.stage}\n\n${form.needs}`,
          source: 'waitlist',
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || `Request failed (${res.status})`);
      }
      setSubmitted(true);
    } catch (err) {
      setError(err.message || 'Something went wrong. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <form className="waitlist-form" onSubmit={onSubmit}>
      <div className="stripe">
        <span className="dot"></span>
        Request a demo
      </div>

      {!submitted ? (
        <>
          <div className="field">
            <label htmlFor={`${idPrefix}-name`}>Your name</label>
            <input id={`${idPrefix}-name`} type="text" required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="First Last" autoComplete="name" />
          </div>
          <div className="field">
            <label htmlFor={`${idPrefix}-email`}>Work email</label>
            <input id={`${idPrefix}-email`} type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="you@studio.com" autoComplete="email" />
          </div>
          <div className="field-row">
            <div className="field">
              <label htmlFor={`${idPrefix}-role`}>Your role</label>
              <select id={`${idPrefix}-role`} value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })}>
                <option>Line Producer</option>
                <option>UPM</option>
                <option>1st AD</option>
                <option>2nd AD</option>
                <option>Production Accountant</option>
                <option>Studio / Exec</option>
                <option>Other</option>
              </select>
            </div>
            <div className="field">
              <label htmlFor={`${idPrefix}-stage`}>Production stage</label>
              <select id={`${idPrefix}-stage`} value={form.stage} onChange={(e) => setForm({ ...form, stage: e.target.value })}>
                <option>Development</option>
                <option>Pre-production</option>
                <option>In production</option>
                <option>Post-production</option>
                <option>Not active</option>
              </select>
            </div>
          </div>
          <div className="field">
            <label htmlFor={`${idPrefix}-needs`}>What are you hoping Krew will do for you?</label>
            <input
              id={`${idPrefix}-needs`}
              type="text"
              value={form.needs}
              onChange={(e) => setForm({ ...form, needs: e.target.value })}
              maxLength={140}
            />
          </div>
          <button type="submit" className="btn spark" disabled={submitting} style={{ width: '100%', justifyContent: 'center', marginTop: 8, opacity: submitting ? 0.6 : 1 }}>
            {submitting ? 'Sending…' : 'Book a demo'}
            {!submitting && <svg aria-hidden="true" focusable="false" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7" /></svg>}
          </button>
          {error && <p role="alert" style={{ fontSize: 12, color: 'var(--danger, #b8371c)', textAlign: 'center', marginTop: 10 }}>{error}</p>}
          <p style={{ fontSize: 11, color: 'var(--fg-4)', textAlign: 'center', marginTop: 14, letterSpacing: 0.4 }}>We read every request. We also reply to every one.</p>
        </>
      ) : (
        <div className="success-stamp">
          <div className="k">
            <img src="/assets/logo-k-spark.png" alt="" />
          </div>
          <h3 style={{ fontSize: 'var(--fs-30)', fontWeight: 900, letterSpacing: '-0.02em' }}>Got it.</h3>
          <p style={{ marginBottom: 18 }}>One of the founders will reply within 48 hours — usually faster.</p>
          <div className="hand-note font-script" style={{ fontSize: 28, transform: 'rotate(-3deg)', display: 'inline-block' }}>
            — The Krew
          </div>
          {onClose && (
            <button type="button" className="btn ghost" style={{ marginTop: 22 }} onClick={onClose}>Close</button>
          )}
        </div>
      )}
    </form>
  );
}

/* ---------- Demo modal ----------
   Fullscreen overlay that hosts the demo form on mobile. Mounted at
   the root of <App/> and shown by listening for any click on an
   anchor whose href ends with #demo. On wider screens the click
   is left alone (browser scrolls to the inline form as before).
   Esc closes; backdrop click closes; body scroll is locked while open. */
function DemoModal() {
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    const isMobile = () => window.matchMedia('(max-width: 720px)').matches;

    const onClick = (e) => {
      if (!isMobile()) return;
      const a = e.target.closest('a[href*="#demo"], a[href*="#book-demo"]');
      if (!a) return;
      // Allow modifier-clicks / new-tab through.
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button === 1) return;
      e.preventDefault();
      setOpen(true);
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);

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

  if (!open) return null;

  return ReactDOM.createPortal(
    <div className="demo-modal" role="dialog" aria-modal="true" aria-label="Demo request" onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}>
      <div className="demo-modal-panel">
        <button type="button" className="demo-modal-close" aria-label="Close" onClick={() => setOpen(false)}>
          <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
            <path d="M6 6l12 12M18 6L6 18" />
          </svg>
        </button>
        <DemoForm idPrefix="wl-modal" onClose={() => setOpen(false)} />
      </div>
    </div>,
    document.body
  );
}

function Waitlist() {
  return (
    <section className="section" id="demo" style={{ background: 'var(--krew-grain-warm)', borderTop: '1px solid var(--border-hair)', padding: '50px 0px 80px', scrollMarginTop: '60px' }}>
      <div className="container">
        <div className="waitlist-wrap">
          <div className="reveal">
            <span className="eyebrow-row"><i className="dot"></i>Next step</span>
            <h2 style={{ marginTop: 14, fontSize: 'clamp(36px, 4.6vw, 72px)', fontWeight: 900, letterSpacing: '-0.03em', lineHeight: 1, textWrap: 'pretty' }}>Ready to <span className="demo-hand-accent">spot&nbsp;trouble</span> early?</h2>
            <p style={{ marginTop: 20, fontSize: 'var(--fs-18)', color: 'var(--fg-2)', lineHeight: 1.55, maxWidth: 520 }}>Krew is accepting a limited number of early production partners. If you've got a slate getting green-lit or a production in early prep, now is the right time to talk.</p>

            <Testimonial compact={true} />

            {/* Mobile-only CTA — the inline form is hidden on mobile;
                this button opens the fullscreen demo modal instead.
                Sits below the testimonial so social proof leads into
                the ask, and the button is the last thing standing. */}
            <a href="#demo" className="btn spark waitlist-mobile-cta">
              Book a demo
              <svg aria-hidden="true" focusable="false" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7" /></svg>
            </a>
          </div>

          <div className="waitlist-form-wrap reveal">
            <DemoForm />
          </div>
        </div>
      </div>
    </section>
  );
}

window.Waitlist = Waitlist;
window.DemoModal = DemoModal;
