/* global React */
const { useState, useRef } = React;

const HOURS = ["Under 100", "100–500", "500–2,000", "2,000–5,000", "5,000+"];
const WORTH = ["Under $5", "$5–10", "$10–15", "$15–20", "$20+", "Not sure yet"];

function validEmail(v) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim()); }

function Check() {
  return <svg viewBox="0 0 24 24"><path d="M5 13l4 4L19 7"/></svg>;
}

function WaitlistForm({ fieldStyle = "boxed", hoursStyle = "chips", showDeal = true, onSubmit, lockedEmail = "", onSkip, onChangeEmail, busy = false }) {
  const [email, setEmail] = useState("");
  const [save, setSave] = useState("");
  const [hours, setHours] = useState("");
  const [tools, setTools] = useState("");
  const [worth, setWorth] = useState("");
  const [wish, setWish] = useState("");
  const [hangout, setHangout] = useState("");
  const [chat, setChat] = useState(false);
  const [tried, setTried] = useState(false);

  const locked = !!lockedEmail;
  const emailOk = locked ? true : validEmail(email);
  const saveOk = save.trim().length >= 4;
  const wishOk = wish.trim().length >= 4;
  const hoursOk = !!hours;
  const ok = emailOk && saveOk && wishOk && hoursOk;

  const submit = (e) => {
    e.preventDefault();
    setTried(true);
    if (ok && !busy) onSubmit({ email: lockedEmail || email, save, hours, tools, worth, wish, hangout, chat });
  };

  const wrapClass = "form-card" + (fieldStyle === "underlined" ? " underlined" : "");

  return (
    <form className={wrapClass} onSubmit={submit} noValidate>
      {/* 1 — email: captured in step 1, shown as a confirmation banner when locked */}
      {locked ? (
        <div className="onlist">
          <span className="onlist-check"><Check /></span>
          <span className="onlist-txt">You’re on the list as <b>{lockedEmail}</b>
            {onChangeEmail && <a onClick={onChangeEmail}>change</a>}</span>
        </div>
      ) : (
        <div className="field">
          <label htmlFor="w-email">Email<span className="req">*</span></label>
          <span className="help">Where we’ll reach you if there’s a seat. No spam, ever.</span>
          <input id="w-email" className={"inp" + (tried && !emailOk ? " err" : "")} type="email"
            placeholder="you@example.com" autoComplete="email"
            value={email} onChange={(e) => setEmail(e.target.value)} />
          {tried && !emailOk && <div className="field-err">Enter a valid email so we can reach you.</div>}
        </div>
      )}

      {/* 2 — current save */}
      <div className="field">
        <label htmlFor="w-save">Tell us about your current save<span className="req">*</span></label>
        <span className="help">Club, league, and how many seasons deep.</span>
        <textarea id="w-save" className={"ta" + (tried && !saveOk ? " err" : "")}
          placeholder="e.g. Real Zaragoza, La Liga 2 → promoted twice, 14 seasons in…"
          value={save} onChange={(e) => setSave(e.target.value)} />
        {tried && !saveOk && <div className="field-err">A sentence or two is plenty.</div>}
      </div>

      {/* 3 — hours */}
      <div className="field">
        <span className="qlabel">Roughly how many hours in FM?<span className="req">*</span></span>
        <span className="help">Lifetime, all editions. Round numbers are fine.</span>
        {hoursStyle === "chips" ? (
          <div className="chips">
            {HOURS.map(h => (
              <span key={h} className={"chip" + (hours === h ? " on" : "")}
                onClick={() => setHours(h)}>{h}</span>
            ))}
          </div>
        ) : (
          <select className="inp" value={hours} onChange={(e) => setHours(e.target.value)}>
            <option value="" disabled>Choose a range…</option>
            {HOURS.map(h => <option key={h} value={h}>{h} hours</option>)}
          </select>
        )}
        {tried && !hoursOk && <div className="field-err">Pick the closest range.</div>}
      </div>

      {/* 4 — tools */}
      <div className="field">
        <label htmlFor="w-tools">Do you use an assistant or AI tools alongside your save?<span className="opt">Optional</span></label>
        <span className="help">Which ones, and what for? (ChatGPT for tactics, a wonderkid spreadsheet, nothing yet. All useful to know.)</span>
        <input id="w-tools" className="inp" type="text"
          placeholder="e.g. ChatGPT for pre-match opposition notes"
          value={tools} onChange={(e) => setTools(e.target.value)} />
      </div>

      {/* worth — optional, non-binding price signal (research only, nothing charged) */}
      <div className="field">
        <span className="qlabel">If Hinru existed today, what would it be worth to you?<span className="opt">Optional</span></span>
        <span className="help">Per month. You haven’t seen it work yet, so “not sure” is a perfectly good answer. Nothing is charged now, or at all at this stage. It just helps us price it fairly when the time comes.</span>
        <div className="chips">
          {WORTH.map(w => (
            <span key={w} className={"chip" + (worth === w ? " on" : "")}
              onClick={() => setWorth(v => v === w ? "" : w)}>{w}</span>
          ))}
        </div>
      </div>

      {/* 5 — the open box (flagship) */}
      <div className="field flagship">
        <div className="flag-rule"></div>
        <span className="flag-eyebrow">What you’d keep</span>
        <span className="qlabel">What do you wish your assistant remembered about your <span className="nowrap">save?<span className="req">*</span></span></span>
        <span className="help">The thing you keep re-explaining, the rule you play by, the history that should carry. Say it however you’d say it.</span>
        <textarea className={"ta" + (tried && !wishOk ? " err" : "")}
          placeholder="The promise I made to the academy kid. Why I never sign a target man. That we’re a counter-attacking side, not whatever the assistant suggests…"
          value={wish} onChange={(e) => setWish(e.target.value)} maxLength={600} />
        <div className="counter">{wish.length}/600</div>
        {tried && !wishOk && <div className="field-err">This one matters most. Give us a line.</div>}
      </div>

      {/* 6 — hangout */}
      <div className="field">
        <label htmlFor="w-hang">Where do you hang out, FM-wise?<span className="opt">Optional</span></label>
        <span className="help">Subreddits, Discords, YouTubers, forums. Wherever you talk shop.</span>
        <input id="w-hang" className="inp" type="text"
          placeholder="r/footballmanagergames, a tactics Discord, Zealand…"
          value={hangout} onChange={(e) => setHangout(e.target.value)} />
      </div>

      {/* 7 — optional chat */}
      <div className="field">
        <div className={"check" + (chat ? " on" : "")} onClick={() => setChat(c => !c)}
          role="checkbox" aria-checked={chat} tabIndex={0}
          onKeyDown={(e) => { if (e.key === " " || e.key === "Enter") { e.preventDefault(); setChat(c => !c); } }}>
          <span className="box"><Check /></span>
          <span className="ctxt"><b>I’d be up for a 20-minute chat about my save.</b>
            <small>Optional. A real conversation helps us build the right thing, and gets you a closer look at the cohort.</small></span>
        </div>
      </div>

      <div className="rule"></div>
      <button className="submit" type="submit" disabled={(tried && !ok) || busy}>{busy ? "Sending…" : (locked ? "Send my answers" : "Join the waitlist")}</button>
      {onSkip && <button type="button" className="skip" disabled={busy} onClick={() => !busy && onSkip({ email: lockedEmail || email, save, hours, tools, worth, wish, hangout, chat, partial: true })}>Skip · just notify me at launch</button>}

      {showDeal && (
        <div className="deal">
          <p className="deal-head">If you make the cohort, here’s the deal</p>
          <div className="deal-grid">
            <div className="deal-item">
              <p className="dt">Free for the beta term</p>
              <p className="dd">Run it alongside your save. Free through beta plus a grace window, not free forever, on purpose.</p>
            </div>
            <div className="deal-item">
              <p className="dt">Honest reactions</p>
              <p className="dd">A light weekly check-in and one ~30-minute chat. Telling us what’s broken is the payment.</p>
            </div>
            <div className="deal-item">
              <p className="dt">We ask before we quote</p>
              <p className="dd">Never a testimonial-for-access trade. If you say something we love, we ask first, with your sign-off each time.</p>
            </div>
            <div className="deal-item">
              <p className="dt">First crack at pricing</p>
              <p className="dd">When founding-member pricing opens, beta testers get grandfathered first. You decide if it’s worth paying for.</p>
            </div>
          </div>
          <p className="deal-honest">The deal is <b>honesty, not praise.</b> A tester who owes us a nice word gives us “nice,” and nice is the most expensive thing a beta can produce.</p>
        </div>
      )}
    </form>
  );
}

