// Vocab Quiz, Grammar Quiz, Sentence Writing, Progress.
// Sentence writing now uses the backend AI proxy (Gemini → Groq cascade).
// ─── Vocab MCQ ─────────────────────────────────────────────────────────────
function VocabQuiz({ state, update }) {
const [filterMode, setFilterMode] = useState('recommended');
const [current, setCurrent] = useState(null);
const [selected, setSelected] = useState(null);
const [locked, setLocked] = useState(false);
const [sessionStats, setSessionStats] = useState({ correct: 0, total: 0 });
const cfg = window.bandConfig.for(state.targetBand);
const generate = useCallback(() => {
const correct = filterMode === 'recommended'
? window.api.randomWordForBand(state.targetBand)
: (() => {
const pool = window.api.wordsByLevel(filterMode);
return pool.length ? pool[Math.floor(Math.random() * pool.length)] : null;
})();
if (!correct) { setCurrent(null); return; }
const all = window.api.allWords();
const otherPool = all.filter(w => w.id !== correct.id);
const distractors = [];
let pool = otherPool;
if (cfg.quizDistractorMode === 'pos') {
const sameP = otherPool.filter(w => w.pos === correct.pos);
pool = sameP.length >= 6 ? sameP : otherPool;
} else if (cfg.quizDistractorMode === 'related' || cfg.quizDistractorMode === 'synonym') {
const related = otherPool.filter(w => w.lvl === correct.lvl && w.pos === correct.pos);
pool = related.length >= 6 ? related : otherPool.filter(w => w.lvl === correct.lvl);
if (pool.length < 6) pool = otherPool;
}
let attempts = 0;
while (distractors.length < 3 && attempts < 50) {
attempts++;
const pick = pool[Math.floor(Math.random() * pool.length)];
if (!pick || pick.b === correct.b || distractors.find(d => d.b === pick.b)) continue;
distractors.push(pick);
}
while (distractors.length < 3) {
const pick = otherPool[Math.floor(Math.random() * otherPool.length)];
if (pick && pick.b !== correct.b && !distractors.find(d => d.b === pick.b)) distractors.push(pick);
}
const options = [correct, ...distractors].sort(() => Math.random() - 0.5);
setCurrent({ word: correct, options, correctIndex: options.findIndex(o => o.id === correct.id) });
setSelected(null); setLocked(false);
}, [filterMode, state.targetBand, cfg.quizDistractorMode]);
useEffect(() => { generate(); }, [generate]);
const choose = (i) => {
if (locked) return;
setSelected(i);
setLocked(true);
const isCorrect = i === current.correctIndex;
setSessionStats(s => ({ correct: s.correct + (isCorrect ? 1 : 0), total: s.total + 1 }));
const id = current.word.id;
let s = state;
s = window.srs.recordInteraction(s, id, isCorrect ? 5 : 1);
s = {
...s,
quiz: { ...s.quiz, vocabScore: s.quiz.vocabScore + (isCorrect ? 1 : 0), vocabAttempts: s.quiz.vocabAttempts + 1 },
vocab: {
...s.vocab,
learnedWords: s.vocab.learnedWords.includes(id) ? s.vocab.learnedWords : [...s.vocab.learnedWords, id],
wrong: !isCorrect ? { ...s.vocab.wrong, [id]: (s.vocab.wrong[id] || 0) + 1 } : s.vocab.wrong,
},
};
s = window.planEngine.bumpProgress(s, isCorrect ? 'vocabReview' : 'vocabReview', 1);
update(s);
};
const sessionAccuracy = sessionStats.total > 0 ? Math.round((sessionStats.correct / sessionStats.total) * 100) : 0;
if (!current) return
Loading…
;
return (
Vocab Quiz · Band {state.targetBand}
Pick the correct meaning.
One English word, four Bangla options.
{[1,2,3].map(l => )}
Session · {sessionStats.correct}/{sessionStats.total}
Accuracy · {sessionAccuracy}%
All-time · {state.quiz.vocabScore}/{state.quiz.vocabAttempts}
{current.word.pos} · L{current.word.lvl}
Which is the correct Bangla meaning?
{current.options.map((opt, i) => {
const isCorrect = i === current.correctIndex;
const isSelected = i === selected;
let bg = 'var(--bg-elevated)', border = 'var(--line)';
if (locked) {
if (isCorrect) { bg = 'var(--success-soft)'; border = 'var(--success)'; }
else if (isSelected) { bg = 'var(--danger-soft)'; border = 'var(--danger)'; }
}
return (
);
})}
{locked && (
{selected === current.correctIndex ? '✓ Correct' : '✗ Not quite'}
{current.word.w} = {current.word.b} {current.word.d && <>— {current.word.d}>}
{current.word.ex &&
"{current.word.ex}"
}
)}
);
}
// ─── Grammar MCQ ──────────────────────────────────────────────────────────
function GrammarQuiz({ state, update }) {
const [category, setCategory] = useState('all');
const [current, setCurrent] = useState(null);
const [selected, setSelected] = useState(null);
const [locked, setLocked] = useState(false);
const pool = useMemo(() => window.api.grammarQuestions(category), [category]);
const generate = useCallback(() => {
if (!pool.length) return;
setCurrent(pool[Math.floor(Math.random() * pool.length)]);
setSelected(null); setLocked(false);
}, [pool]);
useEffect(() => { generate(); }, [generate]);
const choose = (i) => {
if (locked) return;
setSelected(i); setLocked(true);
const isCorrect = i === current.a;
const cat = current.cat;
const byCat = state.quiz.byCategory || {};
const prevCat = byCat[cat] || { correct: 0, total: 0 };
let s = { ...state, quiz: { ...state.quiz,
grammarScore: state.quiz.grammarScore + (isCorrect ? 1 : 0),
grammarAttempts: state.quiz.grammarAttempts + 1,
byCategory: { ...byCat, [cat]: { correct: prevCat.correct + (isCorrect ? 1 : 0), total: prevCat.total + 1 } } } };
s = window.planEngine.bumpProgress(s, 'grammarQuiz', 1);
update(s);
};
const cats = [
{ id: 'all', label: 'All' }, { id: 'tense', label: 'Tense' },
{ id: 'article', label: 'Articles' }, { id: 'preposition', label: 'Prepositions' },
{ id: 'correction', label: 'Correction' },
];
if (!current) return null;
return (
Grammar · {pool.length} questions
Grammar drills.
Pick the grammatically correct option.
{cats.map(c => )}
{current.cat}
{current.q}
{current.opts.map((opt, i) => {
const isCorrect = i === current.a;
const isSelected = i === selected;
let bg = 'var(--bg-elevated)', border = 'var(--line)';
if (locked) {
if (isCorrect) { bg = 'var(--success-soft)'; border = 'var(--success)'; }
else if (isSelected) { bg = 'var(--danger-soft)'; border = 'var(--danger)'; }
}
return (
);
})}
{locked && (
{selected === current.a ? '✓ Correct' : '✗ Not quite'}
{current.exp}
)}
);
}
// ─── Sentence Writing ─────────────────────────────────────────────────────
function pickPrompt(state) {
const candidates = window.api.wordsForBand(state.targetBand).filter(w => w.ex && w.ex.length > 10);
const pool = candidates.length ? candidates : window.api.allWords().filter(w => w.ex);
if (!pool.length) return { word: 'accomplish', hint: 'Write a sentence using "accomplish".' };
const w = pool[Math.floor(Math.random() * pool.length)];
return { word: w.w, hint: `Write a sentence using "${w.w}" (${w.pos}).`, bangla: w.b };
}
function SentenceWriting({ state, update }) {
const [prompt, setPrompt] = useState(() => pickPrompt(state));
const [text, setText] = useState('');
const [loading, setLoading] = useState(false);
const [result, setResult] = useState(null);
const aiAvailable = state.auth?.user && window.apiClient.isConfigured();
const newPrompt = () => { setPrompt(pickPrompt(state)); setText(''); setResult(null); };
const submit = async () => {
if (!text.trim() || loading) return;
setLoading(true); setResult(null);
try {
let parsed;
if (aiAvailable) {
parsed = await window.apiClient.ai.sentenceFeedback(prompt.word, text);
} else {
parsed = { verdict: 'pending', issues: [], correction: text,
feedback: 'AI feedback requires signing in. You can still save sentences and review them later.' };
}
setResult(parsed);
update({ sentences: [{ prompt: prompt.word, user: text, verdict: parsed.verdict, correction: parsed.correction, tstamp: Date.now() }, ...state.sentences].slice(0, 50) });
} catch (e) {
setResult({ verdict: 'incorrect', issues: ['Could not reach the feedback service.'], correction: text, feedback: e.message || 'Please try again.' });
} finally { setLoading(false); }
};
return (
Sentence writing
Write. Get instant feedback.
Use the prompt word in a sentence. AI checks grammar and gives a correction.
{!aiAvailable && (
Sign in to enable AI feedback. Sentences you write now will save to your browser only.
)}
Your prompt
{prompt.word}
{prompt.bangla &&
{prompt.bangla}
}
{prompt.hint}
{result && (
Feedback
{result.verdict === 'correct' ? '✓ Correct' : result.verdict === 'pending' ? '· Saved' : 'Suggested correction'}
"{result.correction}"
{result.issues?.length > 0 && result.verdict !== 'correct' && (
What to fix
{result.issues.map((iss, i) => - • {iss}
)}
)}
{result.feedback &&
{result.feedback}
}
)}
{state.sentences.length > 0 && (
Recent sentences
{state.sentences.slice(0, 5).map((s, i) => (
{s.verdict}
prompt: {s.prompt}
{s.user}
{s.verdict !== 'correct' && s.correction !== s.user &&
→ {s.correction}
}
{new Date(s.tstamp).toLocaleDateString()}
))}
)}
);
}
// ─── Progress page ────────────────────────────────────────────────────────
function Progress({ state }) {
const stats = window.api.stats(state);
const byLevel = window.api.levelProgress(state);
const topWrong = Object.entries(state.vocab.wrong || {}).sort((a, b) => b[1] - a[1]).slice(0, 8);
const catStats = Object.entries(state.quiz.byCategory || {});
const srs = window.srs.counts(state);
const [attempts, setAttempts] = useState(null);
useEffect(() => {
if (!state.auth?.user || !window.apiClient.isConfigured()) return;
window.apiClient.tests.attempts(100)
.then(r => setAttempts(Array.isArray(r) ? r : (r.attempts || [])))
.catch(() => setAttempts([]));
}, [state.auth?.user]);
const bandTrend = useMemo(() => {
if (!attempts) return {};
const bySection = {};
for (const a of attempts) {
if (a.band == null) continue;
(bySection[a.section] ||= []).push(a);
}
for (const k in bySection) bySection[k].sort((x, y) => x.completed_at - y.completed_at);
return bySection;
}, [attempts]);
return (
Progress · Session {state.sessions + 1}
Your journey.
Every session compounds.
{Object.keys(bandTrend).length > 0 && (
<>
Mock test band trend
1 ? 'repeat(auto-fit, minmax(min(100%, 260px), 1fr))' : '1fr', gap: 24 }}>
{Object.entries(bandTrend).map(([section, list]) => {
const recent = list.slice(-20);
const label = section.charAt(0).toUpperCase() + section.slice(1);
const latest = recent[recent.length - 1].band;
const first = recent[0].band;
const delta = recent.length > 1 ? Math.round((latest - first) * 10) / 10 : 0;
return (
{label}
Band {latest}
{recent.length > 1 && (
{delta > 0 ? `+${delta}` : delta} since first attempt
)}
{recent.length > 1 ? (
a.band) }]}
labels={recent.map((a, i) => `#${i + 1}`)}
yMin={0} yMax={9}
ariaLabel={`${label} band score trend`}
/>
) : (
Complete another {section} test to see a trend.
)}
);
})}
>
)}
Vocabulary by level
{byLevel.map(b => (
Level {b.level} · {b.level === 1 ? 'Foundation' : b.level === 2 ? 'Intermediate' : 'Advanced'}
{b.done} / {b.total} · {b.pct}%
))}
{catStats.length > 0 && (
<>
Grammar by category
{catStats.map(([cat, d]) => {
const pct = Math.round((d.correct / d.total) * 100);
return (
{cat}
{d.correct} / {d.total} · {pct}%
);
})}
>
)}
{topWrong.length > 0 && (
<>
Words to review
{topWrong.map(([id, count]) => {
const word = window.api.wordById(id);
if (!word) return null;
return (
{word.w}
{word.b}
{word.d || ''}
missed {count}×
);
})}
>
)}
);
}
Object.assign(window, { VocabQuiz, GrammarQuiz, SentenceWriting, Progress });