/* ============================================================
   APPLY FLOW — Team Dream
   Multi-step form, playful + professional, easy first
   ============================================================ */

const { useState, useEffect, useMemo } = React;

const SEASONS = [
  { id: 'spring',    no: 'NO. 01', name: 'Spring Awakening Circle',  dates: 'MAR 02 — MAY 24', price: '$695',   seats: '6 SEATS LEFT', waitlist: false, includes: ['Two pool sessions per week (Mon · Wed, 6 am)','One Saturday long set','Strength class (Tue, 6:30 pm)','Friday recovery & breathwork (Zoom)','GoSwim video review on every pool session','Welcome retreat: stroke filming, goal setting, fitting'] },
  { id: 'openwater', no: 'NO. 02', name: 'Open Water Circle',        dates: 'JUN 08 — AUG 23', price: '$1,285', seats: '3 SEATS LEFT', waitlist: false, badge: 'SIGNATURE', includes: ['Everything in the Spring Awakening Circle, plus:','Thursday open-water sets (Lake Michigan)','Sighting and pacing clinics','Wetsuit fitting and rental included','Door County lodge weekend (3 days, 2 nights)','Race-day support for one open-water event'] },
  { id: 'autumn',    no: 'NO. 03', name: 'Autumn Endurance Circle',  dates: 'SEP 07 — NOV 22', price: '$795',   seats: '9 SEATS LEFT', waitlist: false, includes: ['Two pool sessions per week','One Saturday long set (3,000-5,000m)','Strength class (Tue)','Friday recovery & breathwork','GoSwim video review','Distance-pacing workshops'] },
  { id: 'winter',    no: 'NO. 04', name: 'Winter Studio Circle',     dates: 'DEC 01 — FEB 21', price: '$645',   seats: 'WAITLIST',     waitlist: true, includes: ['One pool session per week (Wed)','Two strength sessions per week','Bi-weekly mindset workshops','GoSwim video review','Indoor open-water-style sets'] },
  { id: 'year',      no: 'ALL YEAR', name: 'The Full Circle', dates: 'ALL FOUR CIRCLES', price: '$2,895', seats: 'LIMITED · 8 SEATS', waitlist: false, badge: 'BUNDLE', includes: ['All four circles','Quarterly 1:1 coaching','Priority lane assignment','Year-end retreat'] },
];

const STROKES = [
  { id: 'new',       headline: "I'm just starting out",        sub: "New to swimming, or learning as an adult. Welcome — we've got you." },
  { id: 'length',    headline: "I can swim a length or two",   sub: "You've got the basics but distance is still hard. This is a great place to begin." },
  { id: '400m',      headline: "I can swim 400m continuously", sub: "Solid base. You'll fit right into the regular pool sets." },
  { id: 'experienced', headline: "I've been swimming for years", sub: "Coach Reena will love working with you on the technical details." },
  { id: 'race',      headline: "I race",                       sub: "Open water, masters, triathlon — we'll talk goals on the coach call." },
];

const HEARD_FROM = [
  'A current Dreamer referred me',
  'Saw the film (Team Dream)',
  'Instagram or social media',
  'Google search',
  'Through Team Dream Swim Club',
  'Press / article',
  'Other',
];

const STEPS = ['Your circle', 'About you', 'Your stroke', 'Book your call'];

/* ---------- OUTSETA INTEGRATION ----------
   Uses Outseta's documented JS Embed API to launch a pre-filled
   signup + checkout widget. The Outseta script is loaded in
   apply.html's <head>, which exposes window.Outseta after init.
--------------------------------------------- */

const SEASON_LABELS = {
  spring:    'Spring Awakening Circle',
  openwater: 'Open Water Circle',
  autumn:    'Autumn Endurance Circle',
  winter:    'Winter Studio Circle',
  year:      'The Full Circle',
  unsure:    'Not sure yet',
};

const SEASON_TO_PLAN_UID = {
  spring:    'Rm8wodW4',
  openwater: 'wmj5k7WV',
  autumn:    'A938olW0',
  winter:    'nmDAyRQy',
  year:      'BWzLwlQE',
  unsure:    'ZmNJyxm2', // Free "Unsure? Let's Do a Coach Call" plan
};

const STROKE_LABELS = {
  new:         'Starting out',
  length:      'One or two lengths',
  '400m':      '400m continuously',
  experienced: 'Experienced',
  race:        'Race',
};

