/* =============================================================
   Simthetica — Final CTA + dual-mode intake form
   Toggle routes the submission to pilot beta OR data customer.
   ============================================================= */
const { useState: useStateF, useEffect: useEffectF, useRef: useRefF } = React;

/* POST a submission to the serverless endpoint (Vercel function -> Resend). */
const SUBMIT_ENDPOINT = '/api/submit';
async function sendSubmission(payload) {
  const res = await fetch(SUBMIT_ENDPOINT, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    let msg = 'Something went wrong. Please try again.';
    try { const j = await res.json(); if (j && j.error) msg = j.error; } catch (e) {}
    throw new Error(msg);
  }
  return res.json().catch(() => ({}));
}

function Field({ label, required, error, full, children }) {
  return (
    <div className={'field' + (full ? ' full' : '') + (error ? ' has-err' : '')}>
      <label>{label}{required && <span className="req"> *</span>}</label>
      {children}
      <span className="err-msg">{error || 'Required'}</span>
    </div>
  );
}

function Chips({ options, value, onChange }) {
  const toggle = (o) => {
    onChange(value.includes(o) ? value.filter((v) => v !== o) : [...value, o]);
  };
  return (
    <div className="chips">
      {options.map((o) => (
        <button type="button" key={o}
          className={'chip' + (value.includes(o) ? ' on' : '')}
          onClick={() => toggle(o)}>
          <I.Check className="chk" size={13} />{o}
        </button>
      ))}
    </div>
  );
}

function RadioRow({ options, value, onChange }) {
  return (
    <div className="radio-row">
      {options.map((o) => (
        <button type="button" key={o}
          className={'radio-pill' + (value === o ? ' on' : '')}
          onClick={() => onChange(o)}>{o}</button>
      ))}
    </div>
  );
}

/* ---- PILOT FORM -------------------------------------------- */
function PilotForm({ onDone }) {
  const [f, setF] = useStateF({
    name: '', email: '', sim: 'MSFS', experience: '', networks: [],
    aircraft: '', region: '', paid: 'Yes', notes: '',
  });
  const [errs, setErrs] = useStateF({});
  const [busy, setBusy] = useStateF(false);
  const [sendErr, setSendErr] = useStateF(null);
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!f.name.trim()) er.name = 'Required';
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.email)) er.email = 'Enter a valid email';
    if (!f.experience) er.experience = 'Required';
    setErrs(er);
    if (Object.keys(er).length > 0) return;
    setBusy(true); setSendErr(null);
    try {
      await sendSubmission({ type: 'pilot', ...f });
      onDone('pilot');
    } catch (err) {
      setSendErr(err.message || 'Network error — please try again.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <form onSubmit={submit} noValidate>
      <div className="form-head">
        <h3>Apply as a pilot.</h3>
        <p>Tell us how you fly. We are onboarding the first wave of the network now.</p>
      </div>
      <div className="fgrid">
        <Field label="Name" required error={errs.name}>
          <input className={'inp' + (errs.name ? ' err' : '')} value={f.name} onChange={set('name')} placeholder="Your name" />
        </Field>
        <Field label="Email" required error={errs.email}>
          <input className={'inp' + (errs.email ? ' err' : '')} value={f.email} onChange={set('email')} placeholder="you@example.com" type="email" />
        </Field>
        <Field label="Experience level" required error={errs.experience}>
          <select className="sel" value={f.experience} onChange={set('experience')}>
            <option value="">Select…</option>
            <option>Enthusiast — casual realistic flying</option>
            <option>Serious hobbyist — procedures & networks</option>
            <option>Rated private/recreational pilot</option>
            <option>Instructor / professional</option>
          </select>
        </Field>
        <Field label="Virtual ATC experience" full>
          <Chips options={['VATSIM', 'IVAO', 'PilotEdge', 'SayIntentions', 'BeyondATC', 'N/A']}
            value={f.networks} onChange={(v) => setF((s) => ({ ...s, networks: v }))} />
        </Field>
        <Field label="Aircraft usually flown">
          <input className="inp" value={f.aircraft} onChange={set('aircraft')} placeholder="e.g. A320, 737-800, TBM 930" />
        </Field>
        <Field label="Notes" full>
          <textarea className="ta" value={f.notes} onChange={set('notes')} placeholder="Your add-ons stack, hardware, the scenarios you'd most like to fly…"></textarea>
        </Field>
      </div>
      <div className="form-actions">
        <button className="btn btn-primary btn-lg btn-block" type="submit" disabled={busy}>
          {busy ? 'Sending…' : <>Join the pilot beta <I.Arrow size={16} /></>}
        </button>
        {sendErr && <div className="form-error">{sendErr}</div>}
      </div>
    </form>
  );
}

