import { ArrowLeft, ArrowRight, Check, CircleCheck, CircleX, Clock, Flag, LayoutGrid, RotateCcw, X } from 'lucide-react';
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { isFullyCorrect, letterGrade, optionLetter, parseNumericAnswer, scoreQuestion, type SataScoring } from '@shared/content';
import type { AnswerState, SnapshotQuestion } from '@/lib/types';
import { cx, formatDuration, formatMinutes, plural, useHotkeys, useLatest } from '@/lib/util';
import { Markdown } from '@/ui/Markdown';
import { formatRationale } from '@shared/rationale';
import { Badge, Button, Dialog, IconButton, Input, ProgressBar, Segmented, useConfirm } from '@/ui';
import { ExplainSideContext } from './Explain';
/* ------------------------------ option list ------------------------------ */
function OptionList({
question,
selected,
revealed,
onToggle,
}: {
question: SnapshotQuestion;
selected: string[];
/** Show which choices are correct (after checking in practice, or in review). */
revealed: boolean;
onToggle?: (id: string) => void;
}) {
const multi = question.type === 'multi';
return (
{question.options.map((o, i) => {
const picked = selected.includes(o.id);
const state = !revealed ? (picked ? 'picked' : 'idle') : o.correct ? (picked ? 'right' : 'missed') : picked ? 'wrong' : 'idle';
const styles = {
idle: 'border-line-strong bg-surface',
picked: 'border-accent bg-accent-soft ring-1 ring-accent',
right: 'border-good bg-good-soft ring-1 ring-good',
missed: 'border-good/60 bg-surface border-dashed',
wrong: 'border-bad bg-bad-soft ring-1 ring-bad',
}[state];
const key = {
idle: 'border-line-strong text-ink-3 bg-surface',
picked: 'border-accent bg-accent text-accent-ink',
right: 'border-good bg-good text-white dark:text-[#10241a]',
missed: 'border-good text-good bg-surface',
wrong: 'border-bad bg-bad text-white dark:text-[#2a1210]',
}[state];
return (
onToggle?.(o.id)}
className={cx('flex w-full items-start gap-3 rounded-[14px] border px-3.5 py-3 text-left transition-[background,border-color,box-shadow] disabled:cursor-default', styles, !revealed && onToggle && 'hover:border-ink-3 active:scale-[0.995]')}
>
{state === 'right' || state === 'missed' ? : state === 'wrong' ? : optionLetter(i)}
{o.text}
{revealed && (state === 'missed' || state === 'wrong' || state === 'right') && (
{state === 'right' ? 'Correct' : state === 'missed' ? (multi ? 'Correct, not selected' : 'Correct answer') : 'Your answer'}
)}
{revealed && o.why && {o.why} }
);
})}
);
}
/* ------------------------------ numeric answer ------------------------------ */
/** The accepted answer(s) of a numeric question, for display. */
function acceptedAnswers(question: SnapshotQuestion): string {
return question.options
.filter((o) => o.correct !== false)
.map((o) => o.text)
.join(' or ');
}
/** A calculation: the student types the number. Units are optional; only the number is checked. */
function NumericAnswer({
question,
value,
revealed,
onChange,
onSubmit,
autoFocus,
}: {
question: SnapshotQuestion;
value: string;
revealed: boolean;
onChange?: (text: string) => void;
onSubmit?: () => void;
autoFocus?: boolean;
}) {
const right = revealed && isFullyCorrect(scoreQuestion(question, value ? [value] : []));
const unreadable = value.trim() !== '' && parseNumericAnswer(value) === null;
const why = question.options.find((o) => o.why)?.why;
return (
Your answer
onChange?.(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.nativeEvent.isComposing) {
e.preventDefault();
onSubmit?.();
}
}}
placeholder="Type your answer, e.g. 12.5"
aria-invalid={unreadable || undefined}
className={cx(
'num h-14 max-w-sm rounded-[14px] px-4 text-[20px]',
revealed && (right ? 'border-good bg-good-soft ring-1 ring-good' : 'border-bad bg-bad-soft ring-1 ring-bad'),
)}
/>
{!revealed && unreadable &&
Enter a number.
}
{revealed && (
Correct answer
{acceptedAnswers(question)}
{why &&
{why}
}
)}
);
}
/** What the student answered, as text (for the AI explanation). */
function answerTexts(question: SnapshotQuestion, selected: string[]): string[] {
if (question.type === 'numeric') return selected.slice(0, 1);
return question.options.filter((o) => selected.includes(o.id)).map((o) => o.text);
}
/** Tone for a percentage on the 7-point scale: A and B good, C passing, D and F failing. */
export function gradeToneFor(percent: number): 'good' | 'warn' | 'bad' {
const letter = letterGrade(percent);
return letter === 'A' || letter === 'B' ? 'good' : letter === 'C' ? 'warn' : 'bad';
}
/** "2 of 3" style credit for a select-all question, so partial credit is never a mystery. */
function creditDetail(question: SnapshotQuestion, selected: string[], sata: SataScoring): string | null {
if (question.type !== 'multi') return null;
const correctIds = question.options.filter((o) => o.correct).map((o) => o.id);
const right = selected.filter((id) => correctIds.includes(id)).length;
const wrong = selected.length - right;
if (right === correctIds.length && wrong === 0) return null;
if (sata === 'strict') return 'All-or-nothing scoring is on, so every correct choice (and no others) is needed for credit.';
const earned = Math.max(0, right - wrong);
return `Partial credit: ${right} correct ${right === 1 ? 'choice' : 'choices'}${wrong > 0 ? ` minus ${wrong} incorrect` : ''} = ${earned} of ${correctIds.length} ${correctIds.length === 1 ? 'point' : 'points'} for this question.`;
}
const fmtPoints = (n: number) => (Number.isInteger(n) ? String(n) : n.toFixed(1));
function Verdict({ score, detail }: { score: number; detail?: string | null }) {
const full = isFullyCorrect(score);
const partial = !full && score > 0;
return (
{full ? : }
{full ? 'Correct' : partial ? `Partly correct (${Math.round(score * 100)}%)` : 'Incorrect'}
{detail &&
{detail}
}
);
}
/* ------------------------------ runner ------------------------------ */
export interface RunnerProps {
title: string;
mode: 'practice' | 'exam';
questions: SnapshotQuestion[];
answers: Record;
flags: string[];
index: number;
elapsedSec: number;
timeLimitSec: number | null;
/**
* Fixed end time on this device's clock. When set, the countdown follows the wall clock
* and keeps running while the page is hidden or closed. Without it the clock pauses.
*/
deadlineAt?: number | null;
sataScoring: SataScoring;
onAnswer: (questionId: string, selected: string[], checked: boolean) => void;
onFlags: (flags: string[]) => void;
onIndex: (index: number) => void;
/** Called every few seconds with the running clock so progress can be saved. */
onTick?: (elapsedSec: number) => void;
onFinish: (elapsedSec: number) => void;
onExit: () => void;
finishing?: boolean;
/** Extra content under the rationale (AI explanation). */
renderExtra?: (question: SnapshotQuestion, selectedTexts: string[]) => ReactNode;
exitLabel?: string;
}
export function QuizRunner(p: RunnerProps) {
const confirm = useConfirm();
const [elapsed, setElapsed] = useState(p.elapsedSec);
const [navOpen, setNavOpen] = useState(false);
// Room the Explain panel needs on the right on smaller screens (0 = question stays centred).
const [explainReserve, setExplainReserve] = useState(0);
const explainSide = useMemo(() => ({ reserve: setExplainReserve }), []);
const topRef = useRef(null);
const tick = useLatest(p.onTick);
const finish = useLatest(p.onFinish);
const autoSubmitted = useRef(false);
const total = p.questions.length;
const index = Math.min(p.index, total - 1);
const question = p.questions[index];
const answer = p.answers[question.id];
const selected = answer?.selected ?? [];
const checked = p.mode === 'practice' && Boolean(answer?.checked);
const answeredCount = p.questions.filter((q) => (p.mode === 'practice' ? p.answers[q.id]?.checked : (p.answers[q.id]?.selected.length ?? 0) > 0)).length;
const flagged = p.flags.includes(question.id);
const isLast = index === total - 1;
// Running score for practice mode (select-all questions can earn part of a point).
const live = useMemo(() => {
if (p.mode !== 'practice') return null;
let n = 0;
let points = 0;
for (const q of p.questions) {
const a = p.answers[q.id];
if (!a?.checked) continue;
n += 1;
points += scoreQuestion(q, a.selected, p.sataScoring);
}
return n > 0 ? { n, points, percent: Math.round((points / n) * 100) } : null;
}, [p.mode, p.questions, p.answers, p.sataScoring]);
const [wallNow, setWallNow] = useState(() => Date.now());
const deadline = p.deadlineAt && p.timeLimitSec !== null ? p.deadlineAt : null;
const remaining = deadline !== null ? Math.max(0, Math.ceil((deadline - wallNow) / 1000)) : p.timeLimitSec !== null ? Math.max(0, p.timeLimitSec - elapsed) : null;
// Time used: wall clock for deadline exams, otherwise the active-study clock.
const clock = deadline !== null && p.timeLimitSec !== null ? Math.max(elapsed, p.timeLimitSec - (remaining ?? 0)) : elapsed;
const clockRef = useLatest(clock);
useEffect(() => {
const timer = setInterval(() => {
setWallNow(Date.now());
// The untimed/legacy clock pauses while the tab is hidden.
if (document.visibilityState === 'visible') setElapsed((e) => e + 1);
}, 1000);
// Catch up immediately when returning to a deadline exam.
const onVisible = () => document.visibilityState === 'visible' && setWallNow(Date.now());
document.addEventListener('visibilitychange', onVisible);
return () => {
clearInterval(timer);
document.removeEventListener('visibilitychange', onVisible);
};
}, []);
useEffect(() => {
if (elapsed > 0 && elapsed % 10 === 0) tick.current?.(clockRef.current);
}, [elapsed, tick, clockRef]);
useEffect(() => {
if (remaining === 0 && !p.finishing && !autoSubmitted.current) {
autoSubmitted.current = true;
finish.current(clockRef.current);
}
}, [remaining, p.finishing, finish, clockRef]);
useEffect(() => {
topRef.current?.scrollIntoView({ block: 'start' });
}, [index]);
const numeric = question.type === 'numeric';
const toggle = (id: string) => {
if (checked || numeric) return;
const next = question.type === 'single' ? [id] : selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id];
p.onAnswer(question.id, next, false);
};
const typed = numeric ? (selected[0] ?? '') : '';
const setTyped = (text: string) => !checked && p.onAnswer(question.id, text.trim() ? [text] : [], false);
const canCheck = numeric ? parseNumericAnswer(typed) !== null : selected.length > 0;
const check = () => {
if (!canCheck) return;
// Let the typed answer show its correct/incorrect colour instead of the focus ring.
if (numeric) (document.activeElement as HTMLElement | null)?.blur();
p.onAnswer(question.id, numeric ? [typed.trim()] : selected, true);
};
const go = (i: number) => p.onIndex(Math.max(0, Math.min(total - 1, i)));
const toggleFlag = () => p.onFlags(flagged ? p.flags.filter((f) => f !== question.id) : [...p.flags, question.id]);
const requestFinish = async () => {
const unanswered = total - answeredCount;
if (unanswered > 0) {
const ok = await confirm(
p.mode === 'exam'
? { title: 'Submit the exam?', message: `${plural(unanswered, 'question')} ${unanswered === 1 ? 'is' : 'are'} unanswered and will be marked wrong.`, confirmLabel: 'Submit' }
: { title: 'Finish now?', message: `You have answered ${answeredCount} of ${total}. Only answered questions are scored.`, confirmLabel: 'Finish' },
);
if (!ok) return;
}
p.onFinish(clock);
};
const primary = () => {
if (p.mode === 'practice' && !checked) return check();
if (isLast) return void requestFinish();
go(index + 1);
};
useHotkeys({
...(numeric ? {} : Object.fromEntries(question.options.map((o, i) => [String(i + 1), () => toggle(o.id)]))),
...(numeric ? {} : Object.fromEntries(question.options.map((o, i) => [optionLetter(i).toLowerCase(), () => toggle(o.id)]))),
Enter: primary,
ArrowRight: () => go(index + 1),
ArrowLeft: () => go(index - 1),
// "f" doubles as choice F on six-option questions; the flag keeps a dedicated key too.
...(question.options.length < 6 ? { f: toggleFlag } : {}),
m: toggleFlag,
});
const score = checked ? scoreQuestion(question, selected, p.sataScoring) : 0;
const statusOf = (q: SnapshotQuestion) => {
const a = p.answers[q.id];
if (p.mode === 'practice' && a?.checked) return isFullyCorrect(scoreQuestion(q, a.selected, p.sataScoring)) ? 'right' : 'wrong';
return (a?.selected.length ?? 0) > 0 ? 'answered' : 'blank';
};
return (
Question {index + 1}
{question.topic && {question.topic} }
{flagged && (
Flagged
)}
{question.stem}
{question.type === 'multi' ? 'Select all that apply.' : numeric ? 'Enter your answer.' : 'Choose one answer.'}
{numeric ? (
) : (
)}
{checked && (
{question.rationale && (
Rationale
{formatRationale(question.rationale)}
)}
{p.renderExtra?.(question, answerTexts(question, selected))}
)}
} onClick={() => go(index - 1)} disabled={index === 0} aria-label="Previous question">
Back
} onClick={toggleFlag} aria-pressed={flagged}>
{flagged ? 'Flagged' : 'Flag'}
{p.mode === 'practice' && !checked ? (
<>
(isLast ? requestFinish() : go(index + 1))}>
{isLast ? 'Finish' : 'Skip'}
Check
>
) : isLast ? (
{p.mode === 'exam' ? 'Submit exam' : 'See results'}
) : (
<>
{p.mode === 'exam' && answeredCount === total && (
Submit
)}
go(index + 1)} className="min-w-32">
Next
>
)}
(setNavOpen(false), void requestFinish())}>
{p.mode === 'exam' ? 'Submit exam' : 'Finish'}
}
>
{/* Padding keeps the current-question ring (and its offset) inside the scroll area. */}
{p.questions.map((q, i) => {
const s = statusOf(q);
return (
(go(i), setNavOpen(false))}
className={cx(
'num relative grid aspect-square place-items-center rounded-[10px] border text-sm font-semibold',
s === 'right' ? 'border-good bg-good-soft text-good' : s === 'wrong' ? 'border-bad bg-bad-soft text-bad' : s === 'answered' ? 'border-ink bg-ink text-paper' : 'border-line-strong text-ink-2 hover:border-ink-3',
i === index && 'ring-2 ring-accent ring-offset-2 ring-offset-surface',
)}
>
{i + 1}
{p.flags.includes(q.id) && }
);
})}
);
}
/* ------------------------------ results ------------------------------ */
type ScoreTier = 'perfect' | 'a' | 'b' | 'c' | 'fail';
/** Bands of the 7-point scale: 93+ green, 85-92 blue, 77-84 yellow, below 77 (failing) red; 100% is a rainbow. */
export function scoreTier(percent: number): ScoreTier {
const p = Math.round(percent);
return p >= 100 ? 'perfect' : p >= 93 ? 'a' : p >= 85 ? 'b' : p >= 77 ? 'c' : 'fail';
}
const TIER_COLOR: Record, string> = { a: 'var(--good)', b: 'var(--accent)', c: 'var(--score-yellow)', fail: 'var(--bad)' };
/** The result ring: fills up and counts to the score; a perfect score cycles through a rainbow. */
function ScoreRing({ percent, size = 136, stroke = 12 }: { percent: number; size?: number; stroke?: number }) {
const tier = scoreTier(percent);
const [shown, setShown] = useState(0);
useEffect(() => {
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return setShown(percent);
let frame = 0;
const started = performance.now();
const tick = (now: number) => {
const t = Math.min(1, (now - started) / 1100);
setShown(Math.round(percent * (1 - (1 - t) ** 3)));
if (t < 1) frame = requestAnimationFrame(tick);
};
frame = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame);
}, [percent]);
const r = (size - stroke) / 2;
const c = 2 * Math.PI * r;
const gid = `score-${size}`;
return (
{tier === 'perfect' && (
)}
{shown}
%
{tier === 'perfect' && shown === 100 && (
{[0, 1, 2, 3, 4, 5, 6, 7].map((i) => (
))}
)}
);
}
export interface ResultsProps {
title: string;
mode: 'practice' | 'exam';
questions: SnapshotQuestion[];
answers: Record;
flags: string[];
elapsedSec: number;
sataScoring: SataScoring;
completedAt?: number | null;
actions: ReactNode;
onExit: () => void;
exitLabel?: string;
renderExtra?: (question: SnapshotQuestion, selectedTexts: string[]) => ReactNode;
footnote?: ReactNode;
}
export function QuizResults(p: ResultsProps) {
const [filter, setFilter] = useState<'all' | 'wrong' | 'flagged'>('all');
const rows = useMemo(
() =>
p.questions.map((q, i) => {
const selected = p.answers[q.id]?.selected ?? [];
const answered = selected.length > 0;
const score = scoreQuestion(q, selected, p.sataScoring);
return { q, i, selected, answered, score, correct: isFullyCorrect(score), scored: p.mode === 'exam' || answered };
}),
[p.questions, p.answers, p.sataScoring, p.mode],
);
const scored = rows.filter((r) => r.scored);
const points = scored.reduce((n, r) => n + r.score, 0);
const percent = scored.length ? Math.round((points / scored.length) * 100) : 0;
const right = scored.filter((r) => r.correct).length;
const partial = scored.filter((r) => !r.correct && r.score > 0).length;
const wrong = scored.length - right - partial;
const skipped = rows.length - scored.length;
const topics = useMemo(() => {
const map = new Map();
for (const r of scored) {
const key = r.q.topic || 'General';
const cur = map.get(key) ?? { n: 0, s: 0 };
cur.n += 1;
cur.s += r.score;
map.set(key, cur);
}
return [...map.entries()].map(([topic, v]) => ({ topic, n: v.n, accuracy: v.s / v.n })).sort((a, b) => a.accuracy - b.accuracy);
}, [scored]);
const visible = rows.filter((r) => (filter === 'all' ? true : filter === 'wrong' ? r.scored && !r.correct : p.flags.includes(r.q.id)));
const tier = scoreTier(percent);
const headline = { perfect: 'Perfect score!', a: 'Excellent work', b: 'Strong result', c: 'Passing', fail: 'Worth another pass' }[tier];
return (
{p.mode === 'exam' ? 'Exam result' : 'Practice result'}
{headline}
{fmtPoints(points)} of {scored.length} points
{p.elapsedSec > 0 ? ` in ${formatMinutes(p.elapsedSec)}` : ''}
{skipped > 0 ? `. ${plural(skipped, 'question')} skipped and not scored.` : '.'}
{right} correct
{partial > 0 && {partial} partly }
{wrong > 0 && {wrong} incorrect }
{p.actions}
{p.footnote && {p.footnote}
}
{topics.length > 1 && (
By topic
{topics.map((t) => {
const pc = Math.round(t.accuracy * 100);
return (
{t.topic}
{plural(t.n, 'question')}
{pc}%
);
})}
)}
Review
0 ? [{ value: 'flagged' as const, label: `Flagged ${p.flags.length}` }] : []),
]}
/>
{visible.length === 0 ? (
{filter === 'wrong' ? 'Nothing missed. Every scored question was correct.' : 'No questions here.'}
) : (
{visible.map((r) => (
{String(r.i + 1).padStart(2, '0')}
{!r.scored ? Skipped : r.correct ? Correct : r.score > 0 ? Partly correct : {r.answered ? 'Incorrect' : 'Not answered'} }
{r.q.topic && {r.q.topic} }
{p.flags.includes(r.q.id) && (
Flagged
)}
{r.q.stem}
{r.q.type === 'numeric' ? : }
{r.scored && !r.correct && r.answered && creditDetail(r.q, r.selected, p.sataScoring) && {creditDetail(r.q, r.selected, p.sataScoring)}
}
{r.q.rationale && (
Rationale
{formatRationale(r.q.rationale)}
)}
{p.renderExtra && (
{p.renderExtra(r.q, answerTexts(r.q, r.selected))}
)}
))}
)}
);
}
export function RetakeIcon() {
return ;
}