const CALL_WINDOW_LABELS = {
  'wd-morning':  'Weekday mornings',
  'wd-lunch':    'Weekday lunch',
  'wd-evening':  'Weekday evenings',
  'sat-morning': 'Saturday mornings',
  'sat-after':   'Saturday afternoons',
  'sun-flex':    'Sunday flexible',
};

function submitToOutseta(formData) {
  const planUid = SEASON_TO_PLAN_UID[formData.season];

  // Build the registrationDefaults Outseta expects.
  // Custom properties on the Person record use their *system name*.
  // The names below are best guesses — they must match what was set
  // in Outseta → CRM → Custom Properties. Adjust if Outseta ignores any.
  const registrationDefaults = {
    Person: {
      Email:       formData.email,
      FirstName:   formData.firstName,
      LastName:    formData.lastName || '',
      PhoneMobile: formData.phone || '',
      SeasonInterest: SEASON_LABELS[formData.season] || formData.season,
      StrokeLevel:    STROKE_LABELS[formData.stroke] || formData.stroke,
      Goals:          formData.goals || '',
      Notes:          formData.notes || '',
      CallWindows:    (formData.callWindows || []).map(id => CALL_WINDOW_LABELS[id] || id).join(', '),
      CallMethod:     formData.callMethod || '',
      City:           formData.city || '',
      HeardFrom:      formData.heardFrom || '',
    },
  };

  // If applicant entered a promo code, attach it to the subscription so
  // Outseta applies the discount at checkout. Coupons themselves are
  // configured in Outseta (Billing → Discount coupons), which syncs to Stripe.
  if (formData.promoCode && formData.promoCode.trim()) {
    registrationDefaults.Subscription = {
      DiscountCouponSubscriptions: [
        { DiscountCoupon: { UniqueIdentifier: formData.promoCode.trim() } },
      ],
    };
  }

  console.log('[Outseta] auth.open()', { planUid, registrationDefaults });

  if (!window.Outseta || !window.Outseta.auth || typeof window.Outseta.auth.open !== 'function') {
    throw new Error('Outseta is still loading. Wait a moment, then try again.');
  }

  if (!planUid) {
    throw new Error('That circle isn\'t wired up yet. Pick the Spring Awakening Circle for now, or go back to Step 1.');
  }

  window.Outseta.auth.open({
    widgetMode: 'register',
    state: 'checkout',
    planUid: planUid,
    registrationDefaults: registrationDefaults,
  });
}

/* ---------- ROOT ---------- */