/* ---- DATA CUSTOMER FORM ------------------------------------ */
function DataForm({ onDone }) {
  const [f, setF] = useStateF({
    name: '', email: '', company: '', industry: '', need: '',
    scenarios: '', modalities: [], timeline: '', notes: '',
  });
  const [errs, setErrs] = useStateF({});
  const [busy, setBusy] = useStateF(false);
  const [sendErr, setSendErr] = useStateF(null);
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!f.name.trim()) er.name = 'Required';
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.email)) er.email = 'Enter a valid work email';
    if (!f.company.trim()) er.company = 'Required';
    if (!f.need.trim()) er.need = 'Tell us a little about the data need';
    setErrs(er);
    if (Object.keys(er).length > 0) return;
    setBusy(true); setSendErr(null);
    try {
      await sendSubmission({ type: 'data', ...f });
      onDone('data');
    } catch (err) {
      setSendErr(err.message || 'Network error — please try again.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <form onSubmit={submit} noValidate>
      <div className="form-head">
        <h3>Tell us what aviation data you need.</h3>
        <p>We scope scenario-specific data to fit your requirements.</p>
      </div>
      <div className="fgrid">
        <Field label="Name" required error={errs.name}>
          <input className={'inp' + (errs.name ? ' err' : '')} value={f.name} onChange={set('name')} placeholder="Your name" />
        </Field>
        <Field label="Work email" required error={errs.email}>
          <input className={'inp' + (errs.email ? ' err' : '')} value={f.email} onChange={set('email')} placeholder="you@company.com" type="email" />
        </Field>
        <Field label="Company / organization" required error={errs.company} full>
          <input className={'inp' + (errs.company ? ' err' : '')} value={f.company} onChange={set('company')} placeholder="Organization name" />
        </Field>
        <Field label="Industry category" full>
          <select className="sel" value={f.industry} onChange={set('industry')}>
            <option value="">Select…</option>
            <option>Aviation autonomy / avionics</option>
            <option>Airport surface safety</option>
            <option>Aviation AI / world models</option>
            <option>Flight training & safety analytics</option>
            <option>Simulation / synthetic-data team</option>
            <option>Research / academia</option>
            <option>Other</option>
          </select>
        </Field>
        <Field label="Data need" required error={errs.need} full>
          <textarea className={'ta' + (errs.need ? ' err' : '')} value={f.need} onChange={set('need')} placeholder="What are you building, and what behavior or scenarios do you need to capture?"></textarea>
        </Field>
        <Field label="Desired scenarios" full>
          <input className="inp" value={f.scenarios} onChange={set('scenarios')} placeholder="e.g. low-vis taxi, runway incursions, unstable approaches" />
        </Field>
        <Field label="Modalities needed" full>
          <Chips options={['Telemetry', 'Video', 'Cockpit view', 'ATC / comms', 'Pilot actions', 'Labels', 'Scenario metadata']}
            value={f.modalities} onChange={(v) => setF((s) => ({ ...s, modalities: v }))} />
        </Field>
        <Field label="Timeline" full>
          <RadioRow options={['Exploring', 'This quarter', 'Active project']} value={f.timeline} onChange={(v) => setF((s) => ({ ...s, timeline: v }))} />
        </Field>
        <Field label="Notes" full>
          <textarea className="ta" value={f.notes} onChange={set('notes')} placeholder="Volume, format, licensing constraints, anything else…"></textarea>
        </Field>
      </div>
      <div className="form-actions">
        <button className="btn btn-primary btn-lg btn-block" type="submit" disabled={busy} style={{ background: 'var(--indigo-200)' }}>
          {busy ? 'Sending…' : <>Inquire about data <I.Arrow size={16} /></>}
        </button>
        {sendErr && <div className="form-error">{sendErr}</div>}
        <div className="form-note">
          <I.Shield size={13} /> Every trace ships with scenario provenance and rights-cleared consent records.
        </div>
      </div>
    </form>
  );
}

