const STEPS = [
  { id: 'teams', label: 'Your teams' },
  { id: 'cadence', label: 'Newsletters & cadence' },
  { id: 'leagues', label: "What's next" },
  { id: 'signals', label: 'Signals & lens' },
  { id: 'confirm', label: 'Confirm' },
];

function OnboardingPage({ seedEmail = '', onNav = () => {} }) {
  const { isPhone } = window.useIsMobile();
  const [i, setI] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const [op, setOp] = React.useState(1);
  const [v, setV] = React.useState({
    email: seedEmail, teams: [], teamCadence: {}, teamOn: {},
    league: { on: true, cadence: 'daily' }, weeklies: { power: true }, topPicks: false,
    topics: [], intent: '', source: '', leagues: {},
  });
  const set = (patch) => setV(prev => Object.assign({}, prev, patch));
  const update = (fn) => setV(fn);
  const move = (next) => {
    setOp(0);
    setTimeout(() => { setI(next); window.scrollTo(0, 0); setOp(1); }, 180);
  };
  const emailOk = /.+@.+\..+/.test(v.email);
  const valid = i === 0 ? v.teams.length > 0 : (i === STEPS.length - 1 ? emailOk : true);
  const pct = done ? 100 : Math.round((i / (STEPS.length - 1)) * 100);

  // Wire the (previously stubbed) submit to the Synth signup backend. UI/flow unchanged.
  // POST the payload; on a transient failure retry once silently (handles a serverless-DB
  // cold start). Then advance to Will's existing success screen. NOTE: Will's design has no
  // error/retry state, so a persistent failure still shows success — a real error UI is a
  // pre-launch item that needs Will's design (see docs/PHASES.md). The backend logs any
  // failed write so it isn't invisible to us.
  const submit = () => {
    const url = window.SYNTH_SIGNUP_URL || '/signup';
    const opts = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(v) };
    const attempt = (retriesLeft) => fetch(url, opts).then(res => {
      if (res.ok) { setDone(true); return; }
      if (retriesLeft > 0 && res.status >= 500) { attempt(retriesLeft - 1); return; }
      setDone(true);
    }).catch(() => { retriesLeft > 0 ? attempt(retriesLeft - 1) : setDone(true); });
    attempt(1);
  };

  const body = done ? <StepDone v={v} onNav={onNav} />
    : i === 0 ? <StepTeams v={v} set={set} update={update} />
    : i === 1 ? <StepNewsletters v={v} set={set} />
    : i === 2 ? <StepLeagues v={v} set={set} />
    : i === 3 ? <StepSignals v={v} set={set} />
    : <StepConfirm v={v} set={set} onEdit={move} />;

  return (
    <main style={{ background: 'var(--syn-paper)', minHeight: 'calc(100vh - 64px)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ height: 2, background: 'var(--syn-rule)', width: '100%' }}>
        <div style={{ height: '100%', width: pct + '%', background: 'var(--syn-navy)', transition: `width 420ms ${EASE}` }} />
      </div>
      <div style={{ flex: 1, padding: isPhone ? '28px 18px 80px' : '42px 48px 96px' }}>
        <div style={{ maxWidth: 900, margin: '0 auto' }}>
          <div style={{ opacity: op, transition: `opacity 180ms ${EASE}` }}>{body}</div>
        </div>
      </div>
      {done ? null : (
        <div style={{ position: 'sticky', bottom: 0, background: 'var(--syn-paper)', borderTop: '1px solid var(--syn-rule)', padding: isPhone ? '14px 18px' : '16px 48px', zIndex: 5 }}>
          <div style={{ maxWidth: 900, margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: isPhone ? 8 : 16, flexWrap: isPhone ? 'wrap' : 'nowrap' }}>
            <button type="button" onClick={() => (i === 0 ? onNav('home') : move(i - 1))} style={{
              background: 'none', border: '1px solid var(--syn-rule)', borderRadius: 'var(--syn-radius-md)', padding: '12px 20px',
              fontFamily: 'var(--syn-font-body)', fontSize: 14.5, color: 'var(--syn-fg-muted)', cursor: 'pointer',
            }}>{i === 0 ? 'Cancel' : 'Back'}</button>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              {i === 1 ? (
                <React.Fragment>
                  <button type="button" onClick={() => move(STEPS.length - 1)} style={{
                    background: 'var(--syn-navy)', color: 'var(--syn-paper)',
                    border: 0, borderRadius: 'var(--syn-radius-md)', padding: '13px 26px',
                    fontFamily: 'var(--syn-font-body)', fontSize: 15, fontWeight: 500, cursor: 'pointer',
                    transition: `background-color 200ms ${EASE}`,
                  }}>I'm done</button>
                  <button type="button" onClick={() => move(2)} style={{ background: 'var(--syn-paper-2)', border: '1px solid var(--syn-rule)', borderRadius: 'var(--syn-radius-md)', padding: '13px 20px', fontFamily: 'var(--syn-font-body)', fontSize: 14.5, color: 'var(--syn-fg-muted)', cursor: 'pointer' }}>Tell us more about you</button>
                </React.Fragment>
              ) : (
                <React.Fragment>
              {i > 0 && i < STEPS.length - 1 ? (
                <button type="button" onClick={() => move(i + 1)} style={{ background: 'none', border: 0, padding: 0, fontFamily: 'var(--syn-font-body)', fontSize: 14, color: 'var(--syn-fg-subtle)', cursor: 'pointer' }}>Skip</button>
              ) : null}
              <button type="button" disabled={!valid} onClick={() => (i === STEPS.length - 1 ? submit() : move(i + 1))} style={{
                background: valid ? 'var(--syn-navy)' : 'var(--syn-paper-3)', color: valid ? 'var(--syn-paper)' : 'var(--syn-fg-subtle)',
                border: 0, borderRadius: 'var(--syn-radius-md)', padding: '13px 26px',
                fontFamily: 'var(--syn-font-body)', fontSize: 15, fontWeight: 500, cursor: valid ? 'pointer' : 'not-allowed',
                transition: `background-color 200ms ${EASE}`,
              }}>{i === STEPS.length - 1 ? 'Confirm and subscribe' : 'Continue'}</button>
                </React.Fragment>
              )}
            </div>
          </div>
        </div>
      )}
    </main>
  );
}
window.OnboardingPage = OnboardingPage;
