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

// ============ Icons ============
const Icon = {
  arrow: () => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  back: () => <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M11 5l-7 7 7 7"/></svg>,
  check: () => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>,
  pulse: () => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>,
  spark: () => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v6M12 16v6M2 12h6M16 12h6M5 5l4 4M15 15l4 4M5 19l4-4M15 9l4-4"/></svg>,
  shield: () => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2 4 5v7c0 5 3.5 9 8 10 4.5-1 8-5 8-10V5l-8-3z"/></svg>,
  copy: () => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>,
  x: () => <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>,
  link: () => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>,
  msg: () => <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8z"/></svg>,
  lock: () => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>,
  bolt: () => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2 3 14h7l-1 8 10-12h-7l1-8z"/></svg>,
  crown: () => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="m3 20 2-11 5 4 4-8 4 8 5-4 2 11z"/><path d="M3 20h18"/></svg>,
  phone: () => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92z"/></svg>,
  community: () => <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="8" r="3"/><path d="M2 20c.6-3 3.4-5 7-5s6.4 2 7 5"/><circle cx="17" cy="6" r="2.5"/><path d="M22 18c-.3-1.8-1.8-3-4-3.3"/></svg>,
};

// ============ Sport chips ============
const SPORTS = [
  { id: 'soccer', name: 'Soccer' },
  { id: 'basketball', name: 'Basketball' },
  { id: 'football', name: 'Football' },
  { id: 'tennis', name: 'Tennis' },
  { id: 'baseball', name: 'Baseball' },
  { id: 'volleyball', name: 'Volleyball' },
  { id: 'rugby', name: 'Rugby' },
  { id: 'running', name: 'Running / Track' },
  { id: 'cycling', name: 'Cycling' },
  { id: 'mma', name: 'MMA / Combat' },
  { id: 'swimming', name: 'Swimming' },
  { id: 'golf', name: 'Golf' },
  { id: 'hockey', name: 'Hockey' },
  { id: 'other', name: 'Other' },
];

const LEVELS = [
  { id: 'amateur',  name: 'Amateur',          meta: 'Train hard. Play for the love.' },
  { id: 'semipro',  name: 'Semi-Pro',         meta: 'Competing at a high level.' },
  { id: 'pro',      name: 'Professional',     meta: 'Pro contract. Pro standards.' },
  { id: 'ncaa',     name: 'NCAA / College',   meta: 'Division I, II or III athlete.' },
  { id: 'academy',  name: 'Academy / Youth',  meta: 'Club academy or development.' },
];

const WEARABLES = [
  { id: 'apple',  name: 'Apple Watch', meta: 'Series 6+ / Ultra' },
  { id: 'whoop',  name: 'WHOOP',       meta: '4.0 / MG band' },
  { id: 'garmin', name: 'Garmin',      meta: 'Forerunner · Fenix · Venu' },
  { id: 'oura',   name: 'Oura Ring',   meta: 'Gen 3 · Gen 4' },
  { id: 'polar',  name: 'Polar',       meta: 'Vantage · H10' },
  { id: 'none',   name: 'None yet',    meta: 'I track manually.' },
];

const wearableIcon = (id) => {
  const C = "currentColor";
  switch (id) {
    case 'apple':  return <svg viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth="1.5"><rect x="7" y="5" width="10" height="14" rx="3"/><path d="M9 5V3h6v2M9 19v2h6v-2"/></svg>;
    case 'whoop':  return <svg viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth="1.5"><path d="M4 12c0-2 2-3 4-3s3 1 4 3 2 3 4 3 4-1 4-3"/><path d="M4 16c0-2 2-3 4-3s3 1 4 3 2 3 4 3 4-1 4-3"/></svg>;
    case 'garmin': return <svg viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth="1.5"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="3"/><path d="M12 5V3M12 21v-2M5 12H3M21 12h-2"/></svg>;
    case 'oura':   return <svg viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth="1.5"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="4" strokeDasharray="2 2"/></svg>;
    case 'polar':  return <svg viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth="1.5"><circle cx="12" cy="12" r="8"/><path d="M8 12c1-1 2-1 3-1s3 0 4-1M8 14c1-1 2-1 3-1s3 0 4-1"/></svg>;
    case 'none':   return <svg viewBox="0 0 24 24" fill="none" stroke={C} strokeWidth="1.5"><path d="M4 4l16 16M8 6h8a3 3 0 0 1 3 3v6M5 9v6a3 3 0 0 0 3 3h8"/></svg>;
    default: return null;
  }
};