function Confirmation({ data, onFinish }) {
  const masked = data.email;
  const answered = !!data.save && !data.partial;
  // Real waitlist spot (OD-523). One real count — Jack is №1 — so the number is
  // a genuine badge. If the count read failed we show no number rather than a
  // fake one (the brand is "keeps what's real").
  const spot = Number.isInteger(data.position) && data.position > 0 ? data.position : null;
  return (
    <div className="confirm">
      <p className="eyebrow"><span className="dot"></span>{answered ? "Beta application received" : "You’re on the list"}</p>
      <h1 className="stamp">You’re on <span className="g">the list.</span></h1>
      {answered
        ? <p className="sub">We read <b>every</b> answer, yours included. If your save is a fit for the first cohort, you’ll hear from us at <b>{masked}</b>.</p>
        : <p className="sub">Your spot’s saved. We’ll email you the moment we launch. Want to help shape your FM Backroom? Apply to be a beta tester.</p>}

      <div className="receipt">
        <div className="rtop">
          <span>Waitlist receipt</span>
          {spot && <span className="rnum">№ {spot}</span>}
        </div>
        <div className="rline"><span className="rk">●</span> Your spot on the list <span className="rv">secured</span></div>
        {data.save && <div className="rline"><span className="rk">↻</span> Your save, in your words <span className="rv">filed</span></div>}
        {data.worth && <div className="rline"><span className="rk">◇</span> What it’s worth to you <span className="rv">logged</span></div>}
        {data.chat && <div className="rline"><span className="rk">◆</span> Up for a 20-min chat <span className="rv">noted</span></div>}
      </div>

      <div className="next">
        <h3>What happens next</h3>
        {answered ? (
          <ol>
            <li>We read applications in batches and <b>hand-pick the first cohort</b>: long-save players first.</li>
            <li>If you’re in, you’ll get an email with a <b>sign-in code</b> and your beta term.</li>
            <li>No seat this round? Your answers still shape the product. We keep the list warm and widen the door over time.</li>
          </ol>
        ) : (
          <ol>
            <li>You’re on the <b>launch list</b>. We’ll email you the moment Hinru opens.</li>
            <li>Want in earlier? <b>Beta testers get first access.</b></li>
          </ol>
        )}
      </div>

      {answered
        ? <p className="confirm-honest">Thanks for the detail. <b>The words you just wrote</b> are exactly how we learn what a backroom should remember.</p>
        : <div className="confirm-finish">
            <button className="submit" type="button" onClick={onFinish}>Apply to beta test</button>
            <p className="subnote">Two minutes, and we read every answer.</p>
          </div>}
    </div>
  );
}

Object.assign(window, { WaitlistForm, Confirmation });