function ApplyApp() {
  // Read ?season= query param to pre-select
  const initialSeason = useMemo(() => {
    const params = new URLSearchParams(window.location.search);
    const s = params.get('season');
    return SEASONS.find(x => x.id === s) ? s : '';
  }, []);

  // Pull persisted state
  const persisted = useMemo(() => {
    try {
      const raw = localStorage.getItem('tds_apply_v1');
      return raw ? JSON.parse(raw) : null;
    } catch { return null; }
  }, []);

  const [step, setStep] = useState(persisted?.step ?? 0);
  const [data, setData] = useState(persisted?.data ?? {
    season: initialSeason || '',
    firstName: '', lastName: '', email: '', phone: '',
    city: '', heardFrom: '',
    stroke: '', goals: '', notes: '',
    callWindows: [], callMethod: '',
    promoCode: '',
  });
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);
  const [errors, setErrors] = useState({});

  // If URL has ?season, override saved state
  useEffect(() => {
    if (initialSeason && !data.season) {
      setData(d => ({ ...d, season: initialSeason }));
    }
    // eslint-disable-next-line
  }, [initialSeason]);

  // Persist on change
  useEffect(() => {
    if (!submitted) {
      localStorage.setItem('tds_apply_v1', JSON.stringify({ step, data }));
    }
  }, [step, data, submitted]);

  function update(patch) { setData(d => ({ ...d, ...patch })); }

  function validateStep(s) {
    const e = {};
    if (s === 0 && !data.season) e.season = 'Pick a circle — or "I\'m not sure yet" is just fine.';
    if (s === 1) {
      if (!data.firstName.trim()) e.firstName = 'What should we call you?';
      if (!data.email.trim()) e.email = 'We\'ll need this to write back.';
      else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) e.email = 'Hmm — that email looks off.';
    }
    if (s === 2 && !data.stroke) e.stroke = 'Pick the one closest to you.';
    if (s === 3) {
      if (!data.callWindows || data.callWindows.length === 0) e.callWindows = 'Pick at least one window that works for you.';
      if (!data.callMethod) e.callMethod = 'Phone, Zoom, or in-person?';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function next() {
    if (validateStep(step)) {
      if (step < STEPS.length - 1) setStep(step + 1);
      else submit();
    }
  }
  function back() { if (step > 0) setStep(step - 1); setErrors({}); }

  function submit() {
    setSubmitting(true);
    setSubmitError(null);
    try {
      submitToOutseta(data);
      // Outseta's widget takes over the UI now. Leave our submitting
      // state visible so the page shows a calm "opening checkout…"
      // message in case the overlay takes a beat. We do NOT clear
      // localStorage or mark submitted here — if the user closes
      // Outseta's widget without completing, they can resume.
      setTimeout(() => setSubmitting(false), 1200);
    } catch (err) {
      console.error('[Apply] Submission failed:', err);
      setSubmitError(err.message || 'Something went wrong. Please try again, or email info@teamdream.club directly.');
      setSubmitting(false);
    }
  }

  function startOver() {
    setSubmitted(false);
    setStep(0);
    setData({ season: '', firstName: '', lastName: '', email: '', phone: '', city: '', heardFrom: '', stroke: '', goals: '', notes: '', callWindows: [], callMethod: '', promoCode: '' });
  }

  if (submitted) return <Welcome data={data} onRestart={startOver} />;

  return (
    <div>
      <div className="apply-promise">
        <div className="promise-eyebrow">— THE APPLICATION</div>
        <h1 className="promise-h">the first lap is the form.</h1>
        <p className="promise-sub">Four short steps, then a coach call. We read every application — your answers go straight to Derrick and Reena, no algorithms in the middle.</p>
      </div>

      <ProgressRail step={step} total={STEPS.length} label={STEPS[step]} />

      <div className={'apply-card' + (step === 0 ? ' wide' : '')}>
        {step === 0 && <Step1Season data={data} update={update} errors={errors} />}
        {step === 1 && <Step2About data={data} update={update} errors={errors} />}
        {step === 2 && <Step3Stroke data={data} update={update} errors={errors} />}
        {step === 3 && <Step4Book data={data} update={update} errors={errors} onEdit={setStep} />}

        <div className="step-nav">
          <button className="btn-back" onClick={back} disabled={step === 0}>
            <span aria-hidden="true">←</span> Back
          </button>
          <button className="btn-next" onClick={next} disabled={submitting}>
            {submitting
              ? 'Opening secure checkout…'
              : step === STEPS.length - 1
                ? (data.season === 'unsure' ? 'Schedule my coach call' : 'Continue to checkout')
                : 'Continue'}
            <span aria-hidden="true">→</span>
          </button>
        </div>
        {submitError && (
          <div className="submit-error">
            <div className="submit-error-h">We couldn't send your application.</div>
            <div className="submit-error-b">{submitError}</div>
            <div className="submit-error-help">If this keeps happening, email <a href="mailto:info@teamdream.club">info@teamdream.club</a> with the details above and we'll take it from there.</div>
          </div>
        )}
      </div>

      <div className="save-notice">
        Your progress saves automatically · You can close this tab and come back
      </div>
    </div>
  );
}

/* ---------- PROGRESS ---------- */

function ProgressRail({ step, total, label }) {
  return (
    <div className="progress-rail">
      <div className="progress-bar">
        {Array.from({ length: total }).map((_, i) => (
          <div
            key={i}
            className={'progress-step ' + (i < step ? 'done' : i === step ? 'current' : '')}
          />
        ))}
      </div>
      <div className="progress-meta">
        <span>{label}</span>
        <span className="step-count">Step {step + 1} of {total}</span>
      </div>
    </div>
  );
}

/* ---------- STEP 1: SEASON ---------- */

