Files
chadiapp/app/wortschatz/page.tsx
T
X4Lo 1f1d28a34d Add B1 Meister: OeSD B1 exam trainer (German-Arabic)
Next.js app with Hoeren, Lesen, Schreiben, Sprechen, Grammatik and Wortschatz sections, flashcards with spaced repetition, speaking chat, XP/streaks/badges, daily reminders (PWA) and Docker Compose setup for Coolify.
2026-11-05 19:11:46 +00:00

552 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { allWords, topics, wordLabel, type Word } from "@/data/vocab";
import Ar from "@/components/Ar";
import SpeakButton from "@/components/SpeakButton";
import ResultCard from "@/components/ResultCard";
import { addXp, getProgress, recordResult, reviewCard, todayStr, useProgress } from "@/lib/progress";
import { speak } from "@/lib/speech";
import { sfx } from "@/lib/sfx";
import { fireConfetti } from "@/components/AppShell";
type Mode = "karten" | "quiz" | "artikel" | "memory" | "liste";
const modes: { id: Mode; de: string; ar: string }[] = [
{ id: "karten", de: "🃏 Karteikarten", ar: "البطاقات" },
{ id: "quiz", de: "🎯 Quiz", ar: "اختبار" },
{ id: "artikel", de: "⚡ der/die/das", ar: "لعبة الأدوات" },
{ id: "memory", de: "🧠 Memory", ar: "لعبة الذاكرة" },
{ id: "liste", de: "📚 Wortliste", ar: "قائمة الكلمات" },
];
function shuffle<T>(a: T[]): T[] {
const b = [...a];
for (let i = b.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[b[i], b[j]] = [b[j], b[i]];
}
return b;
}
export default function WortschatzPage() {
const [mode, setMode] = useState<Mode>("karten");
const [topic, setTopic] = useState("alle");
const [key, setKey] = useState(0);
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
const words = useMemo(() => (topic === "alle" ? allWords : topics.find((t) => t.id === topic)!.words), [topic]);
const p = useProgress();
const known = words.filter((w) => (p.cards[w.id]?.box ?? 0) >= 3).length;
return (
<div>
<h1>🃏 Wortschatz</h1>
<p className="sub">
{allWords.length} B1-Wörter in {topics.length} Themen – lernen, spielen, wiederholen! <Ar>تعلّم، العب، راجع!</Ar>
</p>
<div className="tabs">
{modes.map((m) => (
<button key={m.id} className={mode === m.id ? "active" : ""} onClick={() => setMode(m.id)}>
{m.de}
</button>
))}
</div>
<div className="row">
<select
value={topic}
onChange={(e) => {
setTopic(e.target.value);
setKey((k) => k + 1);
}}
style={{ flex: 1 }}
aria-label="Thema"
>
<option value="alle">🌍 Alle Themen ({allWords.length})</option>
{topics.map((t) => (
<option key={t.id} value={t.id}>
{t.emoji} {t.de} – {t.ar} ({t.words.length})
</option>
))}
</select>
</div>
<div className="row small muted" style={{ marginTop: 8 }}>
<span>
Gelernt: {known}/{words.length}
</span>
<div className="bar green" style={{ flex: 1, height: 8 }}>
<div style={{ width: `${(known / words.length) * 100}%` }} />
</div>
</div>
<div style={{ marginTop: 14 }} key={`${mode}-${key}`}>
{!mounted ? null : mode === "karten" ? (
<Flashcards words={words} onRestart={() => setKey((k) => k + 1)} />
) : mode === "quiz" ? (
<VocabQuiz words={words} topic={topic} onRestart={() => setKey((k) => k + 1)} />
) : mode === "artikel" ? (
<ArticleGame words={words} onRestart={() => setKey((k) => k + 1)} />
) : mode === "memory" ? (
<Memory words={words} onRestart={() => setKey((k) => k + 1)} />
) : (
<WordList words={words} />
)}
</div>
</div>
);
}
// ---------------- Karteikarten (Leitner) ----------------
function Flashcards({ words, onRestart }: { words: Word[]; onRestart: () => void }) {
const [queue] = useState<Word[]>(() => {
const p = getProgress();
const t = todayStr();
const due = words.filter((w) => p.cards[w.id] && p.cards[w.id].due <= t);
const fresh = words.filter((w) => !p.cards[w.id]).slice(0, 10);
return shuffle([...due, ...fresh]).slice(0, 20);
});
const [i, setI] = useState(0);
const [flipped, setFlipped] = useState(false);
const [stats, setStats] = useState({ known: 0, again: 0 });
const [extra, setExtra] = useState<Word[]>([]);
const all = [...queue, ...extra];
const w = all[i];
const answer = useCallback(
(known: boolean) => {
if (!w) return;
reviewCard(w.id, known);
if (known) sfx.correct();
else {
sfx.flip();
// Nicht gewusst: am Ende dieser Runde noch einmal zeigen
if (!extra.includes(w)) setExtra((e) => [...e, w]);
}
setStats((s) => ({ known: s.known + (known ? 1 : 0), again: s.again + (known ? 0 : 1) }));
setFlipped(false);
setTimeout(() => setI((x) => x + 1), 150);
},
[w, extra],
);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.target as HTMLElement).tagName === "SELECT") return;
if (e.key === " ") {
e.preventDefault();
setFlipped((f) => !f);
sfx.flip();
} else if (flipped && (e.key === "1" || e.key === "ArrowLeft")) answer(false);
else if (flipped && (e.key === "2" || e.key === "ArrowRight")) answer(true);
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [flipped, answer]);
useEffect(() => {
if (!w && all.length > 0 && stats.known > 0) fireConfetti();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [w]);
if (all.length === 0)
return (
<div className="card" style={{ textAlign: "center" }}>
<div style={{ fontSize: 50 }}>🎉</div>
<h3>Alles wiederholt!</h3>
<p className="muted">Für dieses Thema ist heute nichts mehr fällig. Probier ein anderes Thema oder ein Spiel!</p>
<div className="ar">لا توجد بطاقات مستحقة اليوم. جرّب موضوعاً آخر أو لعبة!</div>
</div>
);
if (!w)
return (
<div className="card fade-in" style={{ textAlign: "center" }}>
<div style={{ fontSize: 50 }}>🏁</div>
<h3>Runde geschafft!</h3>
<p>
✅ {stats.known} gewusst • 🔁 {stats.again} nochmal
</p>
<div className="ar">أحسنت! سأذكّرك بالكلمات في الوقت المناسب.</div>
<button className="btn" style={{ marginTop: 12 }} onClick={onRestart}>
Weiter lernen →
</button>
</div>
);
return (
<div>
<div className="row small muted" style={{ marginBottom: 8 }}>
<span>
Karte {i + 1} / {all.length}
</span>
<span className="spacer" />
<span>
✅ {stats.known} • 🔁 {stats.again}
</span>
</div>
<div
className={`flip ${flipped ? "flipped" : ""}`}
onClick={() => {
setFlipped((f) => !f);
sfx.flip();
}}
>
<div className="flip-inner">
<div className="face front">
<div className="pill" style={{ marginBottom: 10 }}>
{topics.find((t) => t.id === w.topic)?.emoji} {topics.find((t) => t.id === w.topic)?.de}
</div>
<div style={{ fontSize: 34, fontWeight: 900 }}>
{w.art && <span className={`art-${w.art}`}>{w.art} </span>}
{w.de}
</div>
{w.pl && <div className="muted">{w.pl}</div>}
<div style={{ marginTop: 14 }} onClick={(e) => e.stopPropagation()}>
<SpeakButton text={wordLabel(w)} />
</div>
<div className="small muted" style={{ marginTop: 16 }}>
Antippen zum Umdrehen • اضغط لقلب البطاقة
</div>
</div>
<div className="face back">
<div className="ar" style={{ fontSize: 30, fontWeight: 800 }}>
{w.ar}
</div>
<div style={{ marginTop: 12, fontWeight: 700 }}>„{w.ex}“</div>
<div className="ar muted">{w.exAr}</div>
<div style={{ marginTop: 10 }} onClick={(e) => e.stopPropagation()}>
<SpeakButton text={w.ex} />
</div>
</div>
</div>
</div>
<div className="grid grid-2" style={{ marginTop: 14 }}>
<button className="btn secondary" disabled={!flipped} onClick={() => answer(false)}>
😕 Nochmal
</button>
<button className="btn green" disabled={!flipped} onClick={() => answer(true)}>
😊 Gewusst!
</button>
</div>
<div className="kbd-hint" style={{ textAlign: "center", marginTop: 8 }}>
Tastatur: Leertaste = umdrehen • 1 = nochmal • 2 = gewusst
</div>
</div>
);
}
// ---------------- Quiz ----------------
function VocabQuiz({ words, topic, onRestart }: { words: Word[]; topic: string; onRestart: () => void }) {
const qs = useMemo(() => {
const pick = shuffle(words).slice(0, 10);
return pick.map((w, n) => {
const reverse = n % 2 === 1;
const pool = shuffle(allWords.filter((x) => x.id !== w.id && x.topic === w.topic)).slice(0, 3);
const filler = pool.length < 3 ? shuffle(allWords.filter((x) => x.id !== w.id)).slice(0, 3 - pool.length) : [];
const opts = shuffle([w, ...pool, ...filler]);
return { w, reverse, opts };
});
}, [words]);
const [i, setI] = useState(0);
const [chosen, setChosen] = useState<string | null>(null);
const [correct, setCorrect] = useState(0);
const [result, setResult] = useState<{ xp: number } | null>(null);
if (result) return <ResultCard correct={correct} total={qs.length} xp={result.xp} onRetry={onRestart} />;
const q = qs[i];
if (!q) return null;
const pick = (id: string) => {
if (chosen) return;
setChosen(id);
const ok = id === q.w.id;
if (ok) {
sfx.correct();
setCorrect((c) => c + 1);
} else sfx.wrong();
setTimeout(() => {
if (i + 1 >= qs.length) {
const c = correct + (ok ? 1 : 0);
const xp = 5 + c * 2;
recordResult(`vocab-quiz-${topic}`, "wortschatz", (c / qs.length) * 100, xp);
setResult({ xp });
} else {
setI(i + 1);
setChosen(null);
}
}, 1000);
};
return (
<div className="card fade-in" key={i}>
<div className="row small muted">
<span>
Frage {i + 1} / {qs.length}
</span>
<span className="spacer" />
<span>✅ {correct}</span>
</div>
<div className="bar" style={{ margin: "8px 0 16px" }}>
<div style={{ width: `${(i / qs.length) * 100}%` }} />
</div>
<div style={{ textAlign: "center" }}>
<div className="small muted">{q.reverse ? "Was heißt das auf Deutsch?" : "Was bedeutet das? • ما معنى؟"}</div>
{q.reverse ? (
<div className="ar" style={{ fontSize: 28, fontWeight: 800 }}>
{q.w.ar}
</div>
) : (
<div className="row" style={{ justifyContent: "center" }}>
<div style={{ fontSize: 28, fontWeight: 900 }}>{wordLabel(q.w)}</div>
<SpeakButton text={wordLabel(q.w)} />
</div>
)}
</div>
{q.opts.map((o, k) => {
let cls = "option";
if (chosen && o.id === q.w.id) cls += " correct";
else if (chosen === o.id) cls += " wrong";
return (
<button key={o.id} className={cls} disabled={!!chosen} onClick={() => pick(o.id)}>
<span className="key">{"abcd"[k]}</span>
{q.reverse ? <span>{wordLabel(o)}</span> : <span className="ar">{o.ar}</span>}
</button>
);
})}
</div>
);
}
// ---------------- Artikel-Spiel ----------------
function ArticleGame({ words, onRestart }: { words: Word[]; onRestart: () => void }) {
const nouns = useMemo(() => {
const n = words.filter((w) => w.art && !w.pl?.includes("Plural"));
return shuffle(n.length >= 8 ? n : allWords.filter((w) => w.art && !w.pl?.includes("Plural")));
}, [words]);
const [started, setStarted] = useState(false);
const [time, setTime] = useState(60);
const [i, setI] = useState(0);
const [score, setScore] = useState(0);
const [combo, setCombo] = useState(0);
const [flash, setFlash] = useState<"ok" | "no" | null>(null);
const [mistakes, setMistakes] = useState<Word[]>([]);
const [saved, setSaved] = useState(false);
const over = started && time <= 0;
useEffect(() => {
if (!started || over) return;
const id = setInterval(() => setTime((t) => t - 1), 1000);
return () => clearInterval(id);
}, [started, over]);
useEffect(() => {
if (over && !saved) {
setSaved(true);
if (score > 0) addXp(Math.min(40, Math.ceil(score / 2)));
if (score >= 30) fireConfetti();
sfx.win();
}
}, [over, saved, score]);
const w = nouns[i % nouns.length];
const guess = (a: string) => {
if (over) return;
if (a === w.art) {
const c = combo + 1;
setCombo(c);
setScore((s) => s + (c >= 5 ? 3 : c >= 3 ? 2 : 1));
setFlash("ok");
sfx.correct();
} else {
setCombo(0);
setFlash("no");
setMistakes((m) => (m.includes(w) ? m : [...m, w]));
sfx.wrong();
}
setTimeout(() => setFlash(null), 250);
setI((x) => x + 1);
};
if (!started)
return (
<div className="card" style={{ textAlign: "center" }}>
<div style={{ fontSize: 50 }}>⚡</div>
<h3>der, die oder das?</h3>
<p>60 Sekunden – so viele Artikel wie möglich! Combo ab 3 richtigen = doppelte Punkte.</p>
<div className="ar">60 ثانية – أكبر عدد ممكن من الأدوات! سلسلة من 3 إجابات صحيحة = نقاط مضاعفة.</div>
<div className="row small" style={{ justifyContent: "center", marginTop: 8 }}>
<span className="art-der">● der = blau</span>
<span className="art-die">● die = rot</span>
<span className="art-das">● das = grün</span>
</div>
<button className="btn" style={{ marginTop: 14 }} onClick={() => setStarted(true)}>
Los geht&apos;s! 🚀
</button>
</div>
);
if (over)
return (
<div className="card fade-in" style={{ textAlign: "center" }}>
<div style={{ fontSize: 50 }}>{score >= 30 ? "🏆" : score >= 15 ? "🌟" : "💪"}</div>
<div style={{ fontSize: 34, fontWeight: 900 }}>{score} Punkte</div>
<div className="muted">+{Math.min(40, Math.ceil(score / 2))} XP</div>
{mistakes.length > 0 && (
<div style={{ marginTop: 12, textAlign: "left" }}>
<b>Diese Wörter wiederholen:</b>
{mistakes.slice(0, 10).map((m) => (
<div key={m.id}>
<span className={`art-${m.art}`} style={{ fontWeight: 900 }}>
{m.art}
</span>{" "}
{m.de} – <span className="ar">{m.ar}</span>
</div>
))}
</div>
)}
<button className="btn" style={{ marginTop: 14 }} onClick={onRestart}>
🔁 Nochmal spielen
</button>
</div>
);
return (
<div className="card" style={{ textAlign: "center", borderColor: flash === "ok" ? "var(--green)" : flash === "no" ? "var(--red)" : undefined, transition: "border-color .2s" }}>
<div className="row">
<span className="pill yellow timer">⏱ {time}s</span>
<span className="spacer" />
{combo >= 3 && <span className="pill red">🔥 Combo x{combo >= 5 ? 3 : 2}</span>}
<span className="pill purple">{score} P</span>
</div>
<div style={{ fontSize: 38, fontWeight: 900, margin: "28px 0 6px" }}>{w.de}</div>
<div className="ar muted">{w.ar}</div>
<div className="grid grid-3" style={{ marginTop: 22 }}>
{(["der", "die", "das"] as const).map((a) => (
<button key={a} className="btn" style={{ background: a === "der" ? "var(--blue)" : a === "die" ? "var(--red)" : "var(--green)", fontSize: 22, boxShadow: "0 4px 0 rgba(0,0,0,.2)" }} onClick={() => guess(a)}>
{a}
</button>
))}
</div>
</div>
);
}
// ---------------- Memory ----------------
function Memory({ words, onRestart }: { words: Word[]; onRestart: () => void }) {
const cards = useMemo(() => {
const pick = shuffle(words).slice(0, 6);
return shuffle(pick.flatMap((w) => [{ key: w.id + "-de", id: w.id, text: wordLabel(w), ar: false }, { key: w.id + "-ar", id: w.id, text: w.ar, ar: true }]));
}, [words]);
const [open, setOpen] = useState<number[]>([]);
const [matched, setMatched] = useState<string[]>([]);
const [moves, setMoves] = useState(0);
const won = matched.length === cards.length / 2;
const [awarded, setAwarded] = useState(false);
useEffect(() => {
if (won && !awarded) {
setAwarded(true);
recordResult("vocab-memory", "wortschatz", Math.max(40, 100 - (moves - 6) * 8), 12);
fireConfetti();
sfx.win();
}
}, [won, awarded, moves]);
const click = (k: number) => {
if (open.length === 2 || open.includes(k) || matched.includes(cards[k].id)) return;
sfx.flip();
const next = [...open, k];
setOpen(next);
if (!cards[k].ar) speak(cards[k].text, { rate: 0.9 });
if (next.length === 2) {
setMoves((m) => m + 1);
const [a, b] = next;
if (cards[a].id === cards[b].id) {
setTimeout(() => {
setMatched((m) => [...m, cards[a].id]);
setOpen([]);
sfx.correct();
}, 400);
} else setTimeout(() => setOpen([]), 900);
}
};
return (
<div>
<div className="row small muted" style={{ marginBottom: 8 }}>
<span>Finde die Paare: Deutsch ↔ Arabisch • جد الأزواج</span>
<span className="spacer" />
<span>Züge: {moves}</span>
</div>
<div className="grid grid-3">
{cards.map((c, k) => {
const shown = open.includes(k) || matched.includes(c.id);
return (
<button
key={c.key}
className="tile"
onClick={() => click(k)}
style={{
minHeight: 92,
textAlign: "center",
background: matched.includes(c.id) ? "var(--green-soft)" : shown ? "var(--yellow-soft)" : "linear-gradient(135deg, var(--purple), var(--blue))",
color: shown ? "var(--text)" : "#fff",
fontWeight: 800,
}}
>
{shown ? <span className={c.ar ? "ar" : ""}>{c.text}</span> : <span style={{ fontSize: 26 }}>❓</span>}
</button>
);
})}
</div>
{won && (
<div className="card fade-in" style={{ textAlign: "center", marginTop: 14 }}>
<div style={{ fontSize: 44 }}>🧠🎉</div>
<b>Geschafft in {moves} Zügen!</b>
<div className="ar">أحسنت! ذاكرة ممتازة.</div>
<button className="btn" style={{ marginTop: 10 }} onClick={onRestart}>
Neue Runde
</button>
</div>
)}
</div>
);
}
// ---------------- Wortliste ----------------
function WordList({ words }: { words: Word[] }) {
const [q, setQ] = useState("");
const p = useProgress();
const list = words.filter((w) => !q || w.de.toLowerCase().includes(q.toLowerCase()) || w.ar.includes(q));
return (
<div>
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="🔎 Suchen … • ابحث" />
<div style={{ marginTop: 10 }}>
{list.map((w) => {
const box = p.cards[w.id]?.box ?? 0;
return (
<div key={w.id} className="card row" style={{ flexWrap: "nowrap", padding: 12 }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 800 }}>
{w.art && <span className={`art-${w.art}`}>{w.art} </span>}
{w.de} {w.pl && <span className="small muted">({w.pl})</span>}
</div>
<div className="ar">{w.ar}</div>
<div className="small muted">{w.ex}</div>
</div>
<div style={{ textAlign: "center" }}>
<SpeakButton text={wordLabel(w) + ". " + w.ex} />
<div className="small" title="Lernstufe">
{"●".repeat(box)}
<span className="muted">{"○".repeat(5 - box)}</span>
</div>
</div>
</div>
);
})}
</div>
</div>
);
}