/* ---- SUCCESS ------------------------------------------------ */
function Success({ mode, onReset }) {
  const ref = 'SIM-' + Math.random().toString(36).slice(2, 7).toUpperCase();
  return (
    <div className="form-success">
      <div className="seal"><I.CheckCircle size={34} /></div>
      <h3>{mode === 'pilot' ? 'Welcome aboard, pilot.' : 'Request received.'}</h3>
      <p>
        {mode === 'pilot'
          ? 'Your application is logged. We will reach out as the next wave of the pilot beta opens — bring your favorite aircraft.'
          : 'Your data request is logged. Our team will follow up to scope scenarios, modalities, and provenance for your project.'}
      </p>
      <p className="ref">Reference · {ref}</p>
      <button className="btn btn-ghost" onClick={onReset} style={{ marginTop: 'var(--space-5)' }}>
        Submit another response
      </button>
    </div>
  );
}

/* ---- FINAL CTA SHELL --------------------------------------- */
function FinalCTA({ mode, setMode, registerScroll }) {
  const [submitted, setSubmitted] = useStateF(null);
  const ref = useRefF(null);
  useEffectF(() => { if (registerScroll) registerScroll(ref); }, [registerScroll]);

  const onDone = (m) => {
    setSubmitted(m);
    if (ref.current) window.scrollTo({ top: ref.current.offsetTop - 64, behavior: 'smooth' });
  };

  return (
    <section className="final" id="beta" ref={ref}>
      <div className="wrap">
        <div className="final-card">
          <div className="final-grid">
            <div className="final-intro">
              <p>Join the beta</p>
              <h2>Two ways into Simthetica.</h2>
              <p>
                Whether you are a pilot who wants your simulator time to contribute to something
                larger, or an organization looking for structured aviation scenario data,
                Simthetica is building its early network now.
              </p>
              <div className="why">
                <div className="row"><I.Plane size={14} /> Fly the scenarios automation cannot script alone</div>
                <div className="row"><I.Database size={14} /> Source-tagged, rights-cleared traces</div>
                <div className="row"><I.Shield size={14} /> Consent on both sides of the marketplace</div>
              </div>
            </div>

            <div className="final-form">
              {!submitted && (
                <div className="seg" role="tablist" aria-label="Choose path">
                  <button className={'pilot' + (mode === 'pilot' ? ' active pilot' : '')}
                    onClick={() => setMode('pilot')} role="tab" aria-selected={mode === 'pilot'}>
                    <I.Plane size={16} /> I’m a pilot
                  </button>
                  <button className={'data' + (mode === 'data' ? ' active data' : '')}
                    onClick={() => setMode('data')} role="tab" aria-selected={mode === 'data'}>
                    <I.Database size={16} /> I need data
                  </button>
                </div>
              )}
              {submitted
                ? <Success mode={submitted} onReset={() => setSubmitted(null)} />
                : (mode === 'pilot' ? <PilotForm onDone={onDone} /> : <DataForm onDone={onDone} />)}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { FinalCTA });