function Step1Season({ data, update, errors }) {
  return (
    <div>
      <div className="step-eyebrow"><span className="num">01</span> Your circle</div>
      <h2 className="step-title">which one calls to you?</h2>
      <p className="step-lede">Pick the circle you're applying for. Not sure yet? That's a great answer too — your coach call will help you find the right entry point.</p>

      <div className="season-options">
        {SEASONS.map(s => (
          <button
            type="button"
            key={s.id}
            className={'season-option ' + (data.season === s.id ? 'selected' : '')}
            onClick={() => update({ season: s.id })}
            aria-pressed={data.season === s.id}
          >
            {s.badge && <span className="so-badge">{s.badge}</span>}
            <div className="check-dot">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            </div>
            <div className="so-no">{s.no}</div>
            <div className="so-name">{s.name}</div>
            <div className="so-dates">{s.dates}</div>
            <div className="so-foot">
              <span className="so-price">{s.price}</span>
              <span className={'so-seats ' + (s.waitlist ? 'waitlist' : '')}>{s.seats}</span>
            </div>
            <div className="so-inc-label">What's included</div>
            <ul className="so-inc">
              {s.includes.map((x, i) => <li key={i} className={x.endsWith(':') ? 'lead' : ''}>{x}</li>)}
            </ul>
          </button>
        ))}

        <button
          type="button"
          className={'season-option unsure ' + (data.season === 'unsure' ? 'selected' : '')}
          onClick={() => update({ season: 'unsure' })}
          aria-pressed={data.season === 'unsure'}
        >
          <div className="so-name">I'm not sure yet — talk me through it</div>
          <div className="so-sub">We'll figure out which circle fits on the coach call.</div>
        </button>
      </div>

      {errors.season && <div className="field-error" style={{ marginTop: 14 }}>{errors.season}</div>}
    </div>
  );
}

/* ---------- STEP 2: ABOUT YOU ---------- */

function Step2About({ data, update, errors }) {
  return (
    <div>
      <div className="step-eyebrow"><span className="num">02</span> About you</div>
      <h2 className="step-title">tell us where to write back.</h2>
      <p className="step-lede">Just the essentials. We'll only use your contact info for the coach call and a welcome packet — no spammy newsletters, ever.</p>

      <div className="field-row two">
        <div className={'field ' + (errors.firstName ? 'invalid' : '')}>
          <label htmlFor="firstName">First name<span className="required">*</span></label>
          <input id="firstName" type="text" value={data.firstName} onChange={e => update({ firstName: e.target.value })} placeholder="Jordan" />
          {errors.firstName && <div className="field-error">{errors.firstName}</div>}
        </div>
        <div className="field">
          <label htmlFor="lastName">Last name<span className="optional">optional</span></label>
          <input id="lastName" type="text" value={data.lastName} onChange={e => update({ lastName: e.target.value })} placeholder="Wells" />
        </div>
      </div>

      <div className="field-row two">
        <div className={'field ' + (errors.email ? 'invalid' : '')}>
          <label htmlFor="email">Email<span className="required">*</span></label>
          <input id="email" type="email" value={data.email} onChange={e => update({ email: e.target.value })} placeholder="you@email.com" />
          {errors.email && <div className="field-error">{errors.email}</div>}
        </div>
        <div className="field">
          <label htmlFor="phone">Phone<span className="optional">optional</span></label>
          <input id="phone" type="tel" value={data.phone} onChange={e => update({ phone: e.target.value })} placeholder="(312) 555-0142" />
        </div>
      </div>

      <div className="field-row two">
        <div className="field">
          <label htmlFor="city">Neighborhood or city<span className="optional">optional</span></label>
          <input id="city" type="text" value={data.city} onChange={e => update({ city: e.target.value })} placeholder="Lincoln Square, Chicago" />
          <div className="hint">Helps us point you to the right pool and meetup spots.</div>
        </div>
        <div className="field">
          <label htmlFor="heardFrom">How'd you find us?<span className="optional">optional</span></label>
          <select id="heardFrom" value={data.heardFrom} onChange={e => update({ heardFrom: e.target.value })}>
            <option value="">— Pick one —</option>
            {HEARD_FROM.map(h => <option key={h} value={h}>{h}</option>)}
          </select>
        </div>
      </div>
    </div>
  );
}

/* ---------- STEP 3: STROKE ---------- */