// ============ Steps ============
const STEPS = [
  { id: 'identity', eyebrow: 'Step 01 · Identity' },
  { id: 'sport',    eyebrow: 'Step 02 · Sport' },
  { id: 'level',    eyebrow: 'Step 03 · Level' },
  { id: 'wearable', eyebrow: 'Step 04 · Hardware' },
  { id: 'why',      eyebrow: 'Step 05 · Motive' },
  { id: 'contact',  eyebrow: 'Step 06 · Community' },
];

// ============ WaitlistForm ============
function WaitlistForm({ onSubmit, submitting, submitError }) {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    name: '', email: '', sport: '', sportOther: '',
    level: '', wearable: '', why: '', phone: '',
  });
  const setField = (k, v) => setData(d => ({ ...d, [k]: v }));

  const canAdvance = useMemo(() => {
    switch (STEPS[step].id) {
      case 'identity': return data.name.trim().length >= 2 && /\S+@\S+\.\S+/.test(data.email);
      case 'sport':    return data.sport && (data.sport !== 'other' || data.sportOther.trim().length > 1);
      case 'level':    return !!data.level;
      case 'wearable': return !!data.wearable;
      case 'why':      return data.why.trim().length >= 8;
      case 'contact':  return true;
      default:         return false;
    }
  }, [step, data]);

  const next = () => {
    if (!canAdvance) return;
    if (step < STEPS.length - 1) setStep(step + 1);
    else onSubmit(data);
  };
  const back = () => step > 0 && setStep(step - 1);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') {
        e.preventDefault();
        next();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  });

  const cur = STEPS[step];

  return (
    <div className="formcard">
      <div className="form-head">
        <div className="label mono">// Waitlist · Founding 100</div>
        <div className="step-count mono">
          <b>{String(step + 1).padStart(2, '0')}</b> / {String(STEPS.length).padStart(2, '0')}
        </div>
      </div>
      <div className="progress">
        {STEPS.map((s, i) => (
          <div key={s.id} className={`seg ${i < step ? 'done' : ''} ${i === step ? 'active' : ''}`}>
            <div className="fill" />
          </div>
        ))}
      </div>

      <div className="step-body">
        <div className="step-anim" key={step}>
          <div className="step-eyebrow mono">{cur.eyebrow}</div>
          {step === 0 && <StepIdentity data={data} setField={setField} />}
          {step === 1 && <StepSport    data={data} setField={setField} />}
          {step === 2 && <StepLevel    data={data} setField={setField} />}
          {step === 3 && <StepWearable data={data} setField={setField} />}
          {step === 4 && <StepWhy      data={data} setField={setField} />}
          {step === 5 && <StepContact  data={data} setField={setField} />}
        </div>
      </div>

      {submitError && (
        <div style={{margin: '0 0 12px', padding: '10px 14px', borderRadius: 10,
          background: 'rgba(255,69,96,0.1)', border: '1px solid rgba(255,69,96,0.3)',
          color: '#FF4560', fontSize: 13}}>
          {submitError}
        </div>
      )}
      <div className="form-foot">
        <button className="btn ghost" onClick={back} disabled={step === 0 || submitting}>
          <Icon.back /> Back
        </button>
        <div className="foot-meta mono">PRESS <kbd>ENTER</kbd> TO CONTINUE</div>
        <button className="btn primary" onClick={next} disabled={!canAdvance || submitting}>
          {submitting ? 'Sending…' : step === STEPS.length - 1 ? 'Claim my spot' : 'Continue'}
          {!submitting && <span className="arrow"><Icon.arrow /></span>}
        </button>
      </div>
    </div>
  );
}

// ============ Step components ============
function StepIdentity({ data, setField }) {
  return (
    <>
      <h2 className="step-q">Welcome, athlete. What do we <em>call you?</em></h2>
      <p className="step-help">We'll use your name for early access invites and your email to send your onboarding kit. No spam — only when LE-G3N is ready for you.</p>
      <div className="field-stack">
        <div className="text-field">
          <label>Full name</label>
          <input value={data.name} onChange={e => setField('name', e.target.value)} placeholder="Sofía Hernández" autoFocus />
        </div>
        <div className="text-field">
          <label>Email</label>
          <input type="email" value={data.email} onChange={e => setField('email', e.target.value)} placeholder="you@team.com" />
        </div>
      </div>
    </>
  );
}

