"use client"; import { useState } from "react"; import type { Question } from "@/data/types"; import { sfx } from "@/lib/sfx"; import Ar from "./Ar"; interface Props { questions: Question[]; onFinish: (correct: number, total: number) => void; /** Im Prüfungsmodus wird die Lösung erst am Ende gezeigt. */ examMode?: boolean; } const letters = "abcdefghij"; export default function Quiz({ questions, onFinish, examMode = false }: Props) { const [answers, setAnswers] = useState<(number | null)[]>(() => questions.map(() => null)); const [submitted, setSubmitted] = useState(false); const correctOf = (q: Question) => (q.kind === "tf" ? (q.answer ? 0 : 1) : q.answer); const allAnswered = answers.every((a) => a !== null); const reveal = (i: number) => (examMode ? submitted : answers[i] !== null); const choose = (qi: number, oi: number) => { if (answers[qi] !== null && !examMode) return; if (submitted) return; const next = [...answers]; next[qi] = oi; setAnswers(next); if (!examMode) { if (oi === correctOf(questions[qi])) sfx.correct(); else sfx.wrong(); } }; const finish = () => { setSubmitted(true); const correct = questions.reduce((n, q, i) => n + (answers[i] === correctOf(q) ? 1 : 0), 0); onFinish(correct, questions.length); }; return (
{questions.map((q, qi) => { const options = q.kind === "tf" ? ["Richtig ✅", "Falsch ❌"] : q.options; const chosen = answers[qi]; const right = correctOf(q); const shown = reveal(qi); return (
{qi + 1}
{q.q}
{q.qAr}
o.length <= 2) ? "grid grid-3" : ""}> {options.map((o, oi) => { let cls = "option"; if (shown && oi === right) cls += " correct"; else if (shown && chosen === oi && oi !== right) cls += " wrong"; else if (!shown && chosen === oi) cls += " selected"; return ( ); })}
{shown && chosen !== null && (
{chosen === right ? "Super! Richtig 🎉" : "Leider falsch."} {q.why ? – {q.why} : null}
)}
); })} {!submitted && (
)}
); }