function Step3Stroke({ data, update, errors }) {
  return (
    <div>
      <div className="step-eyebrow"><span className="num">03</span> Your stroke</div>
      <h2 className="step-title">where are you, in the water?</h2>
      <p className="step-lede">Honest answers only — there's a seat for every level. Pace doesn't matter, commitment does.</p>

      <div className="radio-list">
        {STROKES.map(s => (
          <div
            key={s.id}
            className={'radio-card ' + (data.stroke === s.id ? 'selected' : '')}
            onClick={() => update({ stroke: s.id })}
            role="radio"
            tabIndex="0"
            aria-checked={data.stroke === s.id}
            onKeyDown={e => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); update({ stroke: s.id }); } }}
          >
            <div className="radio-circle"></div>
            <div className="radio-label">
              <div className="radio-headline">{s.headline}</div>
              <div className="radio-sub">{s.sub}</div>
            </div>
          </div>
        ))}
      </div>
      {errors.stroke && <div className="field-error" style={{ marginTop: 14 }}>{errors.stroke}</div>}

      <div className="field" style={{ marginTop: 28 }}>
        <label htmlFor="goals">What pulled you to Team Dream?<span className="optional">optional</span></label>
        <textarea id="goals" value={data.goals} onChange={e => update({ goals: e.target.value })} placeholder="A race I want to finish, a fear I want to face, a friend who joined…"></textarea>
      </div>

      <div className="field">
        <label htmlFor="notes">Anything we should know?<span className="optional">optional</span></label>
        <textarea id="notes" value={data.notes} onChange={e => update({ notes: e.target.value })} placeholder="Injuries, schedule constraints, water history, anything at all."></textarea>
      </div>
    </div>
  );
}

/* ---------- STEP 4: WHEN TO REACH YOU ---------- */

const CALL_WINDOWS = [
  { id: 'wd-morning',  label: 'Weekday mornings',   sub: 'Before 9 am' },
  { id: 'wd-lunch',    label: 'Weekday lunch',      sub: '11 am – 1 pm' },
  { id: 'wd-evening',  label: 'Weekday evenings',   sub: '5 – 8 pm' },
  { id: 'sat-morning', label: 'Saturday mornings',  sub: 'Before noon' },
  { id: 'sat-after',   label: 'Saturday afternoons',sub: 'Noon – 5 pm' },
  { id: 'sun-flex',    label: 'Sunday — flexible',  sub: 'Most of the day works' },
];

const CALL_METHODS = [
  { id: 'phone',    label: 'Phone',    sub: 'Quickest. Bring it with you on a walk.' },
  { id: 'zoom',     label: 'Zoom',     sub: 'Face-to-face from wherever you are.' },
  { id: 'inperson', label: 'In person', sub: 'Coffee, the pool, wherever works.' },
];