function StepSport({ data, setField }) {
  return (
    <>
      <h2 className="step-q">Your sport <em>defines</em> your recovery curve.</h2>
      <p className="step-help">LE-G3N adapts its HRV models, load thresholds and game-day protocols to your discipline. Pick the one you compete in most.</p>
      <div className="chips">
        {SPORTS.map(s => (
          <button key={s.id} className={`chip ${data.sport === s.id ? 'selected' : ''}`}
                  onClick={() => setField('sport', s.id)}>
            <span className="dot" />
            {s.name}
          </button>
        ))}
      </div>
      {data.sport === 'other' && (
        <div className="field-stack" style={{ marginTop: 18 }}>
          <div className="text-field">
            <label>Tell us your sport</label>
            <input value={data.sportOther} onChange={e => setField('sportOther', e.target.value)}
                   placeholder="e.g. Padel, Squash, Climbing…" autoFocus />
          </div>
        </div>
      )}
    </>
  );
}

function StepLevel({ data, setField }) {
  return (
    <>
      <h2 className="step-q">How <em>seriously</em> do you compete?</h2>
      <p className="step-help">Only 100 athletes get in. We prioritize founding access by intensity — but every level shapes the product. Your answer here tells us where your data fits in the model.</p>
      <div className="option-grid" style={{ marginTop: 28 }}>
        {LEVELS.map(l => (
          <button key={l.id} className={`option ${data.level === l.id ? 'selected' : ''}`}
                  onClick={() => setField('level', l.id)}>
            <div className="opt-icon"><Icon.spark /></div>
            <div className="opt-body">
              <div className="opt-name">{l.name}</div>
              <div className="opt-meta mono">{l.meta}</div>
            </div>
          </button>
        ))}
      </div>
    </>
  );
}

function StepWearable({ data, setField }) {
  return (
    <>
      <h2 className="step-q">What's on your <em>wrist?</em></h2>
      <p className="step-help">HRV, sleep and load data pipe straight into LE-G3N. Tell us your hardware so we can have your dashboard live the moment you sign in.</p>
      <div className="option-grid cols-2" style={{ marginTop: 28 }}>
        {WEARABLES.map(w => (
          <button key={w.id} className={`option ${data.wearable === w.id ? 'selected' : ''}`}
                  onClick={() => setField('wearable', w.id)}>
            <div className="opt-icon">{wearableIcon(w.id)}</div>
            <div className="opt-body">
              <div className="opt-name">{w.name}</div>
              <div className="opt-meta mono">{w.meta}</div>
            </div>
          </button>
        ))}
      </div>
    </>
  );
}

function StepWhy({ data, setField }) {
  return (
    <>
      <h2 className="step-q">Why does LE-G3N <em>matter</em> to you?</h2>
      <p className="step-help">One or two sentences. What problem are you trying to solve — overtraining, injury recovery, game-day readiness, edge over rivals? Your words shape what we build first.</p>
      <div className="field-stack">
        <div className="text-field">
          <label>Your story</label>
          <textarea value={data.why} onChange={e => setField('why', e.target.value)}
                    placeholder="I keep peaking in training and showing up flat on game day. I want to know exactly when my body is ready to push…"
                    rows={4} />
        </div>
      </div>
    </>
  );
}

function StepContact({ data, setField }) {
  return (
    <>
      <h2 className="step-q">Join the <em>Founding Athletes</em> community?</h2>
      <p className="step-help">Get direct access to the LE-G3N team, early features, and a private group of athletes who take recovery seriously. Drop your number for the invite — fully optional, never shared, never used for marketing.</p>
      <div className="field-stack">
        <div className="text-field">
          <label>Phone</label>
          <input type="tel" value={data.phone} onChange={e => setField('phone', e.target.value)}
                 placeholder="+1 (555) 010-0420" />
          <span className="suffix optional mono">OPTIONAL</span>
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', color: 'var(--text-dim)', fontSize: 12, marginTop: 4 }}>
          <Icon.shield /> Encrypted in transit. Used only for the Founding Athletes invite.
        </div>
      </div>
    </>
  );
}

