Do not treat a not-yet-loaded voice list as missing German voice, poll for voices, wait after cancel before speaking, keep utterances referenced, retry stalled speech, detect missing end events, unlock speech on first tap, and stop the microphone before the examiner speaks.
294 lines
11 KiB
TypeScript
294 lines
11 KiB
TypeScript
"use client";
|
||
|
||
import Link from "next/link";
|
||
import { useEffect, useMemo, useRef, useState } from "react";
|
||
import { hoerItems, type HoerItem } from "@/data/hoeren";
|
||
import { leseItems, type LeseItem } from "@/data/lesen";
|
||
import { lessons } from "@/data/grammatik";
|
||
import { allWords, wordLabel } from "@/data/vocab";
|
||
import type { Question } from "@/data/types";
|
||
import Quiz from "@/components/Quiz";
|
||
import Ar from "@/components/Ar";
|
||
import { recordResult } from "@/lib/progress";
|
||
import { germanVoiceMissing, speakSequence, stopSpeaking, TTS_MISSING_EVENT } from "@/lib/speech";
|
||
import { fireConfetti } from "@/components/AppShell";
|
||
import { sfx } from "@/lib/sfx";
|
||
|
||
function shuffle<T>(a: T[]): T[] {
|
||
return [...a].sort(() => Math.random() - 0.5);
|
||
}
|
||
|
||
type Block =
|
||
| { kind: "lesen"; item: LeseItem }
|
||
| { kind: "hoeren"; item: HoerItem }
|
||
| { kind: "sprache"; title: string; questions: Question[] };
|
||
|
||
function buildExam(): Block[] {
|
||
const lesen = [1, 2, 3, 4, 5].map((t) => shuffle(leseItems.filter((l) => l.teil === t))[0]).filter(Boolean);
|
||
const hoeren = [1, 2, 3, 4].map((t) => shuffle(hoerItems.filter((h) => h.teil === t))[0]).filter(Boolean);
|
||
const grammar: Question[] = shuffle(lessons.flatMap((l) => l.exercises.filter((e) => e.kind === "mc")))
|
||
.slice(0, 8)
|
||
.map((e) => (e.kind === "mc" ? { kind: "mc", q: e.q, qAr: e.ar ?? "", options: e.options, answer: e.answer } : null))
|
||
.filter((x): x is Extract<Question, { kind: "mc" }> => x !== null);
|
||
const vocab: Question[] = shuffle(allWords)
|
||
.slice(0, 6)
|
||
.map((w) => {
|
||
const opts = shuffle([w, ...shuffle(allWords.filter((x) => x.id !== w.id)).slice(0, 3)]);
|
||
return { kind: "mc" as const, q: `Was bedeutet „${wordLabel(w)}“?`, qAr: "ما معنى الكلمة؟", options: opts.map((o) => o.ar), answer: opts.indexOf(w) };
|
||
});
|
||
return [
|
||
...lesen.map((item) => ({ kind: "lesen" as const, item })),
|
||
...hoeren.map((item) => ({ kind: "hoeren" as const, item })),
|
||
{ kind: "sprache", title: "Sprachbausteine: Grammatik & Wortschatz", questions: [...grammar, ...vocab] },
|
||
];
|
||
}
|
||
|
||
export default function PruefungPage() {
|
||
const [exam, setExam] = useState<Block[] | null>(null);
|
||
const [idx, setIdx] = useState(0);
|
||
const [scores, setScores] = useState<{ kind: Block["kind"]; c: number; t: number }[]>([]);
|
||
const [seconds, setSeconds] = useState(0);
|
||
const [blockDone, setBlockDone] = useState(false);
|
||
const saved = useRef(false);
|
||
|
||
useEffect(() => {
|
||
if (!exam || idx >= exam.length) return;
|
||
const id = setInterval(() => setSeconds((s) => s + 1), 1000);
|
||
return () => clearInterval(id);
|
||
}, [exam, idx]);
|
||
|
||
useEffect(() => () => stopSpeaking(), []);
|
||
|
||
const finished = exam !== null && idx >= exam.length;
|
||
|
||
const summary = useMemo(() => {
|
||
const by = (k: Block["kind"]) => {
|
||
const list = scores.filter((s) => s.kind === k);
|
||
const c = list.reduce((a, b) => a + b.c, 0);
|
||
const t = list.reduce((a, b) => a + b.t, 0);
|
||
return { c, t, pct: t ? Math.round((c / t) * 100) : 0 };
|
||
};
|
||
return { lesen: by("lesen"), hoeren: by("hoeren"), sprache: by("sprache") };
|
||
}, [scores]);
|
||
|
||
useEffect(() => {
|
||
if (finished && !saved.current) {
|
||
saved.current = true;
|
||
const total = scores.reduce((a, b) => a + b.c, 0);
|
||
const max = scores.reduce((a, b) => a + b.t, 0);
|
||
recordResult("modelltest", "pruefung", (total / max) * 100, 30 + total * 2);
|
||
if (total / max >= 0.6) {
|
||
fireConfetti();
|
||
sfx.win();
|
||
}
|
||
}
|
||
}, [finished, scores]);
|
||
|
||
if (!exam)
|
||
return (
|
||
<div>
|
||
<h1>🏅 Modelltest</h1>
|
||
<p className="sub">
|
||
Simuliere die Prüfung: Lesen (5 Teile), Hören (4 Teile) und Sprachbausteine. <Ar>محاكاة الامتحان: القراءة (5 أجزاء)، الاستماع (4 أجزاء) وتمارين لغوية.</Ar>
|
||
</p>
|
||
<div className="card">
|
||
<h3>So funktioniert es • كيف يعمل</h3>
|
||
<ul style={{ paddingLeft: 20, margin: 0, lineHeight: 1.8 }}>
|
||
<li>Du siehst die Lösungen erst am Ende jedes Teils – wie in der echten Prüfung.</li>
|
||
<li>Hörtexte kannst du im Modelltest nur so oft hören wie in der Prüfung.</li>
|
||
<li>Zum Bestehen brauchst du in jedem Modul 60 %.</li>
|
||
<li>Schreiben und Sprechen übst du in den eigenen Bereichen (mit Selbstcheck oder KI-Korrektur).</li>
|
||
</ul>
|
||
<Ar block>
|
||
ترى الحلول فقط في نهاية كل جزء – كما في الامتحان الحقيقي. لا يمكنك سماع النصوص إلا بعدد المرات المسموح بها. تحتاج 60% في كل وحدة للنجاح.
|
||
</Ar>
|
||
<button
|
||
className="btn green block"
|
||
style={{ marginTop: 16 }}
|
||
onClick={() => {
|
||
setExam(buildExam());
|
||
setIdx(0);
|
||
setScores([]);
|
||
setSeconds(0);
|
||
saved.current = false;
|
||
}}
|
||
>
|
||
🚀 Modelltest starten (ca. 45 Min.)
|
||
</button>
|
||
</div>
|
||
<div className="grid grid-2" style={{ marginTop: 12 }}>
|
||
<Link href="/schreiben" className="tile">
|
||
<div className="emoji">✍️</div>
|
||
<div className="t">Schreiben üben</div>
|
||
<div className="s">3 Aufgaben, 60 Min.</div>
|
||
</Link>
|
||
<Link href="/sprechen" className="tile">
|
||
<div className="emoji">🗣️</div>
|
||
<div className="t">Sprechen üben</div>
|
||
<div className="s">Planen, Präsentieren, Fragen</div>
|
||
</Link>
|
||
</div>
|
||
</div>
|
||
);
|
||
|
||
const mm = String(Math.floor(seconds / 60)).padStart(2, "0");
|
||
const ss = String(seconds % 60).padStart(2, "0");
|
||
|
||
if (finished) {
|
||
const rows = [
|
||
{ de: "Lesen", ar: "القراءة", ...summary.lesen },
|
||
{ de: "Hören", ar: "الاستماع", ...summary.hoeren },
|
||
{ de: "Sprachbausteine", ar: "القواعد والمفردات", ...summary.sprache },
|
||
];
|
||
const allPassed = rows.every((r) => r.pct >= 60);
|
||
return (
|
||
<div>
|
||
<h1>{allPassed ? "🏆 Bestanden!" : "💪 Fast geschafft!"}</h1>
|
||
<p className="sub">
|
||
Zeit: {mm}:{ss} Min. <Ar>{allPassed ? "مبروك! أنت على الطريق الصحيح." : "استمر في التدريب – أنت تقترب!"}</Ar>
|
||
</p>
|
||
{rows.map((r) => (
|
||
<div key={r.de} className="card">
|
||
<div className="row">
|
||
<h3 style={{ margin: 0 }}>{r.de}</h3>
|
||
<span className="ar muted small">{r.ar}</span>
|
||
<span className="spacer" />
|
||
<span className={`pill ${r.pct >= 60 ? "green" : "red"}`}>
|
||
{r.c}/{r.t} • {r.pct} % {r.pct >= 60 ? "✅" : "❌"}
|
||
</span>
|
||
</div>
|
||
<div className={`bar ${r.pct >= 60 ? "green" : ""}`} style={{ marginTop: 8 }}>
|
||
<div style={{ width: `${r.pct}%` }} />
|
||
</div>
|
||
</div>
|
||
))}
|
||
<div className="row" style={{ marginTop: 16 }}>
|
||
<button className="btn" onClick={() => setExam(null)}>
|
||
🔁 Neuer Modelltest
|
||
</button>
|
||
<Link href="/" className="btn secondary">
|
||
🏠 Start
|
||
</Link>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const block = exam[idx];
|
||
|
||
return (
|
||
<div>
|
||
<div className="row" style={{ marginTop: 16 }}>
|
||
<span className="pill">
|
||
Teil {idx + 1} / {exam.length}
|
||
</span>
|
||
<span className="pill yellow timer">⏱ {mm}:{ss}</span>
|
||
<span className="spacer" />
|
||
<button
|
||
className="btn secondary small"
|
||
onClick={() => {
|
||
stopSpeaking();
|
||
setExam(null);
|
||
}}
|
||
>
|
||
Abbrechen
|
||
</button>
|
||
</div>
|
||
<div className="bar" style={{ marginTop: 10 }}>
|
||
<div style={{ width: `${(idx / exam.length) * 100}%` }} />
|
||
</div>
|
||
|
||
<div key={idx}>
|
||
{block.kind === "lesen" && (
|
||
<>
|
||
<h2>
|
||
📖 Lesen Teil {block.item.teil}: {block.item.title}
|
||
</h2>
|
||
<div className="card small" style={{ background: "var(--yellow-soft)" }}>
|
||
{block.item.task}
|
||
</div>
|
||
<div className="card reading" style={{ marginTop: 10 }}>
|
||
{block.item.text}
|
||
</div>
|
||
</>
|
||
)}
|
||
{block.kind === "hoeren" && <ExamAudio item={block.item} />}
|
||
{block.kind === "sprache" && <h2>🧩 {block.title}</h2>}
|
||
|
||
<Quiz
|
||
examMode
|
||
questions={block.kind === "sprache" ? block.questions : block.item.questions}
|
||
onFinish={(c, t) => {
|
||
stopSpeaking();
|
||
setScores((s) => [...s, { kind: block.kind, c, t }]);
|
||
setBlockDone(true);
|
||
}}
|
||
/>
|
||
{blockDone && (
|
||
<button
|
||
className="btn blue block"
|
||
style={{ marginTop: 14 }}
|
||
onClick={() => {
|
||
setBlockDone(false);
|
||
setIdx((i) => i + 1);
|
||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||
}}
|
||
>
|
||
{idx + 1 >= exam.length ? "Ergebnis anzeigen 🏁" : "Weiter zum nächsten Teil →"}
|
||
</button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function ExamAudio({ item }: { item: HoerItem }) {
|
||
const max = item.teil === 1 || item.teil === 4 ? 2 : 1;
|
||
const [plays, setPlays] = useState(0);
|
||
const [playing, setPlaying] = useState(false);
|
||
const stop = useRef<(() => void) | null>(null);
|
||
const voices = useMemo(() => {
|
||
const counters = { f: 0, m: 0 };
|
||
const map: Record<string, { gender: "f" | "m"; idx: number }> = {};
|
||
Object.entries(item.speakers).forEach(([n, g]) => (map[n] = { gender: g, idx: counters[g]++ }));
|
||
return map;
|
||
}, [item]);
|
||
useEffect(() => () => stop.current?.(), []);
|
||
return (
|
||
<>
|
||
<h2>
|
||
🎧 Hören Teil {item.teil}: {item.title}
|
||
</h2>
|
||
<div className="card">
|
||
<p style={{ marginTop: 0 }}>{item.situation}</p>
|
||
<div className="row">
|
||
<button
|
||
className="btn blue"
|
||
disabled={playing || plays >= max}
|
||
onClick={() => {
|
||
if (germanVoiceMissing()) {
|
||
window.dispatchEvent(new Event(TTS_MISSING_EVENT));
|
||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||
return;
|
||
}
|
||
setPlays((p) => p + 1);
|
||
setPlaying(true);
|
||
stop.current = speakSequence(
|
||
item.lines.map((l) => ({ text: l.t, gender: voices[l.who]?.gender ?? "f", voiceIndex: voices[l.who]?.idx ?? 0 })),
|
||
0.95,
|
||
() => {},
|
||
() => setPlaying(false),
|
||
);
|
||
}}
|
||
>
|
||
{playing ? "🔊 Läuft …" : `▶ Abspielen (${max - plays}× übrig)`}
|
||
</button>
|
||
</div>
|
||
<div className="small muted" style={{ marginTop: 6 }}>
|
||
Lies zuerst die Fragen! • اقرأ الأسئلة أولاً!
|
||
</div>
|
||
</div>
|
||
</>
|
||
);
|
||
}
|