function Step4Book({ data, update, errors, onEdit }) {
  const selectedSeason = SEASONS.find(s => s.id === data.season);
  const selectedStroke = STROKES.find(s => s.id === data.stroke);

  function toggleWindow(id) {
    const next = data.callWindows.includes(id)
      ? data.callWindows.filter(x => x !== id)
      : [...data.callWindows, id];
    update({ callWindows: next });
  }

  return (
    <div>
      <div className="step-eyebrow"><span className="num">04</span> When to reach you</div>
      <h2 className="step-title">one short call with a coach.</h2>
      <p className="step-lede">Twenty minutes. We'll go through your application, answer questions, and confirm your circle. No pressure, no pitch — a coach will email within 24 hours to set up a specific time.</p>

      <dl className="summary">
        <div className="summary-row">
          <dt>Circle</dt>
          <dd>
            {data.season === 'unsure' ? 'Not sure yet — let\'s talk it through' : selectedSeason ? `${selectedSeason.name} · ${selectedSeason.dates}` : <span className="empty">Not picked yet</span>}
            <button type="button" className="summary-edit" onClick={() => onEdit(0)}>Edit</button>
          </dd>
        </div>
        <div className="summary-row">
          <dt>Name</dt>
          <dd>
            {data.firstName ? `${data.firstName} ${data.lastName}`.trim() : <span className="empty">—</span>}
            <button type="button" className="summary-edit" onClick={() => onEdit(1)}>Edit</button>
          </dd>
        </div>
        <div className="summary-row">
          <dt>Email</dt>
          <dd>{data.email || <span className="empty">—</span>}</dd>
        </div>
        <div className="summary-row">
          <dt>Your stroke</dt>
          <dd>
            {selectedStroke ? selectedStroke.headline : <span className="empty">—</span>}
            <button type="button" className="summary-edit" onClick={() => onEdit(2)}>Edit</button>
          </dd>
        </div>
      </dl>

      <div className="field" style={{ marginTop: 28, marginBottom: 24 }}>
        <label>When's best to reach you?<span className="required">*</span></label>
        <div className="hint" style={{ marginTop: 0, marginBottom: 12 }}>Pick as many as work — more flexibility means a faster call.</div>
        <div className="check-list">
          {CALL_WINDOWS.map(w => (
            <div
              key={w.id}
              className={'check-card ' + (data.callWindows.includes(w.id) ? 'selected' : '')}
              onClick={() => toggleWindow(w.id)}
              role="checkbox"
              tabIndex="0"
              aria-checked={data.callWindows.includes(w.id)}
              onKeyDown={e => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); toggleWindow(w.id); } }}
            >
              <div className="check-box">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              </div>
              <div className="check-label">
                <div className="check-headline">{w.label}</div>
                <div className="check-sub">{w.sub}</div>
              </div>
            </div>
          ))}
        </div>
        {errors.callWindows && <div className="field-error" style={{ marginTop: 10 }}>{errors.callWindows}</div>}
      </div>

      <div className="field">
        <label>Phone, Zoom, or in person?<span className="required">*</span></label>
        <div className="radio-list" style={{ marginTop: 10 }}>
          {CALL_METHODS.map(m => (
            <div
              key={m.id}
              className={'radio-card ' + (data.callMethod === m.id ? 'selected' : '')}
              onClick={() => update({ callMethod: m.id })}
              role="radio"
              tabIndex="0"
              aria-checked={data.callMethod === m.id}
              onKeyDown={e => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); update({ callMethod: m.id }); } }}
            >
              <div className="radio-circle"></div>
              <div className="radio-label">
                <div className="radio-headline">{m.label}</div>
                <div className="radio-sub">{m.sub}</div>
              </div>
            </div>
          ))}
        </div>
        {errors.callMethod && <div className="field-error" style={{ marginTop: 10 }}>{errors.callMethod}</div>}
      </div>

      {data.season !== 'unsure' && (
        <div className="field promo-field" style={{ marginTop: 28 }}>
          <label htmlFor="promoCode">Promo code<span className="optional">optional</span></label>
          <input
            id="promoCode"
            type="text"
            value={data.promoCode || ''}
            onChange={e => update({ promoCode: e.target.value.toUpperCase() })}
            placeholder="e.g. WELCOME25"
            autoComplete="off"
            spellCheck="false"
            style={{ textTransform: 'uppercase', letterSpacing: '0.06em' }}
          />
          <div className="hint">Applied at checkout. Codes are set in Outseta (Billing → Discount coupons).</div>
        </div>
      )}
    </div>
  );
}

/* ---------- WELCOME ---------- */

function Welcome({ data, onRestart }) {
  const selectedSeason = SEASONS.find(s => s.id === data.season);
  return (
    <div>
      <div className="apply-promise">
        <div className="promise-eyebrow">— APPLICATION RECEIVED</div>
      </div>
      <div className="welcome-card">
        <div className="welcome-icon">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
        </div>
        <h1>you're in the circle.</h1>
        <p className="welcome-sub">
          Thank you{data.firstName ? `, ${data.firstName}` : ''}. Your application is in — Derrick or Reena will reach out at <strong>{data.email}</strong> within 24 hours to set up your coach call.
        </p>

        <div className="next-steps">
          <div className="next-step">
            <div className="ns-no">NEXT · 24 HOURS</div>
            <div className="ns-h">Confirmation email</div>
            <div className="ns-b">A note from a coach, plus a calendar invite for your call.</div>
          </div>
          <div className="next-step">
            <div className="ns-no">THEN · YOUR CALL</div>
            <div className="ns-h">Twenty minutes</div>
            <div className="ns-b">A real conversation. We'll confirm {selectedSeason ? selectedSeason.name : 'your circle'} and answer anything you bring.</div>
          </div>
          <div className="next-step">
            <div className="ns-no">AFTER · WELCOME WEEK</div>
            <div className="ns-h">Stroke filming + retreat</div>
            <div className="ns-b">Your first session is the welcome retreat. We film you, set goals, get fitted.</div>
          </div>
        </div>

        <div className="welcome-explore">
          <a href="train.html">Explore the training →</a>
          <a href="about.html">Read our story</a>
          <a href="https://vimeo.com/762316789" target="_blank" rel="noopener">Watch the film</a>
          <a href="#" onClick={(e) => { e.preventDefault(); onRestart(); }}>Apply again</a>
        </div>
      </div>
    </div>
  );
}

/* ---------- MOUNT ---------- */

const root = ReactDOM.createRoot(document.getElementById('apply-root'));
root.render(<ApplyApp />);