// ============ Success ============
function Success({ data }) {
  const refcode = useMemo(() => {
    const first = (data.name || 'ATHLETE').split(' ')[0].toUpperCase().replace(/[^A-Z]/g, '').slice(0, 6);
    const tail = Math.random().toString(36).slice(2, 6).toUpperCase();
    return `LEG3N-${first}-${tail}`;
  }, [data.name]);

  const [copied, setCopied] = useState(false);
  const copy = () => {
    navigator.clipboard?.writeText(refcode);
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };

  return (
    <div className="formcard">
      <div className="form-head">
        <div className="label mono">// Confirmed · Early access unlocked</div>
        <div className="step-count mono"><b>06</b> / 06</div>
      </div>
      <div className="progress">
        {STEPS.map(s => <div key={s.id} className="seg done"><div className="fill" /></div>)}
      </div>

      <div className="success step-anim">
        <div className="check"><Icon.check /></div>
        <h2>You're <em>early</em>, {(data.name || 'athlete').split(' ')[0]}.</h2>
        <p className="lede">
          A confirmation just landed in <b style={{ color: 'var(--text)' }}>{data.email}</b>.
          You signed up before the crowd — and that comes with permanent advantages most athletes will never get.
        </p>

        <div className="perks-card">
          <div className="perks-head">
            <div className="perks-badge mono">
              <span className="status-dot"></span> EARLY ATHLETE · UNLOCKED
            </div>
            <div className="perks-meta mono">FOR LIFE</div>
          </div>
          <div className="perks-list">
            <div className="perk">
              <div className="perk-ico"><Icon.lock /></div>
              <div className="perk-body">
                <div className="perk-ttl">Founding pricing, locked forever</div>
                <div className="perk-sub">When public pricing launches, your rate stays where it started. Never goes up.</div>
              </div>
            </div>
            <div className="perk">
              <div className="perk-ico"><Icon.bolt /></div>
              <div className="perk-body">
                <div className="perk-ttl">First in line when the doors open</div>
                <div className="perk-sub">You skip the public waitlist. Your invite lands before LE-G3N is announced anywhere.</div>
              </div>
            </div>
            <div className="perk">
              <div className="perk-ico"><Icon.crown /></div>
              <div className="perk-body">
                <div className="perk-ttl">Permanent Inner Circle badge</div>
                <div className="perk-sub">A mark on your profile that only the earliest athletes will ever wear.</div>
              </div>
            </div>
            <div className="perk">
              <div className="perk-ico"><Icon.community /></div>
              <div className="perk-body">
                <div className="perk-ttl">Founding Athletes community</div>
                <div className="perk-sub">Get direct access to the LE-G3N team, early features, and a private group of athletes who take recovery seriously.</div>
              </div>
            </div>
            <div className="perk">
              <div className="perk-ico"><Icon.spark /></div>
              <div className="perk-body">
                <div className="perk-ttl">You shape what we build first</div>
                <div className="perk-sub">Your answers in this form go directly into our roadmap. Early athletes vote on every release.</div>
              </div>
            </div>
          </div>
        </div>

        <div className="next-list">
          <div className="item done">
            <div className="n"><Icon.check /></div>
            <div className="body">
              <div className="ttl">Early access confirmed</div>
              <div className="sub">Your athlete profile is locked into the founding cohort.</div>
            </div>
            <div className="stamp mono">JUST NOW</div>
          </div>
          <div className="item">
            <div className="n">02</div>
            <div className="body">
              <div className="ttl">Onboarding kit incoming</div>
              <div className="sub">Wearable sync guide + your first HRV baseline protocol, straight to your inbox.</div>
            </div>
            <div className="stamp mono">~48H</div>
          </div>
          <div className="item">
            <div className="n">03</div>
            <div className="body">
              <div className="ttl">Private beta invite</div>
              <div className="sub">You unlock LE-G3N before anyone else hears it exists. Quietly. No waitlist email blast.</div>
            </div>
            <div className="stamp mono">Q3 · 2026</div>
          </div>
          <div className="item">
            <div className="n">04</div>
            <div className="body">
              <div className="ttl">Public launch</div>
              <div className="sub">By the time other athletes find LE-G3N, you'll already own your readiness curve.</div>
            </div>
            <div className="stamp mono">LATER</div>
          </div>
        </div>

        <div className="share-row">
          <div>
            <div className="lab mono">Bring an athlete — they get early access too</div>
            <div className="refcode" style={{ marginTop: 8 }}>
              <b>CODE</b>{refcode}
              <span className="copy mono" onClick={copy}>
                <Icon.copy /> {copied ? ' COPIED' : ' COPY'}
              </span>
            </div>
          </div>
          <div className="actions">
            <button className="share-btn" title="Share on X"><Icon.x /></button>
            <button className="share-btn" title="Send message"><Icon.msg /></button>
            <button className="share-btn" title="Copy link" onClick={copy}><Icon.link /></button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.WaitlistForm = WaitlistForm;
window.Success = Success;
window.Icon = Icon;
