// App shell: tabs, setup, quiz runtime, records
const { useState: useS, useEffect: useE, useMemo: useM, useRef: useR } = React;

function SetupPanel({ onStart }) {
  const [shuffleOpts, setShuffleOpts] = useS(false);

  const allModules = useM(() => {
    const mods = new Set();
    window.ALL_QUESTIONS.forEach(q => {
      if (q.source) mods.add(q.source);
    });
    return ['All Modules', ...Array.from(mods).sort((a, b) => {
      const numA = parseInt((a.match(/Module (\d+)/) || [])[1] || '0');
      const numB = parseInt((b.match(/Module (\d+)/) || [])[1] || '0');
      return numA - numB;
    })];
  }, []);

  const [selectedModule, setSelectedModule] = useS('All Modules');
  const [limitEnabled, setLimitEnabled] = useS(false);

  const filteredQuestions = useM(() => {
    if (selectedModule === 'All Modules') return window.ALL_QUESTIONS;
    return window.ALL_QUESTIONS.filter(q => q.source === selectedModule);
  }, [selectedModule]);

  const max = filteredQuestions.length;
  const [count, setCount] = useS(max);

  useE(() => {
    if (!limitEnabled) setCount(max);
  }, [max, limitEnabled]);

  useE(() => {
    if (count > max) setCount(max);
  }, [max]);

  const start = () => {
    let pool = window.QuizUtils.shuffle(filteredQuestions);
    if (limitEnabled) pool = pool.slice(0, count);

    // Optionally shuffle option order while preserving correct index
    if (shuffleOpts) {
      pool = pool.map(q => {
        const idxs = Array.from({length: q.options.length}, (_, i) => i);
        const shuffled = window.QuizUtils.shuffle(idxs);
        const newOptions = shuffled.map(i => q.options[i]);
        
        let newCorrect;
        if (Array.isArray(q.correct)) {
            newCorrect = q.correct.map(c => shuffled.indexOf(c));
        } else {
            newCorrect = shuffled.indexOf(q.correct);
        }
        return { ...q, options: newOptions, correct: newCorrect };
      });
    }
    onStart({ mode: selectedModule, questions: pool });
  };

  const exportQuestions = () => {
    const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
    const buildSection = (title, arr) => {
      let out = `=== ${title.toUpperCase()} (${arr.length} questions) ===\n\n`;
      arr.forEach(q => {
        out += `[${q.source.toUpperCase()} · Q${q.num}]\n`;
        const correctAnswers = Array.isArray(q.correct) ? q.correct : [q.correct];
        out += `CORRECT ANSWER: ${correctAnswers.map(c => letters[c] + ') ' + q.options[c]).join(', ')}\n`;
        out += `Question: ${q.q}\n`;
        q.options.forEach((opt, i) => {
          const marker = correctAnswers.includes(i) ? '✓' : ' ';
          out += `  ${marker} ${letters[i] || '?'}) ${opt}\n`;
        });
        out += '\n';
      });
      return out;
    };
    const header = `QUIZE — CYBERSECURITY EXAM PRACTICE · QUESTION BANK EXPORT
Generated: ${new Date().toISOString()}
Total questions: ${window.ALL_QUESTIONS.length}
Format: Each question shows the CORRECT ANSWER at the top, followed by the question text and all options (✓ marks the correct one).

Please verify that each "CORRECT ANSWER" genuinely matches the best answer for the stated question.

`;
    const body = buildSection('Cybersecurity Questions', window.ALL_QUESTIONS);
    const jsonBody = {
      generated: new Date().toISOString(),
      questions: window.ALL_QUESTIONS.map(q => {
        const correctAnswers = Array.isArray(q.correct) ? q.correct : [q.correct];
        return {
          num: q.num, question: q.q, options: q.options,
          correctIndices: correctAnswers, 
          correctAnswers: correctAnswers.map(c => q.options[c]),
        }
      })
    };
    const download = (content, type, name) => {
      const blob = new Blob([content], { type });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url; a.download = name;
      a.click();
      URL.revokeObjectURL(url);
    };
    download(header + body, 'text/plain', `quize-questions-${Date.now()}.txt`);
    download(JSON.stringify(jsonBody, null, 2), 'application/json', `quize-questions-${Date.now()}.json`);
  };

  const [ddOpen, setDdOpen] = useS(false);
  const ddRef = useR(null);

  // close dropdown on outside click
  useE(() => {
    if (!ddOpen) return;
    const handler = (e) => { if (ddRef.current && !ddRef.current.contains(e.target)) setDdOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [ddOpen]);

  return (
    <div className="card">
      <h2 style={{ fontSize: 15, fontWeight: 600, marginBottom: 18 }}>New Quiz</h2>
      <div className="setup">
        <div className="setup-row">
          <div className="setup-label">module</div>
          <div className="setup-control">
            <div className="mod-dropdown" ref={ddRef}>
              <button type="button" className={`mod-dropdown-trigger ${ddOpen ? 'open' : ''}`} onClick={() => setDdOpen(!ddOpen)}>
                <span className="mod-dd-label">{selectedModule.replace(' - Quiz & Review Questions', '')}</span>
                <svg className="mod-dd-chevron" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
              </button>
              {ddOpen && (
                <div className="mod-dropdown-list">
                  {allModules.map(m => (
                    <button
                      key={m}
                      type="button"
                      className={`mod-dropdown-item ${m === selectedModule ? 'active' : ''}`}
                      onClick={() => { setSelectedModule(m); setDdOpen(false); }}
                    >
                      {m.replace(' - Quiz & Review Questions', '')}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>

        <div className="setup-row">
          <div className="setup-label">questions</div>
          <div className="setup-control">
            {!limitEnabled ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <span className="num-max"><strong>All {max} questions</strong> will be asked</span>
                <button className="btn btn-ghost" style={{ fontSize: '11px', padding: '2px 6px', height: 'auto', color: 'var(--text-faint)' }} onClick={() => setLimitEnabled(true)}>
                  limit questions
                </button>
              </div>
            ) : (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
                <NumField value={count} onChange={setCount} min={1} max={max} />
                <span className="num-max">of {max} available</span>
                <button className="btn btn-ghost" style={{ fontSize: '11px', padding: '2px 6px', height: 'auto', color: 'var(--text-faint)' }} onClick={() => setLimitEnabled(false)}>
                  ask all
                </button>
                <div style={{ display: 'flex', gap: 6, width: '100%', marginTop: 4 }}>
                  {[10, 20, 50, max].filter((v,i,a) => a.indexOf(v)===i && v<=max && v>0).map(v => (
                    <button key={v} className="btn btn-sm btn-ghost" onClick={() => setCount(v)}>{v}</button>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="setup-row">
          <div className="setup-label">shuffle answers</div>
          <div className="setup-control">
            <div className="pill-toggle-row">
              <button
                type="button"
                className={`pill-toggle ${shuffleOpts ? 'on' : ''}`}
                onClick={() => setShuffleOpts(!shuffleOpts)}
                aria-pressed={shuffleOpts}
                aria-label="Shuffle answers"
              >
                <span className="pill-toggle-thumb" />
              </button>
              <span className={`pill-toggle-state ${shuffleOpts ? 'on' : ''}`}>
                {shuffleOpts ? 'ON' : 'OFF'}
              </span>
            </div>
            <span className="num-max" style={{ marginLeft: 12 }}>
              {shuffleOpts ? 'answer order will be randomized' : 'keep original answer order'}
            </span>
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, marginTop: 8, flexWrap: 'wrap', alignItems: 'center' }}>
          <button className="btn btn-ghost btn-sm" onClick={exportQuestions} title="Download all questions with correct answers marked">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
            Export questions
          </button>
          <button className="btn btn-primary" onClick={start} disabled={count < 1}>
            Start Quiz
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
          </button>
        </div>
      </div>
    </div>
  );
}

function NumField({ value, onChange, min, max }) {
  const set = v => {
    let n = parseInt(v, 10);
    if (isNaN(n)) n = min;
    n = Math.max(min, Math.min(max, n));
    onChange(n);
  };
  return (
    <div className="num-field">
      <button onClick={() => set(value - 1)} disabled={value <= min}>−</button>
      <input type="number" value={value} min={min} max={max} onChange={e => set(e.target.value)} />
      <button onClick={() => set(value + 1)} disabled={value >= max}>+</button>
    </div>
  );
}

function ResumeCard({ paused, onResume, onDiscard }) {
  const { formatDate } = window.QuizUtils;
  const answered = paused.answers.filter(a => a != null).length;
  const total = paused.questions.length;
  const pct = Math.round((answered / total) * 100);
  return (
    <div className="card" style={{ marginBottom: 16, borderColor: 'var(--accent-border)', background: 'linear-gradient(135deg, rgba(122,162,255,0.06), transparent)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--accent-soft)', color: 'var(--accent)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><window.Icon.Pause size={20} /></div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 2 }}>Paused quiz — resume where you left off</div>
            <div style={{ fontSize: 12, color: 'var(--text-faint)', fontFamily: 'var(--mono)' }}>
              <span className={`mode-pill ${paused.mode}`} style={{ marginRight: 8 }}>{paused.mode}</span>
              {answered}/{total} answered · question {paused.current + 1} · paused {formatDate(paused.ts)}
            </div>
            <div style={{ width: 220, height: 4, background: 'var(--bg-soft)', borderRadius: 99, marginTop: 8, overflow: 'hidden' }}>
              <div style={{ width: pct + '%', height: '100%', background: 'var(--accent)' }} />
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-ghost btn-sm" onClick={onDiscard}>Discard</button>
          <button className="btn btn-primary btn-sm" onClick={onResume}>Resume <window.Icon.ArrowRight size={12} /></button>
        </div>
      </div>
    </div>
  );
}

// ==== Quiz runner ====
function QuizRunner({ mode, questions, onFinish, onQuit, onPause, initialState }) {
  const [current, setCurrent] = useS(initialState?.current ?? 0);
  const [answers, setAnswers] = useS(() => initialState?.answers ?? Array(questions.length).fill(null));
  const [hintMap, setHintMap] = useS({});
  const [revealMap, setRevealMap] = useS({});
  const [confirmFinish, setConfirmFinish] = useS(false);
  const [confirmQuit, setConfirmQuit] = useS(false);
  const startRef = useR(Date.now() - (initialState?.elapsedMs ?? 0));

  const q = questions[current];
  const answeredCount = answers.filter(a => a != null).length;

  const select = (i) => {
    const next = answers.slice();
    const q = questions[current];
    
    if (Array.isArray(q.correct)) {
      let sel = next[current] || [];
      if (!Array.isArray(sel)) sel = [sel];
      
      if (sel.includes(i)) sel = sel.filter(x => x !== i);
      else sel = [...sel, i];
      
      next[current] = sel;
    } else {
      next[current] = i;
    }
    setAnswers(next);
  };

  const go = (delta) => {
    const n = Math.max(0, Math.min(questions.length - 1, current + delta));
    setCurrent(n);
  };

  const triggerHint = () => {
    setHintMap(m => ({ ...m, [current]: (m[current] || 0) + 1 }));
  };

  const toggleReveal = () => {
    setRevealMap(m => ({ ...m, [current]: !m[current] }));
  };

  const finish = () => {
    onFinish({ answers, elapsedMs: Date.now() - startRef.current });
  };

  const pause = () => {
    onPause({ current, answers, elapsedMs: Date.now() - startRef.current });
  };

  // keyboard
  useE(() => {
    const onKey = (e) => {
      if (e.target.tagName === 'INPUT') return;
      if (e.key === 'ArrowRight') go(1);
      else if (e.key === 'ArrowLeft') go(-1);
      else if (['1','2','3','4'].includes(e.key)) select(parseInt(e.key)-1);
      else if (e.key.toLowerCase() === 'a') select(0);
      else if (e.key.toLowerCase() === 'b') select(1);
      else if (e.key.toLowerCase() === 'c') select(2);
      else if (e.key.toLowerCase() === 'd') select(3);
      else if (e.key.toLowerCase() === 'h') triggerHint();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [current, answers]);

  return (
    <div className="card">
      <ProgressHeader
        current={current}
        total={questions.length}
        answered={answeredCount}
        onQuit={() => setConfirmQuit(true)}
        onReview={() => setConfirmFinish(true)}
      />
      <QuestionNav questions={questions} answers={answers} current={current} onJump={setCurrent} />
      <QuestionView
        question={q}
        index={current}
        total={questions.length}
        selected={answers[current]}
        onSelect={select}
        onHint={triggerHint}
        hintActive={!!hintMap[current]}
        showReveal={!!revealMap[current]}
        onToggleReveal={toggleReveal}
        key={current + ':' + (hintMap[current] || 0)}
      />

      <div className="q-actions" style={{ marginTop: 24, borderTop: '1px solid var(--border)', paddingTop: 20 }}>
        <button className="btn btn-ghost" onClick={() => go(-1)} disabled={current === 0}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6"/></svg>
          Previous
        </button>
        {current < questions.length - 1 ? (
          <button className="btn btn-primary" onClick={() => go(1)}>
            Next
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m9 18 6-6-6-6"/></svg>
          </button>
        ) : (
          <button className="btn btn-primary" onClick={() => setConfirmFinish(true)}>
            Finish Quiz
          </button>
        )}
      </div>

      {confirmQuit && (
        <div className="modal-backdrop" onClick={() => setConfirmQuit(false)}>
          <div className="modal" onClick={e => e.stopPropagation()}>
            <div className="modal-head"><h3>Quit this quiz?</h3></div>
            <div className="modal-body">
              <p style={{ color: 'var(--text-dim)', fontSize: 14, marginBottom: 8 }}>
                You're on question <strong style={{ color: 'var(--text)' }}>{current + 1}</strong> of <strong style={{ color: 'var(--text)' }}>{questions.length}</strong>, with <strong style={{ color: 'var(--text)' }}>{answeredCount}</strong> answered.
              </p>
              <div style={{ display: 'grid', gap: 10, marginTop: 16 }}>
                <div style={{ padding: 14, background: 'var(--bg-soft)', border: '1px solid var(--border)', borderRadius: 8 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4, display: 'flex', alignItems: 'center', gap: 8 }}><window.Icon.Save size={14} /> Pause &amp; Save</div>
                  <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>Save your progress and resume this quiz later from where you left off.</div>
                </div>
                <div style={{ padding: 14, background: 'var(--bg-soft)', border: '1px solid var(--border)', borderRadius: 8 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4, color: 'var(--danger)', display: 'flex', alignItems: 'center', gap: 8 }}><window.Icon.Trash size={14} /> Quit without saving</div>
                  <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>Discard progress and return to the home screen. No record is saved.</div>
                </div>
              </div>
            </div>
            <div className="modal-foot">
              <button className="btn btn-ghost btn-sm" onClick={() => setConfirmQuit(false)}>Cancel</button>
              <button className="btn btn-danger btn-sm" onClick={onQuit}>Quit without saving</button>
              <button className="btn btn-primary btn-sm" onClick={pause}>Pause &amp; Save</button>
            </div>
          </div>
        </div>
      )}

      {confirmFinish && (
        <div className="modal-backdrop" onClick={() => setConfirmFinish(false)}>
          <div className="modal" onClick={e => e.stopPropagation()}>
            <div className="modal-head"><h3>Finish quiz?</h3></div>
            <div className="modal-body">
              <p style={{ color: 'var(--text-dim)', fontSize: 14, marginBottom: 12 }}>
                You've answered <strong style={{ color: 'var(--text)' }}>{answeredCount}</strong> of <strong style={{ color: 'var(--text)' }}>{questions.length}</strong> questions.
                {answeredCount < questions.length && ' Unanswered questions will count as skipped.'}
              </p>
            </div>
            <div className="modal-foot">
              <button className="btn btn-ghost btn-sm" onClick={() => setConfirmFinish(false)}>Keep going</button>
              <button className="btn btn-primary btn-sm" onClick={finish}>See results</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ==== Root app ====
function App() {
  const [tab, setTab] = useS('home'); // home | records
  const [phase, setPhase] = useS('setup'); // setup | running | celebrate | results
  const [session, setSession] = useS(null);
  const [pausedSession, setPausedSession] = useS(() => window.Store.getPaused());
  const [resumeToast, setResumeToast] = useS(false);

  const startQuiz = ({ mode, questions }) => {
    setSession({ mode, questions, answers: null, elapsedMs: 0, initialState: null });
    setPhase('running');
  };

  const resumeQuiz = () => {
    const p = window.Store.getPaused();
    if (!p) return;
    setSession({
      mode: p.mode,
      questions: p.questions,
      answers: null,
      elapsedMs: 0,
      initialState: { current: p.current, answers: p.answers, elapsedMs: p.elapsedMs },
    });
    setPhase('running');
  };

  const pauseQuiz = ({ current, answers, elapsedMs }) => {
    if (!session) return;
    const data = {
      ts: Date.now(),
      mode: session.mode,
      questions: session.questions,
      current, answers, elapsedMs,
    };
    window.Store.savePaused(data);
    setPausedSession(data);
    setSession(null);
    setPhase('setup');
    setTab('home');
    setResumeToast(true);
    setTimeout(() => setResumeToast(false), 2600);
  };

  const discardPaused = () => {
    window.Store.clearPaused();
    setPausedSession(null);
  };

  const finishQuiz = ({ answers, elapsedMs }) => {
    window.Store.clearPaused();
    setPausedSession(null);
    setSession(s => {
      const qs = s.questions;
      let c = 0, w = 0, sk = 0;
      answers.forEach((a, i) => {
        if (a == null || (Array.isArray(a) && a.length === 0)) sk++;
        else {
          const isCorrect = Array.isArray(qs[i].correct) 
            ? (Array.isArray(a) && a.length === qs[i].correct.length && qs[i].correct.every(x => a.includes(x)))
            : a === qs[i].correct;
          if (isCorrect) c++;
          else w++;
        }
      });
      const p = qs.length > 0 ? Math.round((c / qs.length) * 100) : 0;
      const rec = {
        id: `rec_${Date.now()}`,
        ts: Date.now(),
        mode: s.mode,
        total: qs.length,
        correct: c, wrong: w, skipped: sk, pct: p,
        durationMs: elapsedMs,
        details: qs.map((q, i) => ({
          source: q.source, num: q.num, q: q.q,
          correct: q.correct, answered: answers[i], options: q.options,
        })),
      };
      window.Store.add(rec);
      return { ...s, answers, elapsedMs, savedRecord: rec };
    });
    setPhase('celebrate');
  };

  const restart = () => {
    setSession(null);
    setPhase('setup');
    setTab('home');
  };

  const quit = () => {
    window.Store.clearPaused();
    setPausedSession(null);
    setSession(null);
    setPhase('setup');
    setTab('home');
  };

  // For computing celebration stats
  const celStats = useM(() => {
    if (!session || !session.answers) return null;
    const qs = session.questions;
    let correct = 0, wrong = 0, skipped = 0;
    session.answers.forEach((a, i) => {
      if (a == null || (Array.isArray(a) && a.length === 0)) skipped++;
      else {
        const isCorrect = Array.isArray(qs[i].correct) 
          ? (Array.isArray(a) && a.length === qs[i].correct.length && qs[i].correct.every(x => a.includes(x)))
          : a === qs[i].correct;
        if (isCorrect) correct++;
        else wrong++;
      }
    });
    const pct = qs.length > 0 ? Math.round((correct / qs.length) * 100) : 0;
    return { correct, wrong, skipped, pct, total: qs.length };
  }, [session]);

  return (
    <div className="app">
      <div className="header">
        <div className="brand">
          <div className="brand-mark">🛡</div>
          <div className="brand-text">
            <h1>Quize</h1>
            <p>Cybersecurity exam practice</p>
          </div>
        </div>
        <div className="header-actions">
          {phase === 'running' && <span style={{ fontSize: 12, color: 'var(--text-faint)', fontFamily: 'var(--mono)' }}>A/B/C/D · H hint · ← →</span>}
        </div>
      </div>

      {phase === 'setup' && (
        <>
          <div className="tabs">
            <button className={`tab ${tab === 'home' ? 'active' : ''}`} onClick={() => setTab('home')}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
              Practice
            </button>
            <button className={`tab ${tab === 'records' ? 'active' : ''}`} onClick={() => setTab('records')}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
              History
              <span className="tab-count">{window.Store.all().length}</span>
            </button>
          </div>
          {tab === 'home' && <>
            {pausedSession && <ResumeCard paused={pausedSession} onResume={resumeQuiz} onDiscard={discardPaused} />}
            <SetupPanel onStart={startQuiz} />
          </>}
          {tab === 'records' && <RecordsView />}
        </>
      )}

      {phase === 'running' && session && (
        <QuizRunner
          mode={session.mode}
          questions={session.questions}
          initialState={session.initialState}
          onFinish={finishQuiz}
          onQuit={quit}
          onPause={pauseQuiz}
        />
      )}

      {phase === 'celebrate' && session && celStats && (
        <CelebrationModal
          record={session.savedRecord}
          correct={celStats.correct}
          wrong={celStats.wrong}
          skipped={celStats.skipped}
          total={celStats.total}
          pct={celStats.pct}
          elapsedMs={session.elapsedMs}
          onReview={() => setPhase('results')}
          onRestart={restart}
          onHome={() => { setTab('home'); restart(); }}
          onHistory={() => { setSession(null); setPhase('setup'); setTab('records'); }}
        />
      )}

      {phase === 'results' && session && (
        <ResultsView
          questions={session.questions}
          answers={session.answers}
          elapsedMs={session.elapsedMs}
          mode={session.mode}
          onRestart={restart}
          onHome={restart}
        />
      )}
      {resumeToast && (
        <div className="toast" style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><window.Icon.Save size={14} /> Progress saved. Come back anytime to resume.</div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
