// Mock Tests — list, runner, results. // Sections: reading, listening, writing, speaking. Backend stores all content; // frontend pulls test, renders the right runner, and submits answers for scoring. // In-progress-attempt draft persistence — a page refresh or crash during a // timed test used to lose all answers with no recovery. Keyed per test id so // switching tests (or the browser being closed and reopened) doesn't mix // drafts. Best-effort: localStorage failures (private browsing quota, etc.) // are swallowed, matching how the rest of this app treats localStorage. function draftKey(testId) { return `ielts_test_draft_${testId}`; } function saveDraft(testId, data) { try { localStorage.setItem(draftKey(testId), JSON.stringify({ ...data, savedAt: Date.now() })); } catch {} } function loadDraft(testId) { try { const raw = localStorage.getItem(draftKey(testId)); if (!raw) return null; const parsed = JSON.parse(raw); // Drafts older than 24h are probably from an abandoned attempt on a test // whose content may have since changed — don't silently resurrect them. if (!parsed.savedAt || Date.now() - parsed.savedAt > 24 * 3600 * 1000) return null; return parsed; } catch { return null; } } function clearDraft(testId) { try { localStorage.removeItem(draftKey(testId)); } catch {} } const SECTION_META = { reading: { label: 'Reading', icon: 'book', color: 'var(--primary)', bg: 'var(--primary-soft)', durationDefault: 3600 }, listening: { label: 'Listening', icon: 'volume', color: 'var(--accent)', bg: 'var(--accent-soft)', durationDefault: 1800 }, writing: { label: 'Writing', icon: 'edit', color: 'var(--success)', bg: 'var(--success-soft)', durationDefault: 2400 }, speaking: { label: 'Speaking', icon: 'volume', color: 'var(--gold)', bg: 'var(--gold-soft)', durationDefault: 840 }, }; // ─── Top-level Mock Tests page ──────────────────────────────────────────── function MockTests({ state, update }) { const [view, setView] = useState('list'); // 'list' | 'runner' | 'result' | 'history' const [activeTest, setActiveTest] = useState(null); // test object from backend (with content) const [activeResult, setActiveResult] = useState(null); const startTest = async (testId) => { if (!window.apiClient.isConfigured()) { alert('Mock tests require a backend connection. Sign in to continue.'); return; } try { const { test } = await window.apiClient.tests.get(testId); setActiveTest(test); setView('runner'); } catch (e) { alert(e.message || 'Could not load test.'); } }; const finishTest = (result) => { setActiveResult(result); setActiveTest(null); setView('result'); // Note progress let s = state; const sec = result.section; if (sec === 'reading') s = window.planEngine.noteProgress(s, { readingSection: true }); if (sec === 'listening') s = window.planEngine.noteProgress(s, { listeningSection: true }); if (sec === 'writing') { s = window.planEngine.noteProgress(s, result.task === 1 ? { writingTask1: true } : { writingTask2: true }); } if (sec === 'speaking') s = window.planEngine.noteProgress(s, { speakingSet: true }); update(s); }; if (view === 'runner' && activeTest) { return { setActiveTest(null); setView('list'); }} />; } if (view === 'result' && activeResult) { return { setActiveResult(null); setView('list'); }} />; } if (view === 'history') { return setView('list')} onPick={() => {}} />; } return setView('history')} />; } // ─── Tests list ──────────────────────────────────────────────────────────── function TestsList({ state, onStart, onShowHistory }) { const [tests, setTests] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); const [section, setSection] = useState('all'); const [generating, setGenerating] = useState(false); const [genError, setGenError] = useState(''); const [showGenMenu, setShowGenMenu] = useState(false); const examType = state.profile?.examType || 'academic'; const generateTest = async (sec) => { setShowGenMenu(false); setGenerating(true); setGenError(''); try { const res = await window.apiClient.call('/api/ai/generate-test', { method: 'POST', body: { section: sec, exam_type: examType }, }); const data = res.data || res; if (data && data.test_id) onStart(data.test_id); else throw new Error('Generation did not return a test.'); } catch (e) { setGenError(e.message || 'Could not generate a test. The AI may be busy — please try again.'); } setGenerating(false); }; useEffect(() => { if (!window.apiClient.isConfigured()) { setError('The backend isn\'t configured yet — mock tests need a connection. Set up the backend (see docs/DEPLOY.md) or work in guest mode for vocabulary, grammar, and writing practice.'); setLoading(false); return; } if (!state.auth?.user) { setError('Sign in (free) to unlock mock tests — your attempts, scores, and history sync across devices.'); setLoading(false); return; } setLoading(true); window.apiClient.tests.list({ exam_type: examType }) .then(r => setTests(r.tests || [])) .catch(e => setError(e.message || 'Failed to load tests.')) .finally(() => setLoading(false)); }, [examType]); const filtered = useMemo(() => { if (!tests) return []; return section === 'all' ? tests : tests.filter(t => t.section === section); }, [tests, section]); const grouped = useMemo(() => { const g = { reading: [], listening: [], writing: [], speaking: [] }; for (const t of filtered) (g[t.section] = g[t.section] || []).push(t); return g; }, [filtered]); return (
Mock tests · {examType}

