/* Poise onboarding - Act 1 (Hook) + Act 2 (Investment): S1–S11 */

const { useState, useEffect, useRef } = React;
const { Button } = window.PoiseDesignSystem_eee0d2;

/* S1 · Welcome lives in welcome-v2.jsx */

/* ============ S2 · The Hook - signature moment 1 ============ */
/* Choreography: moment lines land → headline lands → pause → the turn lands quieter. */
function HookScreen() {
  const flow = useFlow();
  const [stage, setStage] = useState(0);
  const [underlineOn, setUnderlineOn] = useState(false);
  const timers = useRef([]);

  const steps = [600, 1600, 2500, 3700, 4900, 6300, 7500]; // m1, m2, m3, headline, turn, resolve, CTA (~20% tighter)

  useEffect(() => {
    const base = flow.t.motion ? 1 : 0.02;
    timers.current = steps.map((t, i) => setTimeout(() => setStage(i + 1), t * base));
    timers.current.push(setTimeout(() => setUnderlineOn(true), (steps[5] + 500) * base));
    return () => timers.current.forEach(clearTimeout);
  }, [flow.t.motion]);

  const show = (n) => ({ opacity: stage >= n ? 1 : 0, pointerEvents: stage >= n ? 'auto' : 'none', transform: stage >= n ? 'none' : 'translateY(10px)', transition: 'opacity 750ms var(--ease-out), transform 750ms var(--ease-out)' });

  const cta = (
    <div style={{ width: '100%', ...show(steps.length) }}>
      <Button variant="primary" size="lg" fullWidth onClick={() => flow.next()}>Continue</Button>
    </div>
  );

  return (
    <Screen id="hook" label="S2 · The hook (unseen hours)" enter="from-black" topBar={<TopBar onBack={() => flow.back()} />} cta={cta}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 14 }}>
        <P style={{ fontSize: 19, ...show(1) }}>Walking into the meeting.</P>
        <P style={{ fontSize: 19, ...show(2) }}>Across the table at lunch.</P>
        <P style={{ fontSize: 19, ...show(3) }}>In the background of someone’s photo.</P>
        <H style={{ fontSize: 32, marginTop: 26, ...show(4) }}>Everyone saw your posture.</H>
        <P style={{ fontSize: 20, marginTop: 10, ...show(5) }}>Except you.</P>
        <P style={{ fontSize: 20, marginTop: 22, color: 'var(--text-primary)', fontWeight: 600, ...show(6) }}>That changes <span className={`underline-draw${underlineOn ? ' on' : ''}`}>today</span>.</P>
      </div>
    </Screen>
  );
}

/* ============ S3–S7 · Priming questions ============ */
function QuestionScreen({ index }) {
  const flow = useFlow();
  const q = QUESTIONS[index];
  const multi = !!q.multi;
  const saved = flow.answers[q.short];
  const [picked, setPicked] = useState(saved != null ? saved : (multi ? [] : null));

  const isSel = (k) => multi ? picked.includes(k) : picked === k;
  const exclusiveOn = multi && picked.includes(q.exclusive);

  const choose = (k) => {
    if (multi) {
      let next;
      if (k === q.exclusive) {
        next = picked.includes(k) ? [] : [k];
      } else {
        if (exclusiveOn) return;
        next = picked.includes(k) ? picked.filter((x) => x !== k) : [...picked, k];
      }
      setPicked(next);
      flow.setAnswer(q.short, next.length ? next : undefined);
    } else {
      const next = picked === k ? null : k;
      setPicked(next);
      flow.setAnswer(q.short, next != null ? next : undefined);
    }
  };

  const hasPick = multi ? picked.length > 0 : !!picked;

  const proceed = () => {
    track('onboarding_question_answered', { question: q.key, answer: picked, skipped: false });
    flow.next();
  };

  const skip = () => {
    flow.setAnswer(q.short, undefined);
    track('onboarding_question_answered', { question: q.key, answer: null, skipped: true });
    flow.next();
  };

  return (
    <Screen
      id={q.short}
      label={`S${index + 3} · Question: ${q.short}`}
      topBar={<TopBar onBack={() => flow.back()} cue={`${index + 1} of ${QUESTIONS.length}`} onSkip={skip} />}
      cta={
        <div style={{ width: '100%' }}>
          <Button variant="primary" size="lg" fullWidth disabled={!hasPick} onClick={proceed}>Continue</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', flex: 1, paddingBottom: 8 }}>
        <span className="poise-caption" style={{ textAlign: 'center', color: 'var(--text-secondary)', paddingTop: 2 }}>{index + 1} of {QUESTIONS.length}</span>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <H style={{ fontSize: 27, marginBottom: multi ? 8 : 28, textAlign: 'center' }}>{q.title}</H>
          {multi && <span className="poise-caption" style={{ textAlign: 'center', marginBottom: 28, color: 'var(--text-secondary)' }}>Select all that apply</span>}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
            {q.options.map((o, i) => {
              const disabled = multi && exclusiveOn && o.k !== q.exclusive;
              return (
                <div key={o.k} className="rise" style={{ animationDelay: `${80 + i * 55}ms` }}>
                  <button
                    className={`opt-card ${isSel(o.k) ? 'sel' : ''} ${disabled ? 'disabled' : ''}`}
                    onClick={() => choose(o.k)}
                  >
                    <span>{o.label}</span>
                  </button>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </Screen>
  );
}

/* ============ S11 · Personalized insight ============ */
function InsightScreen() {
  const flow = useFlow();
  const branch = pickBranch(flow.answers, flow.t.forceBranch);
  const [stage, setStage] = useState(0);

  useEffect(() => {
    track('insight_branch', { branch: branch.id });
    const base = flow.t.motion ? 1 : 0.02;
    const ts = [500, 1300, 2300, 3300].map((t, i) => setTimeout(() => setStage(i + 1), t * base));
    return () => ts.forEach(clearTimeout);
  }, [branch.id]);

  const show = (n) => ({ opacity: stage >= n ? 1 : 0, pointerEvents: stage >= n ? 'auto' : 'none', transform: stage >= n ? 'none' : 'translateY(10px)', transition: 'opacity 650ms var(--ease-out), transform 650ms var(--ease-out)' });

  return (
    <Screen
      id="insight" label="S11 · Personalized insight"
      topBar={<TopBar onBack={() => flow.back()} />}
      cta={
        <div style={{ width: '100%', ...show(4) }}>
          <Button variant="primary" size="lg" fullWidth onClick={() => flow.next()}>Continue</Button>
        </div>
      }
    >
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 18 }}>
        <span className="poise-caption" style={show(1)}>What your answers say</span>
        <H style={{ fontSize: 31, ...(branch.id === 'serious' ? { textWrap: 'normal' } : {}), ...show(2) }}>{branch.headline}</H>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 8 }}>
          {branch.body.map((line, i) => (
            <P key={i} style={{ fontSize: 18, ...show(3 + Math.min(i, 1) * 0) }}>{line}</P>
          ))}
        </div>
      </div>
    </Screen>
  );
}

Object.assign(window, { HookScreen, QuestionScreen, InsightScreen });