Take a mock test.

Practice individual sections under exam conditions, or take a full mock when you're ready.

{showGenMenu && !generating && (
Choose a section
{[['reading', '📖 Reading'], ['listening', '🎧 Listening'], ['writing', '✍️ Writing'], ['speaking', '🗣️ Speaking']].map(([s, label]) => ( ))}
)}
{!loading && !error && (
✨ Unlimited practice: press Generate a test, pick any section, and you get a test you have not done yet — served instantly from the bank, or freshly written by AI once you have done them all.
)} {loading &&
Loading tests…
} {genError && (
⚠ {genError}
)} {error && (
Heads up
{error}
)} {!loading && !error && ( <>
{['all', 'reading', 'listening', 'writing', 'speaking'].map(s => ( ))}
{filtered.length === 0 && (
No tests in this category yet.
If you're an admin, head to Settings → Admin to add some.
)} {section === 'all' ? (
{Object.entries(grouped).map(([sec, list]) => list.length > 0 && ( ))}
) : ( )} )}
); } function SectionGroup({ section, tests, onStart, hideHeader }) { const meta = SECTION_META[section] || {}; return (
{!hideHeader && (
{meta.label}
{tests.length} test{tests.length !== 1 ? 's' : ''}
)}
{tests.map(t => ( ))}
); } // ─── Test Runner ─────────────────────────────────────────────────────────── // Picks the right sub-runner based on test.section. function TestRunner({ test, state, onFinish, onCancel }) { if (test.section === 'reading') return ; if (test.section === 'listening') return ; if (test.section === 'writing') return ; if (test.section === 'speaking') return ; return
Unknown section type.
; } // ─── Timer ───────────────────────────────────────────────────────────────── function Timer({ totalSeconds, onExpire, paused }) { const [remaining, setRemaining] = useState(totalSeconds); useEffect(() => { if (paused) return; const t = setInterval(() => setRemaining(r => Math.max(0, r - 1)), 1000); return () => clearInterval(t); }, [paused]); // onExpire (usually the runner's `submit`) is a fresh function identity on // every parent re-render — including one triggered by onExpire's own // setSubmitting(true) call. Depending on it directly re-fired this effect // on every such re-render even though `remaining` was still 0, causing a // duplicate submit. Route through a ref instead so only `remaining` // actually re-running the effect. const onExpireRef = useRef(onExpire); onExpireRef.current = onExpire; const firedRef = useRef(false); useEffect(() => { if (remaining === 0 && !firedRef.current) { firedRef.current = true; onExpireRef.current?.(); } }, [remaining]); const m = Math.floor(remaining / 60), s = remaining % 60; const danger = remaining < 60; return (
{String(m).padStart(2, '0')}:{String(s).padStart(2, '0')}
); } // ─── Reading Runner ──────────────────────────────────────────────────────── function ReadingRunner({ test, state, onFinish, onCancel }) { const c = test.content; const draft = useMemo(() => loadDraft(test.id), [test.id]); const [answers, setAnswers] = useState(() => draft?.answers || {}); const [submitting, setSubmitting] = useState(false); const [confirmSubmit, setConfirmSubmit] = useState(false); const startedAt = useRef(draft?.startedAt || Date.now()); const allQs = useMemo(() => collectQuestions(c), [c]); const answered = Object.keys(answers).filter(k => answers[k] !== '' && answers[k] != null).length; useEffect(() => { saveDraft(test.id, { answers, startedAt: startedAt.current }); }, [answers, test.id]); const submit = async () => { if (submitting) return; // re-entrancy guard: manual click racing timer expiry, etc. setSubmitting(true); try { const res = await window.apiClient.tests.submit(test.id, { answers, started_at: startedAt.current, completed_at: Date.now(), duration_seconds: Math.round((Date.now() - startedAt.current) / 1000), }); clearDraft(test.id); onFinish({ ...res, section: 'reading', test }); } catch (e) { alert(e.message || 'Submission failed.'); setSubmitting(false); setConfirmSubmit(false); } }; return (
{ clearDraft(test.id); onCancel(); }} onTimerExpire={submit} />
{c.title || 'Reading passage'}
{c.instructions &&

{c.instructions}

}
{c.passage}
{allQs.map((q, i) => setAnswers(a => ({ ...a, [q.id]: v }))} />)}
{!confirmSubmit ? ( ) : ( <> )}
); } // ─── Listening Runner ────────────────────────────────────────────────────── function ListeningRunner({ test, state, onFinish, onCancel }) { const c = test.content; const draft = useMemo(() => loadDraft(test.id), [test.id]); const [answers, setAnswers] = useState(() => draft?.answers || {}); const [submitting, setSubmitting] = useState(false); const [confirmSubmit, setConfirmSubmit] = useState(false); const [playing, setPlaying] = useState(false); const [playCount, setPlayCount] = useState(() => draft?.playCount || 0); const startedAt = useRef(draft?.startedAt || Date.now()); const allQs = useMemo(() => collectQuestions(c), [c]); const answered = Object.keys(answers).filter(k => answers[k] !== '' && answers[k] != null).length; useEffect(() => { saveDraft(test.id, { answers, playCount, startedAt: startedAt.current }); }, [answers, playCount, test.id]); const playLimit = c.playLimit || 2; const audioMode = c.audioMode || (test.audio_url ? 'file' : 'tts'); const playTTS = () => { if (playCount >= playLimit) return; setPlaying(true); const u = new SpeechSynthesisUtterance(c.transcript); u.lang = 'en-US'; u.rate = 0.95; const voices = window.speechSynthesis.getVoices(); const v = voices.find(v => /en-/i.test(v.lang)); if (v) u.voice = v; u.onend = () => { setPlaying(false); setPlayCount(c => c + 1); }; u.onerror = () => { setPlaying(false); }; window.speechSynthesis.cancel(); window.speechSynthesis.speak(u); }; const stopTTS = () => { window.speechSynthesis.cancel(); setPlaying(false); }; const submit = async () => { if (submitting) return; // re-entrancy guard: manual click racing timer expiry, etc. setSubmitting(true); try { const res = await window.apiClient.tests.submit(test.id, { answers, started_at: startedAt.current, completed_at: Date.now(), duration_seconds: Math.round((Date.now() - startedAt.current) / 1000), }); clearDraft(test.id); onFinish({ ...res, section: 'listening', test }); } catch (e) { alert(e.message || 'Submission failed.'); setSubmitting(false); setConfirmSubmit(false); } }; return (
{ clearDraft(test.id); onCancel(); }} onTimerExpire={submit} /> {/* Audio controls */}
Audio
{c.title}
{c.context &&
{c.context}
}
{audioMode === 'tts' ? ( <> {!playing ? ( ) : ( )} ) : test.audio_url ? ( ) : ( Audio not available. )}
{/* Questions */}
{allQs.map((q, i) => setAnswers(a => ({ ...a, [q.id]: v }))} />)}
{!confirmSubmit ? ( ) : ( <> )}
); } // ─── Writing Runner ──────────────────────────────────────────────────────── function WritingRunner({ test, state, onFinish, onCancel }) { const c = test.content; const taskNum = c.task || 1; const minWords = c.minWords || (taskNum === 1 ? 150 : 250); const draft = useMemo(() => loadDraft(test.id), [test.id]); const [essay, setEssay] = useState(() => draft?.essay || ''); const [submitting, setSubmitting] = useState(false); const [confirmSubmit, setConfirmSubmit] = useState(false); const startedAt = useRef(draft?.startedAt || Date.now()); const wordCount = essay.trim().split(/\s+/).filter(Boolean).length; useEffect(() => { saveDraft(test.id, { essay, startedAt: startedAt.current }); }, [essay, test.id]); const submit = async () => { if (submitting) return; // re-entrancy guard: manual click racing timer expiry, etc. setSubmitting(true); try { // Get AI feedback first const ai = await window.apiClient.ai.writingScore(taskNum, c.examType || test.exam_type, c.prompt, essay); const res = await window.apiClient.tests.submit(test.id, { answers: { essay }, ai_feedback: ai, started_at: startedAt.current, completed_at: Date.now(), duration_seconds: Math.round((Date.now() - startedAt.current) / 1000), }); clearDraft(test.id); onFinish({ ...res, section: 'writing', task: taskNum, test }); } catch (e) { alert(e.message || 'Submission failed.'); setSubmitting(false); setConfirmSubmit(false); } }; return (
= minWords ? 1 : 0} total={1} onCancel={() => { clearDraft(test.id); onCancel(); }} onTimerExpire={submit} />
Task {taskNum} · {c.examType || test.exam_type}
{c.prompt}
{c.chart && (
📊 {c.chart.title || 'Chart'}
{c.chart.type === 'bar' ? ( `${v}${c.chart.yFormat}`) : undefined} ariaLabel={c.chart.title || 'Task 1 bar chart'} /> ) : ( <> `${v}${c.chart.yFormat}`) : undefined} ariaLabel={c.chart.title || 'Task 1 line chart'} /> )} {c.visualDescription &&
{c.visualDescription}
}
)} {!c.chart && c.visualDescription && (
📊 Chart description (read-only)
{c.visualDescription}
)}
Minimum {minWords} words · Suggested time {Math.round((c.timeLimit || 1200) / 60)} minutes.