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.
This commit is contained in:
X4Lo committed 2026-11-05 19:11:46 +00:00
commit 1f1d28a34d
42 files changed
+8879

No files matched your search

+133
View File
@@ -0,0 +1,133 @@
import Anthropic from "@anthropic-ai/sdk";
// Optionaler KI-Gesprächspartner (Sprechen) und KI-Korrektur (Schreiben).
// Läuft nur, wenn ANTHROPIC_API_KEY in .env.local gesetzt ist – sonst nutzt die App den Offline-Trainer.
export const runtime = "nodejs";
const MODEL = "claude-opus-5-5";
function enabled() {
return Boolean(process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN);
}
export async function GET() {
return Response.json({ enabled: enabled() });
}
interface ChatBody {
mode: "chat";
topic: string;
context?: string;
history: { role: "user" | "assistant"; content: string }[];
}
interface WriteBody {
mode: "write";
task: string;
points: string[];
words: number;
text: string;
}
const chatSchema = {
type: "object",
additionalProperties: false,
properties: {
reply: { type: "string", description: "Deine nächste Äußerung als Prüfer/Gesprächspartner auf Deutsch (B1-Niveau, 1–3 Sätze, endet meist mit einer Frage)." },
replyAr: { type: "string", description: "Arabische Übersetzung von reply." },
correction: { type: "string", description: "Kurze, freundliche Korrektur der letzten Antwort des Lernenden auf Deutsch (verbesserter Satz). Leer, wenn es keine Fehler gab oder es noch keine Antwort gab." },
tipAr: { type: "string", description: "Ein kurzer Tipp auf Arabisch zur letzten Antwort (Grammatik, Wortschatz oder Redemittel). Leer, wenn es noch keine Antwort gab." },
score: { type: "integer", description: "Bewertung der letzten Antwort 0–5 für B1-Niveau (0, wenn noch keine Antwort)." },
},
required: ["reply", "replyAr", "correction", "tipAr", "score"],
};
const writeSchema = {
type: "object",
additionalProperties: false,
properties: {
points: { type: "integer", description: "Geschätzte Punkte 0–20 nach ÖSD-B1-Kriterien (Aufgabenerfüllung, Kohärenz, Wortschatz, Strukturen)." },
summaryDe: { type: "string", description: "Kurzes Feedback auf Deutsch (2–4 Sätze)." },
summaryAr: { type: "string", description: "Dasselbe Feedback auf Arabisch." },
corrected: { type: "string", description: "Der korrigierte Text des Lernenden (gleiche Struktur, Fehler verbessert)." },
mistakes: {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: {
wrong: { type: "string" },
right: { type: "string" },
explainAr: { type: "string" },
},
required: ["wrong", "right", "explainAr"],
},
},
},
required: ["points", "summaryDe", "summaryAr", "corrected", "mistakes"],
};
const client = new Anthropic();
async function ask(system: string, messages: Anthropic.Beta.BetaMessageParam[], schema: Record<string, unknown>, effort: "low" | "medium") {
const response = await client.beta.messages.create({
model: MODEL,
max_tokens: 4000,
betas: ["server-side-fallback-2026-07-01"],
fallbacks: "default",
system,
messages,
output_config: { effort, format: { type: "json_schema", schema } },
});
if (response.stop_reason === "refusal") throw new Error("refusal");
const text = response.content.find((b): b is Anthropic.Beta.BetaTextBlock => b.type === "text")?.text ?? "{}";
return JSON.parse(text) as Record<string, unknown>;
}
export async function POST(req: Request) {
if (!enabled()) return Response.json({ error: "disabled" }, { status: 503 });
let body: ChatBody | WriteBody;
try {
body = (await req.json()) as ChatBody | WriteBody;
} catch {
return Response.json({ error: "bad request" }, { status: 400 });
}
try {
if (body.mode === "chat") {
const system = [
"Du bist ein freundlicher, motivierender ÖSD-Prüfer und Gesprächspartner für das Modul Sprechen, Niveau B1.",
"Der Lernende spricht Arabisch als Muttersprache und lebt in Österreich.",
`Thema des Gesprächs: ${body.topic}.`,
body.context ? `Situation: ${body.context}` : "",
"Führe ein natürliches Gespräch: reagiere kurz auf das Gesagte (zeige Interesse, stimme zu oder widersprich höflich) und stelle dann eine passende neue Frage oder einen Vorschlag.",
"Sprich einfach und klar (B1), maximal 3 kurze Sätze. Variiere die Fragen. Wenn der Lernende Fehler macht, korrigiere sie im Feld correction, nicht in reply.",
"Wenn die Nachrichtenliste nur die Startanweisung enthält, beginne das Gespräch mit einer Begrüßung und der ersten Frage.",
]
.filter(Boolean)
.join("\n");
const history = body.history.slice(-16);
const messages: Anthropic.Beta.BetaMessageParam[] = [{ role: "user", content: "[Start des Gesprächs]" }, ...history.map((m) => ({ role: m.role, content: m.content }))];
// Die Liste muss mit einer Nutzer-Nachricht enden
if (messages[messages.length - 1].role !== "user") messages.push({ role: "user", content: "[Bitte weiter]" });
return Response.json(await ask(system, messages, chatSchema, "low"));
}
if (body.mode === "write") {
const system = [
"Du bist ein erfahrener ÖSD-Prüfer für das Modul Schreiben, Niveau B1. Der Lernende spricht Arabisch.",
"Bewerte den Text fair nach ÖSD-Kriterien: Wurden alle Leitpunkte behandelt? Ist der Text zusammenhängend (Konnektoren)? Passt das Register (du/Sie, Anrede, Gruß)? Wortschatz und Grammatik auf B1-Niveau?",
"Sei ermutigend. Nenne maximal 6 wichtige Fehler mit kurzer arabischer Erklärung.",
].join("\n");
const prompt = `Aufgabe: ${body.task}\nLeitpunkte: ${body.points.join(" | ")}\nZiel: ca. ${body.words} Wörter\n\nText des Lernenden:\n"""\n${body.text.slice(0, 4000)}\n"""`;
return Response.json(await ask(system, [{ role: "user", content: prompt }], writeSchema, "medium"));
}
} catch (error) {
if (error instanceof Anthropic.AuthenticationError) return Response.json({ error: "auth" }, { status: 401 });
if (error instanceof Anthropic.RateLimitError) return Response.json({ error: "rate" }, { status: 429 });
if (error instanceof Anthropic.APIError) return Response.json({ error: `api ${error.status}` }, { status: 502 });
return Response.json({ error: "failed" }, { status: 500 });
}
return Response.json({ error: "unknown mode" }, { status: 400 });
}
+179
View File
@@ -0,0 +1,179 @@
"use client";
import { useEffect, useState } from "react";
import { resetProgress, updateSettings, useProgress } from "@/lib/progress";
import { downloadCalendarReminder, notificationsSupported, registerServiceWorker, requestNotificationPermission, showReminder } from "@/lib/reminder";
import { germanVoices, speak } from "@/lib/speech";
import Ar from "@/components/Ar";
export default function EinstellungenPage() {
const p = useProgress();
const [perm, setPerm] = useState<string>("…");
const [msg, setMsg] = useState("");
const [ai, setAi] = useState<boolean | null>(null);
const [voices, setVoices] = useState<string[]>([]);
useEffect(() => {
setPerm(notificationsSupported() ? Notification.permission : "unsupported");
fetch("/api/coach")
.then((r) => r.json())
.then((d: { enabled: boolean }) => setAi(d.enabled))
.catch(() => setAi(false));
const load = () => setVoices(germanVoices().map((v) => `${v.name} (${v.lang})`));
load();
const t = setTimeout(load, 800);
return () => clearTimeout(t);
}, []);
const enableReminders = async (on: boolean) => {
if (!on) {
updateSettings({ reminder: { ...p.reminder, enabled: false } });
return;
}
const r = await requestNotificationPermission();
setPerm(r);
if (r === "granted") {
await registerServiceWorker();
updateSettings({ reminder: { ...p.reminder, enabled: true } });
setMsg("✅ Erinnerungen sind aktiv! • التذكيرات مفعّلة!");
} else if (r === "unsupported") {
setMsg("Dieser Browser unterstützt keine Benachrichtigungen. Nutze die Kalender-Erinnerung unten. • استخدم تذكير التقويم.");
} else {
setMsg("Benachrichtigungen wurden blockiert. Erlaube sie in den Browser-Einstellungen. • اسمح بالإشعارات في إعدادات المتصفح.");
}
};
return (
<div>
<h1>⚙️ Einstellungen</h1>
<p className="sub">
Personalisiere deinen Lernplan. <Ar>خصّص خطة تعلّمك.</Ar>
</p>
<div className="card">
<h3>👤 Profil</h3>
<label className="small muted">Dein Name • اسمك</label>
<input value={p.name} onChange={(e) => updateSettings({ name: e.target.value })} placeholder="z. B. Chadi" />
<label className="small muted" style={{ display: "block", marginTop: 10 }}>
Prüfungsdatum • تاريخ الامتحان
</label>
<input type="date" value={p.examDate ?? ""} onChange={(e) => updateSettings({ examDate: e.target.value || null })} />
<label className="small muted" style={{ display: "block", marginTop: 10 }}>
Tagesziel • هدف اليوم
</label>
<div className="grid grid-3">
{[
{ xp: 30, de: "🙂 Locker", ar: "خفيف" },
{ xp: 50, de: "💪 Normal", ar: "عادي" },
{ xp: 100, de: "🔥 Intensiv", ar: "مكثّف" },
].map((g) => (
<button key={g.xp} className={`option ${p.dailyGoal === g.xp ? "selected" : ""}`} style={{ flexDirection: "column", alignItems: "center" }} onClick={() => updateSettings({ dailyGoal: g.xp })}>
<span>{g.de}</span>
<span className="small muted">
{g.xp} XP • {g.ar}
</span>
</button>
))}
</div>
</div>
<div className="card">
<h3>🔔 Tägliche Erinnerung • التذكير اليومي</h3>
<label className="row" style={{ cursor: "pointer" }}>
<input type="checkbox" checked={p.reminder.enabled} onChange={(e) => void enableReminders(e.target.checked)} style={{ width: 22, height: 22 }} />
<b>Jeden Tag erinnern</b>
</label>
<label className="small muted" style={{ display: "block", marginTop: 10 }}>
Uhrzeit • الوقت
</label>
<input type="time" value={p.reminder.time} onChange={(e) => updateSettings({ reminder: { ...p.reminder, time: e.target.value } })} />
<div className="small muted" style={{ marginTop: 6 }}>
Status: {perm === "granted" ? "✅ erlaubt" : perm === "denied" ? "🚫 blockiert" : perm === "unsupported" ? "❌ nicht unterstützt" : "❔ noch nicht gefragt"}
</div>
{msg && <div className="feedback ok">{msg}</div>}
<div className="row" style={{ marginTop: 12 }}>
<button className="btn secondary small" disabled={perm !== "granted"} onClick={() => void showReminder(true)}>
🔔 Test-Benachrichtigung
</button>
<button className="btn blue small" onClick={() => downloadCalendarReminder(p.reminder.time)}>
📅 Als Kalender-Erinnerung speichern
</button>
</div>
<details style={{ marginTop: 12 }}>
<summary>Wie funktionieren die Erinnerungen? • كيف تعمل التذكيرات؟</summary>
<ul className="small" style={{ paddingLeft: 18, lineHeight: 1.7 }}>
<li>Wenn du heute noch nicht gelernt hast, bekommst du zur gewählten Uhrzeit eine Benachrichtigung.</li>
<li>
Am Handy: Installiere die App (Browser-Menü → „Zum Startbildschirm hinzufügen“). Auf Android/Chrome kommen die Erinnerungen dann auch bei geschlossener App (der Browser
entscheidet über den genauen Zeitpunkt).
</li>
<li>Auf iPhone (ab iOS 16.4) gehen Benachrichtigungen nur bei installierter App, solange sie im Hintergrund läuft.</li>
<li>
<b>Am zuverlässigsten:</b> „Als Kalender-Erinnerung speichern“ – dein Handy-Kalender erinnert dich dann jeden Tag, egal welcher Browser.
</li>
</ul>
<Ar block>
<span className="small">
إذا لم تدرس اليوم ستصلك إشعار في الوقت المحدد. على الهاتف: ثبّت التطبيق على الشاشة الرئيسية. الطريقة الأكثر موثوقية هي حفظ التذكير في تقويم الهاتف – سيذكّرك كل يوم.
</span>
</Ar>
</details>
</div>
<div className="card">
<h3>🎛️ Lernen</h3>
<label className="row" style={{ cursor: "pointer" }}>
<input type="checkbox" checked={p.showArabic} onChange={(e) => updateSettings({ showArabic: e.target.checked })} style={{ width: 22, height: 22 }} />
<span>
<b>Arabische Übersetzungen anzeigen</b>
<br />
<span className="small muted">Aus = Challenge-Modus: Übersetzung erst nach Antippen • إخفاء الترجمة لتحدٍّ أكبر</span>
</span>
</label>
<label className="row" style={{ cursor: "pointer", marginTop: 10 }}>
<input type="checkbox" checked={p.sound} onChange={(e) => updateSettings({ sound: e.target.checked })} style={{ width: 22, height: 22 }} />
<b>Soundeffekte 🔊</b>
</label>
<div style={{ marginTop: 12 }}>
<b>Deutsche Stimmen auf diesem Gerät:</b>{" "}
<button className="btn secondary small" onClick={() => speak("Hallo! Ich bin deine Stimme für die Hörübungen. Viel Erfolg bei der Prüfung!")}>
🔊 Testen
</button>
<div className="small muted" style={{ marginTop: 4 }}>
{voices.length ? voices.join(" • ") : "Keine deutsche Stimme gefunden – installiere eine deutsche Sprachausgabe im System (Windows: Einstellungen → Zeit & Sprache → Sprache)."}
</div>
</div>
</div>
<div className="card">
<h3>🤖 KI-Gesprächspartner</h3>
{ai === null ? (
<p className="muted">Prüfe …</p>
) : ai ? (
<div className="feedback ok">✅ Aktiv – im Sprechen-Teil führt die KI echte, freie Gespräche und korrigiert deine Texte im Schreiben-Teil.</div>
) : (
<div className="small">
<p style={{ marginTop: 0 }}>
Nicht aktiv. Die App funktioniert trotzdem komplett mit dem eingebauten Trainer. Für freie KI-Gespräche und KI-Textkorrektur: Lege im Projektordner eine Datei <code>.env.local</code>{" "}
mit <code>ANTHROPIC_API_KEY=…</code> an und starte die App neu.
</p>
<Ar block>غير مفعّل. التطبيق يعمل كاملاً بدونه. لتفعيل المحادثة الحرة بالذكاء الاصطناعي أضف مفتاح API في ملف ‎.env.local ثم أعد تشغيل التطبيق.</Ar>
</div>
)}
</div>
<div className="card" style={{ borderColor: "var(--red)" }}>
<h3>🗑️ Fortschritt zurücksetzen</h3>
<p className="small muted">Löscht XP, Serie, Karteikarten und Ergebnisse auf diesem Gerät.</p>
<button
className="btn small"
onClick={() => {
if (window.confirm("Wirklich den gesamten Fortschritt löschen? • هل تريد حذف كل التقدّم؟")) resetProgress();
}}
>
Zurücksetzen
</button>
</div>
</div>
);
}
+880
View File
@@ -0,0 +1,880 @@
:root {
--bg: #fff8f0;
--bg2: #ffffff;
--card: #ffffff;
--text: #1f2a44;
--muted: #6b7280;
--line: #f0e4d7;
--red: #e63946;
--red-soft: #ffe3e5;
--yellow: #ffb703;
--yellow-soft: #fff3cd;
--green: #2a9d8f;
--green-soft: #d8f3ee;
--blue: #3a86ff;
--blue-soft: #e0ecff;
--purple: #8338ec;
--purple-soft: #efe4ff;
--orange: #fb8500;
--orange-soft: #ffe8d1;
--shadow: 0 6px 20px rgba(31, 42, 68, 0.08);
--shadow-pop: 0 4px 0 rgba(31, 42, 68, 0.15);
--radius: 20px;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #121826;
--bg2: #182033;
--card: #1c2539;
--text: #f1f3f8;
--muted: #9aa3b5;
--line: #2a3550;
--red-soft: #3a1f27;
--yellow-soft: #3a3220;
--green-soft: #173533;
--blue-soft: #1b2a47;
--purple-soft: #2a1f45;
--orange-soft: #3a2a1b;
--shadow: 0 6px 20px rgba(0, 0, 0, 0.35);
--shadow-pop: 0 4px 0 rgba(0, 0, 0, 0.4);
}
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
background: var(--bg);
color: var(--text);
font-family: var(--font-latin), system-ui, sans-serif;
-webkit-tap-highlight-color: transparent;
}
body {
min-height: 100dvh;
overflow-x: hidden;
}
a {
color: inherit;
text-decoration: none;
}
button {
font-family: inherit;
font-size: inherit;
color: inherit;
}
textarea,
input,
select {
font-family: inherit;
font-size: 16px;
color: var(--text);
background: var(--bg2);
border: 2px solid var(--line);
border-radius: 14px;
padding: 12px 14px;
width: 100%;
outline: none;
}
textarea:focus,
input:focus,
select:focus {
border-color: var(--blue);
}
.ar {
font-family: var(--font-arabic), "Segoe UI", Tahoma, sans-serif;
direction: rtl;
unicode-bidi: isolate;
line-height: 1.8;
}
.hide-ar .ar.optional {
display: none;
}
/* ---------- Layout ---------- */
.shell {
max-width: 820px;
margin: 0 auto;
padding: 0 16px 110px;
}
.topbar {
position: sticky;
top: 0;
z-index: 20;
background: color-mix(in srgb, var(--bg) 88%, transparent);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--line);
}
.topbar-inner {
max-width: 820px;
margin: 0 auto;
padding: 10px 16px;
display: flex;
align-items: center;
gap: 10px;
}
.brand {
display: flex;
align-items: center;
gap: 8px;
font-weight: 900;
font-size: 18px;
margin-right: auto;
}
.brand img {
width: 30px;
height: 30px;
}
.chip {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 6px 11px;
border-radius: 999px;
font-weight: 800;
font-size: 14px;
background: var(--card);
border: 2px solid var(--line);
white-space: nowrap;
}
.chip.fire {
color: var(--orange);
}
.chip.xp {
color: var(--purple);
}
.bottomnav {
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 30;
background: var(--card);
border-top: 1px solid var(--line);
padding-bottom: env(safe-area-inset-bottom);
}
.bottomnav-inner {
max-width: 820px;
margin: 0 auto;
display: grid;
grid-template-columns: repeat(7, 1fr);
}
.navlink {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
padding: 8px 2px 9px;
font-size: 11px;
font-weight: 700;
color: var(--muted);
border-top: 3px solid transparent;
}
.navlink .ico {
font-size: 21px;
line-height: 1;
}
.navlink.active {
color: var(--red);
border-top-color: var(--red);
}
/* ---------- Bausteine ---------- */
h1 {
font-size: 28px;
margin: 22px 0 4px;
font-weight: 900;
letter-spacing: -0.5px;
}
h2 {
font-size: 20px;
margin: 26px 0 10px;
font-weight: 900;
}
h3 {
margin: 0 0 6px;
font-size: 17px;
font-weight: 800;
}
.sub {
color: var(--muted);
margin: 0 0 14px;
}
.card {
background: var(--card);
border: 2px solid var(--line);
border-radius: var(--radius);
padding: 18px;
box-shadow: var(--shadow);
}
.card + .card {
margin-top: 12px;
}
.grid {
display: grid;
gap: 12px;
}
.grid-2 {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.grid-3 {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
@media (max-width: 560px) {
.grid-3 {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
.tile {
display: block;
border-radius: var(--radius);
padding: 16px;
border: 2px solid var(--line);
background: var(--card);
box-shadow: var(--shadow-pop);
transition: transform 0.12s ease, box-shadow 0.12s ease;
cursor: pointer;
text-align: left;
width: 100%;
}
.tile:hover {
transform: translateY(-2px);
}
.tile:active {
transform: translateY(2px);
box-shadow: none;
}
.tile .emoji {
font-size: 30px;
}
.tile .t {
font-weight: 900;
font-size: 17px;
margin-top: 6px;
}
.tile .s {
color: var(--muted);
font-size: 13px;
margin-top: 2px;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
border: none;
border-radius: 16px;
padding: 13px 20px;
font-weight: 900;
font-size: 16px;
cursor: pointer;
background: var(--red);
color: #fff;
box-shadow: 0 4px 0 #b02a35;
transition: transform 0.08s ease, box-shadow 0.08s ease, opacity 0.2s;
user-select: none;
}
.btn:active {
transform: translateY(3px);
box-shadow: 0 1px 0 #b02a35;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn.secondary {
background: var(--card);
color: var(--text);
border: 2px solid var(--line);
box-shadow: 0 4px 0 var(--line);
}
.btn.green {
background: var(--green);
box-shadow: 0 4px 0 #1f7469;
}
.btn.blue {
background: var(--blue);
box-shadow: 0 4px 0 #2763c4;
}
.btn.purple {
background: var(--purple);
box-shadow: 0 4px 0 #5f22b3;
}
.btn.small {
padding: 8px 13px;
font-size: 14px;
border-radius: 12px;
}
.btn.block {
width: 100%;
}
.row {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.spacer {
flex: 1;
}
.muted {
color: var(--muted);
}
.small {
font-size: 13px;
}
.pill {
display: inline-block;
padding: 3px 10px;
border-radius: 999px;
font-size: 12px;
font-weight: 800;
background: var(--blue-soft);
color: var(--blue);
}
.pill.green {
background: var(--green-soft);
color: var(--green);
}
.pill.red {
background: var(--red-soft);
color: var(--red);
}
.pill.yellow {
background: var(--yellow-soft);
color: #b07d00;
}
.pill.purple {
background: var(--purple-soft);
color: var(--purple);
}
.bar {
height: 12px;
border-radius: 999px;
background: var(--line);
overflow: hidden;
}
.bar > div {
height: 100%;
border-radius: 999px;
background: linear-gradient(90deg, var(--yellow), var(--orange));
transition: width 0.5s ease;
}
.bar.green > div {
background: linear-gradient(90deg, #52c7b8, var(--green));
}
.tabs {
display: flex;
gap: 8px;
overflow-x: auto;
padding: 2px 0 8px;
scrollbar-width: none;
}
.tabs button {
flex: 0 0 auto;
border: 2px solid var(--line);
background: var(--card);
border-radius: 999px;
padding: 8px 14px;
font-weight: 800;
cursor: pointer;
}
.tabs button.active {
background: var(--text);
color: var(--bg);
border-color: var(--text);
}
/* ---------- Quiz ---------- */
.option {
display: flex;
width: 100%;
text-align: left;
gap: 10px;
align-items: center;
padding: 13px 15px;
border-radius: 14px;
border: 2px solid var(--line);
background: var(--bg2);
cursor: pointer;
font-weight: 700;
margin-top: 8px;
transition: transform 0.08s ease;
}
.option:hover:not(:disabled) {
border-color: var(--blue);
}
.option:active:not(:disabled) {
transform: scale(0.98);
}
.option .key {
flex: 0 0 28px;
height: 28px;
border-radius: 9px;
display: grid;
place-items: center;
background: var(--line);
font-size: 13px;
font-weight: 900;
}
.option.correct {
border-color: var(--green);
background: var(--green-soft);
}
.option.selected {
border-color: var(--blue);
background: var(--blue-soft);
}
.option.wrong {
border-color: var(--red);
background: var(--red-soft);
animation: shake 0.35s;
}
.option:disabled {
cursor: default;
}
@keyframes shake {
0%,
100% {
transform: translateX(0);
}
25% {
transform: translateX(-6px);
}
75% {
transform: translateX(6px);
}
}
.feedback {
margin-top: 10px;
padding: 10px 12px;
border-radius: 12px;
font-weight: 700;
font-size: 14px;
}
.feedback.ok {
background: var(--green-soft);
color: var(--green);
}
.feedback.no {
background: var(--red-soft);
color: var(--red);
}
.reading {
white-space: pre-wrap;
line-height: 1.75;
font-size: 16.5px;
}
.word-chip {
border: 2px solid var(--line);
background: var(--bg2);
border-radius: 12px;
padding: 8px 12px;
font-weight: 800;
cursor: pointer;
box-shadow: 0 3px 0 var(--line);
}
.word-chip:active {
transform: translateY(2px);
box-shadow: none;
}
.drop-zone {
min-height: 56px;
border: 2px dashed var(--line);
border-radius: 14px;
padding: 8px;
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
/* ---------- Karteikarten ---------- */
.flip {
perspective: 1200px;
cursor: pointer;
user-select: none;
}
.flip-inner {
position: relative;
min-height: 280px;
transition: transform 0.55s cubic-bezier(0.2, 0.8, 0.2, 1);
transform-style: preserve-3d;
}
.flip.flipped .flip-inner {
transform: rotateY(180deg);
}
.face {
position: absolute;
inset: 0;
backface-visibility: hidden;
border-radius: 26px;
padding: 24px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
border: 2px solid var(--line);
box-shadow: var(--shadow);
}
.face.front {
background: linear-gradient(135deg, var(--card), var(--blue-soft));
}
.face.back {
transform: rotateY(180deg);
background: linear-gradient(135deg, var(--card), var(--yellow-soft));
}
.art-der {
color: #3a86ff;
}
.art-die {
color: #e63946;
}
.art-das {
color: #2a9d8f;
}
/* ---------- Chat ---------- */
.chat {
display: flex;
flex-direction: column;
gap: 10px;
}
.bubble {
max-width: 86%;
padding: 12px 14px;
border-radius: 18px;
line-height: 1.5;
animation: pop 0.25s ease;
}
.bubble.bot {
align-self: flex-start;
background: var(--card);
border: 2px solid var(--line);
border-bottom-left-radius: 6px;
}
.bubble.me {
align-self: flex-end;
background: var(--blue);
color: #fff;
border-bottom-right-radius: 6px;
}
.bubble.tip {
align-self: stretch;
max-width: 100%;
background: var(--yellow-soft);
border: 2px dashed var(--yellow);
font-size: 14px;
}
@keyframes pop {
from {
transform: scale(0.92);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
.typing span {
display: inline-block;
width: 7px;
height: 7px;
margin: 0 2px;
border-radius: 50%;
background: var(--muted);
animation: blink 1.2s infinite;
}
.typing span:nth-child(2) {
animation-delay: 0.2s;
}
.typing span:nth-child(3) {
animation-delay: 0.4s;
}
@keyframes blink {
0%,
80%,
100% {
opacity: 0.25;
}
40% {
opacity: 1;
}
}
.composer {
position: sticky;
bottom: 74px;
background: var(--bg);
padding: 10px 0;
}
.mic {
width: 54px;
height: 54px;
border-radius: 50%;
border: none;
font-size: 22px;
cursor: pointer;
background: var(--red);
color: #fff;
box-shadow: 0 4px 0 #b02a35;
flex: 0 0 auto;
}
.mic.on {
animation: pulse 1.2s infinite;
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 rgba(230, 57, 70, 0.6);
}
100% {
box-shadow: 0 0 0 18px rgba(230, 57, 70, 0);
}
}
/* ---------- Toasts & Konfetti ---------- */
.toasts {
position: fixed;
top: 64px;
left: 50%;
transform: translateX(-50%);
z-index: 60;
display: flex;
flex-direction: column;
gap: 8px;
align-items: center;
pointer-events: none;
width: min(92vw, 420px);
}
.toast {
background: var(--text);
color: var(--bg);
padding: 10px 16px;
border-radius: 14px;
font-weight: 800;
box-shadow: var(--shadow);
animation: toastIn 0.3s ease, toastOut 0.3s ease 2.4s forwards;
text-align: center;
}
@keyframes toastIn {
from {
transform: translateY(-12px) scale(0.95);
opacity: 0;
}
}
@keyframes toastOut {
to {
transform: translateY(-12px);
opacity: 0;
}
}
.confetti {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 70;
overflow: hidden;
}
.confetti i {
position: absolute;
top: -20px;
width: 10px;
height: 14px;
border-radius: 2px;
animation: fall linear forwards;
}
@keyframes fall {
to {
transform: translateY(110vh) rotate(720deg);
}
}
.ring {
--p: 0;
width: 92px;
height: 92px;
border-radius: 50%;
background: conic-gradient(var(--orange) calc(var(--p) * 1%), var(--line) 0);
display: grid;
place-items: center;
flex: 0 0 auto;
}
.ring > div {
width: 72px;
height: 72px;
border-radius: 50%;
background: var(--card);
display: grid;
place-items: center;
font-weight: 900;
font-size: 18px;
text-align: center;
line-height: 1.1;
}
.hero {
border-radius: 26px;
padding: 20px;
color: #fff;
background: linear-gradient(135deg, #e63946 0%, #fb8500 100%);
box-shadow: var(--shadow);
position: relative;
overflow: hidden;
}
.hero::after {
content: "";
position: absolute;
right: -40px;
top: -40px;
width: 160px;
height: 160px;
border-radius: 50%;
background: rgba(255, 255, 255, 0.12);
}
.kbd-hint {
font-size: 12px;
color: var(--muted);
}
.fade-in {
animation: pop 0.3s ease;
}
.week {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 6px;
text-align: center;
font-size: 12px;
font-weight: 800;
}
.week .d {
aspect-ratio: 1;
border-radius: 12px;
display: grid;
place-items: center;
background: var(--line);
font-size: 16px;
}
.week .d.on {
background: var(--orange-soft);
border: 2px solid var(--orange);
}
details summary {
cursor: pointer;
font-weight: 800;
}
.slide {
border-left: 5px solid var(--purple);
padding: 10px 14px;
background: var(--purple-soft);
border-radius: 12px;
margin-top: 8px;
}
.timer {
font-variant-numeric: tabular-nums;
font-weight: 900;
}
+231
View File
@@ -0,0 +1,231 @@
"use client";
import { useMemo, useState } from "react";
import { lessons, type GrammarEx, type Lesson } from "@/data/grammatik";
import Ar from "@/components/Ar";
import SpeakButton from "@/components/SpeakButton";
import ResultCard from "@/components/ResultCard";
import { recordResult, useProgress } from "@/lib/progress";
import { sfx } from "@/lib/sfx";
export default function GrammatikPage() {
const [lesson, setLesson] = useState<Lesson | null>(null);
const p = useProgress();
if (lesson) return <LessonView key={lesson.id} lesson={lesson} onBack={() => setLesson(null)} />;
return (
<div>
<h1>🧩 Grammatik</h1>
<p className="sub">
Die wichtigsten B1-Themen – auf Arabisch erklärt, mit Übungen. <Ar>أهم مواضيع B1 – مشروحة بالعربية مع تمارين.</Ar>
</p>
<div className="grid grid-2">
{lessons.map((l) => {
const score = p.done[l.id];
return (
<button key={l.id} className="tile" onClick={() => setLesson(l)}>
<div className="row" style={{ alignItems: "flex-start" }}>
<span className="emoji">{l.emoji}</span>
<span className="spacer" />
{score !== undefined && <span className={`pill ${score >= 60 ? "green" : "yellow"}`}>{score} %</span>}
</div>
<div className="t">{l.title}</div>
<div className="s ar" style={{ textAlign: "left" }}>
{l.titleAr}
</div>
</button>
);
})}
</div>
</div>
);
}
function LessonView({ lesson, onBack }: { lesson: Lesson; onBack: () => void }) {
const [round, setRound] = useState(0);
const [results, setResults] = useState<(boolean | null)[]>(() => lesson.exercises.map(() => null));
const [awarded, setAwarded] = useState<{ c: number; t: number; xp: number } | null>(null);
const onAnswer = (i: number, ok: boolean) => {
const next = results.map((r, j) => (j === i ? ok : r));
setResults(next);
if (next.every((r) => r !== null) && !awarded) {
const c = next.filter(Boolean).length;
const xp = 5 + c * 2;
recordResult(lesson.id, "grammatik", (c / next.length) * 100, xp);
setAwarded({ c, t: next.length, xp });
}
};
return (
<div>
<button className="btn secondary small" style={{ marginTop: 16 }} onClick={onBack}>
← Zurück
</button>
<h1 style={{ fontSize: 24 }}>
{lesson.emoji} {lesson.title}
</h1>
<div className="ar muted">{lesson.titleAr}</div>
<div className="card" style={{ marginTop: 12, background: "var(--purple-soft)", borderColor: "var(--purple)" }}>
<h3>📚 الشرح</h3>
{lesson.explainAr.map((t, i) => (
<p key={i} className="ar" style={{ margin: "4px 0" }}>
{t}
</p>
))}
</div>
<h2>Regeln • القواعد</h2>
<div className="card">
{lesson.rules.map((r, i) => (
<div key={i} style={{ padding: "8px 0", borderBottom: i < lesson.rules.length - 1 ? "1px dashed var(--line)" : "none" }}>
<div style={{ fontWeight: 800 }}>{r.de}</div>
<div className="ar small muted">{r.ar}</div>
</div>
))}
</div>
<h2>Beispiele • أمثلة</h2>
{lesson.examples.map((e, i) => (
<div key={i} className="card row" style={{ flexWrap: "nowrap" }}>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 700 }}>{e.de}</div>
<Ar block>
<span className="small muted">{e.ar}</span>
</Ar>
</div>
<SpeakButton text={e.de} />
</div>
))}
<h2>Übungen • تمارين</h2>
<div key={round}>
{lesson.exercises.map((ex, i) => (
<div key={i} className="card" style={{ marginTop: 12 }}>
<div className="row" style={{ marginBottom: 6 }}>
<span className="pill">{i + 1}</span>
<span className="small muted">{ex.kind === "order" ? "Bring die Wörter in die richtige Reihenfolge • رتّب الكلمات" : "Wähle die richtige Antwort • اختر الإجابة الصحيحة"}</span>
</div>
{ex.kind === "mc" ? <McEx ex={ex} onAnswer={(ok) => onAnswer(i, ok)} /> : <OrderEx ex={ex} onAnswer={(ok) => onAnswer(i, ok)} />}
</div>
))}
</div>
{awarded && (
<ResultCard
correct={awarded.c}
total={awarded.t}
xp={awarded.xp}
onRetry={() => {
setResults(lesson.exercises.map(() => null));
setAwarded(null);
setRound((r) => r + 1);
}}
/>
)}
</div>
);
}
function McEx({ ex, onAnswer }: { ex: Extract<GrammarEx, { kind: "mc" }>; onAnswer: (ok: boolean) => void }) {
const [chosen, setChosen] = useState<number | null>(null);
return (
<div>
<div style={{ fontWeight: 800, fontSize: 17 }}>{ex.q}</div>
{ex.ar && (
<Ar block>
<span className="small muted">{ex.ar}</span>
</Ar>
)}
<div className="grid grid-2">
{ex.options.map((o, i) => {
let cls = "option";
if (chosen !== null && i === ex.answer) cls += " correct";
else if (chosen === i) cls += " wrong";
return (
<button
key={i}
className={cls}
disabled={chosen !== null}
onClick={() => {
setChosen(i);
const ok = i === ex.answer;
if (ok) sfx.correct();
else sfx.wrong();
onAnswer(ok);
}}
>
{o}
</button>
);
})}
</div>
{chosen !== null && (
<div className={`feedback ${chosen === ex.answer ? "ok" : "no"}`}>
{chosen === ex.answer ? "Richtig! 🎉" : `Richtig wäre: ${ex.options[ex.answer]}`}
{ex.why && <span style={{ fontWeight: 600 }}> – {ex.why}</span>}
</div>
)}
</div>
);
}
function OrderEx({ ex, onAnswer }: { ex: Extract<GrammarEx, { kind: "order" }>; onAnswer: (ok: boolean) => void }) {
const shuffled = useMemo(() => {
const idx = ex.words.map((_, i) => i);
for (let k = 0; k < 20; k++) {
idx.sort(() => Math.random() - 0.5);
if (idx.some((v, i) => v !== i)) break;
}
return idx;
}, [ex]);
const [picked, setPicked] = useState<number[]>([]);
const [checked, setChecked] = useState<boolean | null>(null);
const target = ex.words.join(" ");
const current = picked.map((i) => ex.words[i]).join(" ");
const check = () => {
const ok = current === target;
setChecked(ok);
if (ok) sfx.correct();
else sfx.wrong();
onAnswer(ok);
};
return (
<div>
<Ar block>
<span className="small">{ex.ar}</span>
</Ar>
<div className="drop-zone" style={{ marginTop: 8, borderColor: checked === null ? undefined : checked ? "var(--green)" : "var(--red)" }}>
{picked.length === 0 && <span className="muted small">Tippe die Wörter an …</span>}
{picked.map((wi, k) => (
<button key={k} className="word-chip" disabled={checked !== null} onClick={() => setPicked((p) => p.filter((_, j) => j !== k))}>
{ex.words[wi]}
</button>
))}
</div>
<div className="row" style={{ marginTop: 10 }}>
{shuffled
.filter((i) => !picked.includes(i))
.map((i) => (
<button key={i} className="word-chip" disabled={checked !== null} onClick={() => setPicked((p) => [...p, i])}>
{ex.words[i]}
</button>
))}
</div>
{checked === null ? (
<button className="btn green small" style={{ marginTop: 10 }} disabled={picked.length !== ex.words.length} onClick={check}>
Prüfen ✔
</button>
) : (
<div className={`feedback ${checked ? "ok" : "no"}`}>
{checked ? "Perfekt! 🎉" : "Richtig wäre:"} {!checked && <b>{target}</b>}
<span style={{ marginLeft: 8 }}>
<SpeakButton text={target} />
</span>
</div>
)}
</div>
);
}
+189
View File
@@ -0,0 +1,189 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { hoerItems, hoerTeile, type HoerItem } from "@/data/hoeren";
import Quiz from "@/components/Quiz";
import ResultCard from "@/components/ResultCard";
import Ar from "@/components/Ar";
import { recordResult, useProgress } from "@/lib/progress";
import { hasGermanVoice, speakSequence, stopSpeaking, TTS_MISSING_EVENT, ttsSupported } from "@/lib/speech";
export default function HoerenPage() {
const [teil, setTeil] = useState<number>(1);
const [item, setItem] = useState<HoerItem | null>(null);
const p = useProgress();
const list = hoerItems.filter((h) => h.teil === teil);
const info = hoerTeile.find((t) => t.teil === teil)!;
if (item) return <Player key={item.id} item={item} onBack={() => setItem(null)} />;
return (
<div>
<h1>🎧 Hören</h1>
<p className="sub">
Hör genau zu und beantworte die Fragen. <Ar>استمع جيداً وأجب عن الأسئلة.</Ar>
</p>
<div className="tabs">
{hoerTeile.map((t) => (
<button key={t.teil} className={teil === t.teil ? "active" : ""} onClick={() => setTeil(t.teil)}>
Teil {t.teil}
</button>
))}
</div>
<div className="card" style={{ background: "var(--blue-soft)", borderColor: "var(--blue)" }}>
<h3>{info.de}</h3>
<div className="ar">{info.ar}</div>
<div className="small" style={{ marginTop: 4 }}>
💡 {info.hint}
</div>
</div>
<div className="grid" style={{ marginTop: 12 }}>
{list.map((h) => {
const score = p.done[h.id];
return (
<button key={h.id} className="tile" onClick={() => setItem(h)}>
<div className="row">
<span style={{ fontSize: 28 }}>{h.lines.length > 1 ? "💬" : "📻"}</span>
<div style={{ flex: 1 }}>
<div className="t" style={{ marginTop: 0 }}>
{h.title}
</div>
<div className="s ar" style={{ textAlign: "left" }}>
{h.titleAr}
</div>
</div>
{score !== undefined ? <span className={`pill ${score >= 60 ? "green" : "yellow"}`}>{score} %</span> : <span className="pill">{h.questions.length} Fragen</span>}
</div>
</button>
);
})}
</div>
</div>
);
}
function Player({ item, onBack }: { item: HoerItem; onBack: () => void }) {
const [rate, setRate] = useState(0.95);
const [playing, setPlaying] = useState(false);
const [line, setLine] = useState(-1);
const [plays, setPlays] = useState(0);
const [exam, setExam] = useState(false);
const [result, setResult] = useState<{ c: number; t: number; xp: number } | null>(null);
const [round, setRound] = useState(0);
const stopRef = useRef<(() => void) | null>(null);
const maxPlays = item.teil === 1 || item.teil === 4 ? 2 : 1;
const voices = useMemo(() => {
const counters = { f: 0, m: 0 };
const map: Record<string, { gender: "f" | "m"; idx: number }> = {};
Object.entries(item.speakers).forEach(([name, g]) => {
map[name] = { gender: g, idx: counters[g]++ };
});
return map;
}, [item]);
useEffect(() => () => stopSpeaking(), []);
const play = () => {
if (playing) {
stopRef.current?.();
setPlaying(false);
setLine(-1);
return;
}
if (exam && plays >= maxPlays) return;
if (!hasGermanVoice()) {
window.dispatchEvent(new Event(TTS_MISSING_EVENT));
window.scrollTo({ top: 0, behavior: "smooth" });
return;
}
setPlaying(true);
setPlays((n) => n + 1);
stopRef.current = speakSequence(
item.lines.map((l) => ({ text: l.t, gender: voices[l.who]?.gender ?? "f", voiceIndex: voices[l.who]?.idx ?? 0 })),
rate,
(i) => setLine(i),
() => {
setPlaying(false);
setLine(-1);
},
);
};
return (
<div>
<button className="btn secondary small" style={{ marginTop: 16 }} onClick={onBack}>
← Zurück
</button>
<h1 style={{ fontSize: 24 }}>{item.title}</h1>
<div className="ar muted">{item.titleAr}</div>
<div className="card" style={{ marginTop: 12 }}>
<div className="pill">Teil {item.teil}</div>
<p style={{ fontWeight: 700 }}>{item.situation}</p>
<Ar block>{item.situationAr}</Ar>
{!ttsSupported() && <div className="feedback no">Dein Browser unterstützt keine Sprachausgabe. Bitte Chrome, Edge oder Safari verwenden.</div>}
<div className="row" style={{ marginTop: 14 }}>
<button className={`btn ${playing ? "secondary" : "blue"}`} onClick={play} disabled={!playing && exam && plays >= maxPlays}>
{playing ? "⏹ Stopp" : plays === 0 ? "▶ Abspielen" : "🔁 Nochmal hören"}
</button>
<select value={rate} onChange={(e) => setRate(Number(e.target.value))} style={{ width: "auto" }} aria-label="Geschwindigkeit">
<option value={0.75}>🐢 Langsam</option>
<option value={0.95}>🚶 Normal</option>
<option value={1.1}>🐇 Schnell</option>
</select>
<label className="row small" style={{ gap: 6 }}>
<input type="checkbox" checked={exam} onChange={(e) => setExam(e.target.checked)} style={{ width: 18, height: 18 }} />
Prüfungsmodus ({maxPlays}× hören)
</label>
</div>
<div className="small muted" style={{ marginTop: 8 }}>
{playing && line >= 0 ? `🔊 ${item.lines[line].who} spricht …` : `Gehört: ${plays}×`}
</div>
</div>
<h2>Fragen • الأسئلة</h2>
<Quiz
key={round}
questions={item.questions}
onFinish={(c, t) => {
const xp = 5 + c * 3;
recordResult(item.id, "hoeren", (c / t) * 100, xp);
setResult({ c, t, xp });
}}
/>
{result && (
<>
<ResultCard
correct={result.c}
total={result.t}
xp={result.xp}
onRetry={() => {
setResult(null);
setRound((r) => r + 1);
setPlays(0);
}}
/>
<h2>Transkript • النص</h2>
<div className="card">
{item.lines.map((l, i) => (
<p key={i} style={{ margin: "0 0 10px", background: line === i ? "var(--yellow-soft)" : undefined, borderRadius: 8 }}>
{item.lines.length > 1 || item.teil !== 1 ? <b>{l.who}: </b> : null}
{l.t}
</p>
))}
<details style={{ marginTop: 10 }}>
<summary>🌍 Arabische Übersetzung • الترجمة العربية</summary>
<div className="ar" style={{ marginTop: 8 }}>
{item.translationAr}
</div>
</details>
</div>
</>
)}
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
import type { Metadata, Viewport } from "next";
import { Nunito, Cairo } from "next/font/google";
import "./globals.css";
import AppShell from "@/components/AppShell";
const latin = Nunito({ subsets: ["latin", "latin-ext"], variable: "--font-latin", display: "swap" });
const arabic = Cairo({ subsets: ["arabic"], variable: "--font-arabic", display: "swap" });
export const metadata: Metadata = {
title: "B1 Meister – ÖSD B1 Prüfungstrainer",
description: "Bereite dich mit Spaß auf das ÖSD Zertifikat B1 vor: Hören, Lesen, Schreiben, Sprechen, Grammatik, Wortschatz – mit arabischer Übersetzung.",
icons: { icon: "/icon.svg", apple: "/icon.svg" },
appleWebApp: { capable: true, title: "B1 Meister", statusBarStyle: "default" },
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
themeColor: "#e63946",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="de" className={`${latin.variable} ${arabic.variable}`}>
<body>
<AppShell>{children}</AppShell>
</body>
</html>
);
}
+142
View File
@@ -0,0 +1,142 @@
"use client";
import { useState } from "react";
import { leseItems, leseTeile, type LeseItem } from "@/data/lesen";
import Quiz from "@/components/Quiz";
import ResultCard from "@/components/ResultCard";
import Ar from "@/components/Ar";
import SpeakButton from "@/components/SpeakButton";
import { recordResult, useProgress } from "@/lib/progress";
export default function LesenPage() {
const [teil, setTeil] = useState<number>(1);
const [item, setItem] = useState<LeseItem | null>(null);
const p = useProgress();
const info = leseTeile.find((t) => t.teil === teil)!;
if (item) return <Reader key={item.id} item={item} onBack={() => setItem(null)} />;
return (
<div>
<h1>📖 Lesen</h1>
<p className="sub">
Texte wie in der echten Prüfung – mit Wortliste und Übersetzung. <Ar>نصوص مثل الامتحان الحقيقي – مع قائمة كلمات وترجمة.</Ar>
</p>
<div className="tabs">
{leseTeile.map((t) => (
<button key={t.teil} className={teil === t.teil ? "active" : ""} onClick={() => setTeil(t.teil)}>
Teil {t.teil}
</button>
))}
</div>
<div className="card" style={{ background: "var(--green-soft)", borderColor: "var(--green)" }}>
<h3>{info.de}</h3>
<div className="ar">{info.ar}</div>
<div className="small" style={{ marginTop: 4 }}>
💡 {info.hint}
</div>
</div>
<div className="grid" style={{ marginTop: 12 }}>
{leseItems
.filter((l) => l.teil === teil)
.map((l) => {
const score = p.done[l.id];
return (
<button key={l.id} className="tile" onClick={() => setItem(l)}>
<div className="row">
<span style={{ fontSize: 28 }}>📰</span>
<div style={{ flex: 1 }}>
<div className="t" style={{ marginTop: 0 }}>
{l.title}
</div>
<div className="s">
{l.kind} • <span className="ar">{l.titleAr}</span>
</div>
</div>
{score !== undefined ? <span className={`pill ${score >= 60 ? "green" : "yellow"}`}>{score} %</span> : <span className="pill">{l.questions.length} Fragen</span>}
</div>
</button>
);
})}
</div>
</div>
);
}
function Reader({ item, onBack }: { item: LeseItem; onBack: () => void }) {
const [result, setResult] = useState<{ c: number; t: number; xp: number } | null>(null);
const [round, setRound] = useState(0);
const [showTr, setShowTr] = useState(false);
const [open, setOpen] = useState<number | null>(null);
return (
<div>
<button className="btn secondary small" style={{ marginTop: 16 }} onClick={onBack}>
← Zurück
</button>
<h1 style={{ fontSize: 24 }}>{item.title}</h1>
<div className="ar muted">{item.titleAr}</div>
<div className="card" style={{ marginTop: 12, background: "var(--yellow-soft)", borderColor: "var(--yellow)" }}>
<b>Aufgabe:</b> {item.task}
<Ar block>{item.taskAr}</Ar>
</div>
<div className="card" style={{ marginTop: 12 }}>
<div className="row" style={{ marginBottom: 8 }}>
<span className="pill green">{item.kind}</span>
<span className="spacer" />
<SpeakButton text={item.text} label="Vorlesen" />
</div>
<div className="reading">{item.text}</div>
</div>
<h2>Wortschatz-Hilfe • مساعدة المفردات</h2>
<div className="row">
{item.glossary.map((g, i) => (
<button key={i} className="word-chip" onClick={() => setOpen(open === i ? null : i)}>
{g.de}
{open === i && (
<span className="ar" style={{ display: "block", fontWeight: 600 }}>
{g.ar}
</span>
)}
</button>
))}
</div>
<h2>Fragen • الأسئلة</h2>
<Quiz
key={round}
questions={item.questions}
onFinish={(c, t) => {
const xp = 5 + c * 3;
recordResult(item.id, "lesen", (c / t) * 100, xp);
setResult({ c, t, xp });
}}
/>
{result && (
<ResultCard
correct={result.c}
total={result.t}
xp={result.xp}
onRetry={() => {
setResult(null);
setRound((r) => r + 1);
}}
/>
)}
<div style={{ marginTop: 16 }}>
<button className="btn secondary block" onClick={() => setShowTr((s) => !s)}>
🌍 {showTr ? "Übersetzung ausblenden" : "Arabische Übersetzung zeigen"} • الترجمة
</button>
{showTr && (
<div className="card ar fade-in" style={{ marginTop: 10 }}>
{item.translationAr}
</div>
)}
</div>
</div>
);
}
+15
View File
@@ -0,0 +1,15 @@
import type { MetadataRoute } from "next";
export default function manifest(): MetadataRoute.Manifest {
return {
name: "B1 Meister – ÖSD Prüfungstrainer",
short_name: "B1 Meister",
description: "ÖSD Zertifikat B1: Hören, Lesen, Schreiben, Sprechen, Grammatik und Wortschatz – Deutsch/Arabisch",
start_url: "/",
display: "standalone",
background_color: "#fff8f0",
theme_color: "#e63946",
lang: "de",
icons: [{ src: "/icon.svg", sizes: "any", type: "image/svg+xml", purpose: "any" }],
};
}
+229
View File
@@ -0,0 +1,229 @@
"use client";
import Link from "next/link";
import { useEffect, useState } from "react";
import { addDays, badgeInfo, levelInfo, todayStr, useProgress } from "@/lib/progress";
import { allWords, wordLabel } from "@/data/vocab";
import { hoerItems } from "@/data/hoeren";
import { leseItems } from "@/data/lesen";
import { schreibTasks } from "@/data/schreiben";
import { lessons } from "@/data/grammatik";
import SpeakButton from "@/components/SpeakButton";
import Ar from "@/components/Ar";
const tips = [
{ de: "Lies im Lesen-Teil zuerst die Aufgaben – dann weißt du, was du suchst.", ar: "في قسم القراءة اقرأ الأسئلة أولاً – هكذا تعرف ما تبحث عنه." },
{ de: "In Schreiben bekommst du Punkte für jeden Leitpunkt. Vergiss keinen!", ar: "في الكتابة تحصل على نقاط عن كل نقطة مطلوبة. لا تنسَ أياً منها!" },
{ de: "Beim Sprechen ist es okay, nachzufragen: „Können Sie das bitte wiederholen?“", ar: "في المحادثة لا بأس أن تسأل: «هل يمكنك تكرار ذلك من فضلك؟»" },
{ de: "Benutze Konnektoren wie „weil“, „deshalb“, „obwohl“ – das zeigt B1-Niveau.", ar: "استخدم أدوات الربط مثل weil وdeshalb وobwohl – هذا يُظهر مستوى B1." },
{ de: "Im Hören-Teil: Achte auf Zahlen, Uhrzeiten und Verneinungen („nicht“, „kein“).", ar: "في الاستماع: انتبه للأرقام والأوقات والنفي (nicht، kein)." },
{ de: "Lerne Nomen immer mit Artikel und Plural: der Tisch, die Tische.", ar: "تعلّم الأسماء دائماً مع الأداة والجمع." },
{ de: "15 Minuten jeden Tag sind besser als 2 Stunden am Sonntag.", ar: "15 دقيقة كل يوم أفضل من ساعتين يوم الأحد." },
{ de: "Sprich laut mit dir selbst – beim Kochen, beim Spazierengehen.", ar: "تحدّث بصوت عالٍ مع نفسك – أثناء الطبخ أو المشي." },
{ de: "In der Prüfung brauchst du in jedem Modul 60 %, um zu bestehen.", ar: "في الامتحان تحتاج 60% في كل وحدة لتنجح." },
{ de: "Bei der Präsentation: Struktur ist wichtiger als perfekte Grammatik.", ar: "في العرض التقديمي: التنظيم أهم من القواعد المثالية." },
];
const motivations = [
{ de: "Jeder Tag ein kleiner Schritt – und bald bist du B1! 🚀", ar: "كل يوم خطوة صغيرة – وقريباً ستصل إلى B1!" },
{ de: "Fehler sind Beweise, dass du es versuchst. 💪", ar: "الأخطاء دليل على أنك تحاول." },
{ de: "Du schaffst das! Schritt für Schritt. 🌟", ar: "ستنجح! خطوة بخطوة." },
{ de: "Heute lernen, morgen sprechen! 🗣️", ar: "تعلّم اليوم، وتحدّث غداً!" },
];
function dayIndex() {
const d = new Date();
return Math.floor(d.getTime() / 86400000);
}
export default function Home() {
const p = useProgress();
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
const li = levelInfo(p.xp);
const t = todayStr();
const todayXp = p.history[t] ?? 0;
const goalPct = Math.min(100, Math.round((todayXp / p.dailyGoal) * 100));
const di = dayIndex();
const word = allWords[di % allWords.length];
const tip = tips[di % tips.length];
const moti = motivations[di % motivations.length];
const dueCards = allWords.filter((w) => p.cards[w.id] && p.cards[w.id].due <= t).length;
const newCards = allWords.filter((w) => !p.cards[w.id]).length;
const hour = mounted ? new Date().getHours() : 12;
const greet = hour < 11 ? "Guten Morgen" : hour < 18 ? "Hallo" : "Guten Abend";
const greetAr = hour < 11 ? "صباح الخير" : hour < 18 ? "مرحباً" : "مساء الخير";
const week = Array.from({ length: 7 }, (_, i) => addDays(t, i - 6));
const wd = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];
const doneIn = (ids: string[]) => ids.filter((id) => p.done[id] !== undefined).length;
const sections = [
{ href: "/hoeren", emoji: "🎧", de: "Hören", ar: "الاستماع", done: doneIn(hoerItems.map((x) => x.id)), total: hoerItems.length, color: "var(--blue-soft)" },
{ href: "/lesen", emoji: "📖", de: "Lesen", ar: "القراءة", done: doneIn(leseItems.map((x) => x.id)), total: leseItems.length, color: "var(--green-soft)" },
{ href: "/schreiben", emoji: "✍️", de: "Schreiben", ar: "الكتابة", done: doneIn(schreibTasks.map((x) => x.id)), total: schreibTasks.length, color: "var(--yellow-soft)" },
{ href: "/sprechen", emoji: "🗣️", de: "Sprechen", ar: "المحادثة", done: p.sections.sprechen ?? 0, total: 0, color: "var(--red-soft)" },
{ href: "/grammatik", emoji: "🧩", de: "Grammatik", ar: "القواعد", done: doneIn(lessons.map((x) => x.id)), total: lessons.length, color: "var(--purple-soft)" },
{ href: "/wortschatz", emoji: "🃏", de: "Wortschatz", ar: "المفردات", done: allWords.length - newCards, total: allWords.length, color: "var(--orange-soft)" },
];
let countdown: number | null = null;
if (p.examDate) {
const [y, m, d] = p.examDate.split("-").map(Number);
const [ty, tm, td] = t.split("-").map(Number);
countdown = Math.round((new Date(y, m - 1, d).getTime() - new Date(ty, tm - 1, td).getTime()) / 86400000);
}
return (
<div>
<h1>
{greet}
{p.name ? `, ${p.name}` : ""}! 👋
</h1>
<p className="sub">
{moti.de} <Ar>{greetAr} – {moti.ar}</Ar>
</p>
<div className="hero">
<div className="row" style={{ position: "relative", zIndex: 1 }}>
<div style={{ flex: 1, minWidth: 180 }}>
<div style={{ opacity: 0.9, fontWeight: 700 }}>Level {li.level}</div>
<div style={{ fontSize: 26, fontWeight: 900 }}>{li.name}</div>
<div className="bar" style={{ background: "rgba(255,255,255,.3)", marginTop: 8 }}>
<div style={{ width: `${li.pct}%`, background: "#fff" }} />
</div>
<div className="small" style={{ marginTop: 4, opacity: 0.9 }}>
{li.into} / {li.need} XP bis Level {li.level + 1}
</div>
</div>
<div className="ring" style={{ ["--p" as string]: goalPct, background: `conic-gradient(#fff ${goalPct}%, rgba(255,255,255,.3) 0)` }}>
<div style={{ color: "var(--text)" }}>
{todayXp}
<span className="small muted">/{p.dailyGoal} XP</span>
</div>
</div>
</div>
<div style={{ position: "relative", zIndex: 1, marginTop: 10, fontWeight: 800 }}>
{goalPct >= 100 ? "🏆 Tagesziel geschafft! Super!" : "🎯 Tagesziel: " + p.dailyGoal + " XP"}
{countdown !== null && countdown >= 0 && <span> • 📅 Noch {countdown} Tage bis zur Prüfung</span>}
</div>
</div>
<div className="card" style={{ marginTop: 14 }}>
<div className="row">
<h3 style={{ margin: 0 }}>🔥 {p.streak} {p.streak === 1 ? "Tag" : "Tage"} Serie</h3>
<span className="spacer" />
<span className="small muted">Rekord: {p.bestStreak}</span>
</div>
<div className="week" style={{ marginTop: 10 }}>
{week.map((d) => {
const [y, m, dd] = d.split("-").map(Number);
const on = (p.history[d] ?? 0) > 0;
return (
<div key={d}>
<div className={`d ${on ? "on" : ""}`}>{on ? "🔥" : "·"}</div>
<div className="muted" style={{ marginTop: 3 }}>
{wd[new Date(y, m - 1, dd).getDay()]}
</div>
</div>
);
})}
</div>
{!p.reminder.enabled && (
<Link href="/einstellungen" className="btn secondary small" style={{ marginTop: 12 }}>
🔔 Tägliche Erinnerung einschalten
</Link>
)}
</div>
<h2>Prüfungsteile • أقسام الامتحان</h2>
<div className="grid grid-3">
{sections.map((s) => (
<Link key={s.href} href={s.href} className="tile" style={{ background: `linear-gradient(160deg, var(--card) 40%, ${s.color})` }}>
<div className="emoji">{s.emoji}</div>
<div className="t">{s.de}</div>
<div className="s ar" style={{ direction: "rtl", textAlign: "left" }}>
{s.ar}
</div>
<div className="bar green" style={{ marginTop: 8, height: 8 }}>
<div style={{ width: s.total ? `${Math.round((s.done / s.total) * 100)}%` : `${Math.min(100, s.done * 5)}%` }} />
</div>
<div className="s">{s.total ? `${s.done}/${s.total}` : `${s.done} Antworten`}</div>
</Link>
))}
</div>
<div className="grid grid-2" style={{ marginTop: 12 }}>
<Link href="/wortschatz" className="tile" style={{ background: "linear-gradient(135deg, var(--purple), var(--blue))", color: "#fff" }}>
<div className="emoji">🃏</div>
<div className="t">Karteikarten</div>
<div className="s" style={{ color: "#fff", opacity: 0.9 }}>
{mounted ? `${dueCards} fällig • ${newCards} neu` : "…"}
</div>
</Link>
<Link href="/pruefung" className="tile" style={{ background: "linear-gradient(135deg, var(--green), #52c7b8)", color: "#fff" }}>
<div className="emoji">🏅</div>
<div className="t">Modelltest</div>
<div className="s" style={{ color: "#fff", opacity: 0.9 }}>
Prüfung simulieren • امتحان تجريبي
</div>
</Link>
</div>
<h2>Wort des Tages • كلمة اليوم</h2>
<div className="card">
<div className="row">
<div style={{ fontSize: 24, fontWeight: 900 }}>
{word.art && <span className={`art-${word.art}`}>{word.art} </span>}
{word.de}
</div>
<span className="spacer" />
<SpeakButton text={wordLabel(word) + ". " + word.ex} />
</div>
{word.pl && <div className="muted small">{word.pl}</div>}
<div className="ar" style={{ fontSize: 20, fontWeight: 700 }}>
{word.ar}
</div>
<div style={{ marginTop: 6 }}>„{word.ex}“</div>
<Ar block>
<span className="muted">{word.exAr}</span>
</Ar>
</div>
<h2>Prüfungstipp • نصيحة</h2>
<div className="card" style={{ background: "var(--yellow-soft)", borderColor: "var(--yellow)" }}>
<div style={{ fontWeight: 800 }}>💡 {tip.de}</div>
<Ar block>{tip.ar}</Ar>
</div>
<h2>Abzeichen • الأوسمة</h2>
<div className="grid grid-3">
{Object.entries(badgeInfo).map(([id, b]) => {
const has = p.badges.includes(id);
return (
<div key={id} className="card" style={{ textAlign: "center", padding: 12, opacity: has ? 1 : 0.4, filter: has ? "none" : "grayscale(1)" }}>
<div style={{ fontSize: 30 }}>{b.emoji}</div>
<div className="small" style={{ fontWeight: 800 }}>
{b.de}
</div>
<div className="ar small muted">{b.ar}</div>
</div>
);
})}
</div>
<h2>Über die Prüfung • عن الامتحان</h2>
<div className="card">
<p style={{ marginTop: 0 }}>
Das <b>ÖSD Zertifikat B1</b> hat vier Module: Lesen (65 Min.), Hören (ca. 40 Min.), Schreiben (60 Min.) und Sprechen (ca. 15 Min., zu zweit). Du brauchst in jedem Modul
mindestens <b>60 %</b>. Die Module kann man einzeln ablegen.
</p>
<Ar block>
امتحان ÖSD B1 يتكون من أربع وحدات: القراءة (65 دقيقة)، الاستماع (حوالي 40 دقيقة)، الكتابة (60 دقيقة) والمحادثة (حوالي 15 دقيقة، مع شريك). تحتاج إلى 60% على الأقل في كل وحدة،
ويمكن تقديم الوحدات بشكل منفصل.
</Ar>
</div>
</div>
);
}
+293
View File
@@ -0,0 +1,293 @@
"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 { hasGermanVoice, 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 (!hasGermanVoice()) {
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>
</>
);
}
+350
View File
@@ -0,0 +1,350 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { schreibAufgaben, schreibRedemittel, schreibTasks, type SchreibTask } from "@/data/schreiben";
import Ar from "@/components/Ar";
import { recordResult, useProgress } from "@/lib/progress";
import { fireConfetti } from "@/components/AppShell";
export default function SchreibenPage() {
const [aufgabe, setAufgabe] = useState<1 | 2 | 3>(1);
const [task, setTask] = useState<SchreibTask | null>(null);
const p = useProgress();
const info = schreibAufgaben.find((a) => a.aufgabe === aufgabe)!;
if (task) return <Editor key={task.id} task={task} onBack={() => setTask(null)} />;
return (
<div>
<h1>✍️ Schreiben</h1>
<p className="sub">
Drei Aufgaben wie in der Prüfung. Schreib selbst – dann prüfen wir zusammen! <Ar>ثلاث مهام كما في الامتحان. اكتب بنفسك ثم نراجع معاً!</Ar>
</p>
<div className="tabs">
{schreibAufgaben.map((a) => (
<button key={a.aufgabe} className={aufgabe === a.aufgabe ? "active" : ""} onClick={() => setAufgabe(a.aufgabe)}>
Aufgabe {a.aufgabe}
</button>
))}
</div>
<div className="card" style={{ background: "var(--yellow-soft)", borderColor: "var(--yellow)" }}>
<div className="row">
<h3 style={{ margin: 0 }}>{info.de}</h3>
<span className="spacer" />
<span className="pill yellow">⏱ {info.time}</span>
</div>
<div className="ar">{info.ar}</div>
<ul style={{ margin: "8px 0 0", paddingLeft: 20 }}>
{info.tips.map((t, i) => (
<li key={i} style={{ marginBottom: 4 }}>
{t.de}
<br />
<Ar>
<span className="small muted">{t.ar}</span>
</Ar>
</li>
))}
</ul>
</div>
<div className="grid" style={{ marginTop: 12 }}>
{schreibTasks
.filter((t) => t.aufgabe === aufgabe)
.map((t) => {
const score = p.done[t.id];
return (
<button key={t.id} className="tile" onClick={() => setTask(t)}>
<div className="row">
<span style={{ fontSize: 28 }}>{aufgabe === 2 ? "💬" : "✉️"}</span>
<div style={{ flex: 1 }}>
<div className="t" style={{ marginTop: 0 }}>
{t.title}
</div>
<div className="s ar" style={{ textAlign: "left" }}>
{t.titleAr}
</div>
</div>
{score !== undefined ? <span className={`pill ${score >= 60 ? "green" : "yellow"}`}>{score} %</span> : <span className="pill">~{t.words} Wörter</span>}
</div>
</button>
);
})}
</div>
</div>
);
}
const connectors = ["weil", "dass", "deshalb", "deswegen", "aber", "außerdem", "obwohl", "wenn", "denn", "trotzdem", "damit", "zuerst", "dann", "danach", "einerseits", "andererseits", "zum beispiel", "meiner meinung nach", "ob", "als", "sondern", "darum", "also", "falls"];
interface Check {
ok: boolean;
de: string;
ar: string;
}
function selfCheck(task: SchreibTask, text: string, ticked: boolean[]): Check[] {
const lower = text.toLowerCase();
const words = text.trim().split(/\s+/).filter(Boolean).length;
const found = connectors.filter((c) => new RegExp(`(^|[^a-zäöüß])${c}([^a-zäöüß]|$)`, "i").test(lower));
const checks: Check[] = [
{
ok: words >= task.words * 0.8,
de: `Länge: ${words} Wörter (Ziel ca. ${task.words})`,
ar: words >= task.words * 0.8 ? "الطول مناسب" : "النص قصير جداً – اكتب أكثر",
},
{
ok: found.length >= (task.aufgabe === 3 ? 2 : 3),
de: `Konnektoren: ${found.length ? found.join(", ") : "keine"}`,
ar: "استخدم أدوات ربط مثل weil, deshalb, außerdem",
},
{
ok: ticked.every(Boolean),
de: "Alle Leitpunkte bearbeitet (selbst abhaken)",
ar: "هل كتبت عن كل النقاط؟",
},
];
if (task.aufgabe !== 2) {
checks.push({
ok: /^\s*(liebe|lieber|hallo|hi|sehr geehrte|sehr geehrter|guten tag)/i.test(text),
de: "Anrede am Anfang",
ar: task.aufgabe === 3 ? "ابدأ بـ Sehr geehrte/r …" : "ابدأ بـ Liebe/Lieber …",
});
checks.push({
ok: /(grüße|grüßen|gruß|bis bald|tschüss)/i.test(text),
de: "Grußformel am Ende",
ar: task.aufgabe === 3 ? "اختم بـ Mit freundlichen Grüßen" : "اختم بـ Liebe Grüße",
});
}
if (task.aufgabe === 3) {
checks.push({
ok: /\b(Sie|Ihnen|Ihr|Ihre)\b/.test(text) && !/\b(du|dich|dir|dein|deine)\b/i.test(text),
de: "Formell: „Sie“ (groß) statt „du“",
ar: "في الرسالة الرسمية استخدم Sie وليس du",
});
}
if (task.aufgabe === 1) {
checks.push({
ok: /\b(du|dich|dir|dein|deine|deinen|euch|ihr)\b/i.test(text),
de: "Informell: „du“ an den Freund / die Freundin",
ar: "في الرسالة الشخصية استخدم du",
});
}
return checks;
}
interface AiResult {
points: number;
summaryDe: string;
summaryAr: string;
corrected: string;
mistakes: { wrong: string; right: string; explainAr: string }[];
}
function Editor({ task, onBack }: { task: SchreibTask; onBack: () => void }) {
const draftKey = `b1meister:draft:${task.id}`;
const [text, setText] = useState("");
const [ticked, setTicked] = useState<boolean[]>(task.points.map(() => false));
const [checks, setChecks] = useState<Check[] | null>(null);
const [showModel, setShowModel] = useState(false);
const [seconds, setSeconds] = useState(0);
const [aiEnabled, setAiEnabled] = useState(false);
const [ai, setAi] = useState<AiResult | null>(null);
const [aiLoading, setAiLoading] = useState(false);
const [aiError, setAiError] = useState("");
const awarded = useRef(false);
const ref = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
try {
setText(localStorage.getItem(draftKey) ?? "");
} catch {
/* ignorieren */
}
fetch("/api/coach")
.then((r) => r.json())
.then((d: { enabled: boolean }) => setAiEnabled(d.enabled))
.catch(() => setAiEnabled(false));
const id = setInterval(() => setSeconds((s) => s + 1), 1000);
return () => clearInterval(id);
}, [draftKey]);
const update = (v: string) => {
setText(v);
try {
localStorage.setItem(draftKey, v);
} catch {
/* ignorieren */
}
};
const insert = (s: string) => {
const el = ref.current;
if (!el) return update(text + s);
const start = el.selectionStart ?? text.length;
const end = el.selectionEnd ?? text.length;
const v = text.slice(0, start) + s + " " + text.slice(end);
update(v);
setTimeout(() => {
el.focus();
el.selectionStart = el.selectionEnd = start + s.length + 1;
}, 0);
};
const words = text.trim().split(/\s+/).filter(Boolean).length;
const award = (score: number) => {
if (awarded.current) return;
awarded.current = true;
recordResult(task.id, "schreiben", score, 10 + Math.round(score / 10));
if (score >= 80) fireConfetti();
};
const runCheck = () => {
const c = selfCheck(task, text, ticked);
setChecks(c);
award(Math.round((c.filter((x) => x.ok).length / c.length) * 100));
};
const runAi = async () => {
setAiLoading(true);
setAiError("");
try {
const r = await fetch("/api/coach", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ mode: "write", task: task.situation, points: task.points.map((p) => p.de), words: task.words, text }),
});
if (!r.ok) throw new Error(String(r.status));
const d = (await r.json()) as AiResult;
setAi(d);
award(Math.round((d.points / 20) * 100));
} catch {
setAiError("Die KI-Korrektur ist gerade nicht erreichbar. Nutze den Selbstcheck. • التصحيح الآلي غير متاح حالياً.");
} finally {
setAiLoading(false);
}
};
const mm = String(Math.floor(seconds / 60)).padStart(2, "0");
const ss = String(seconds % 60).padStart(2, "0");
return (
<div>
<button className="btn secondary small" style={{ marginTop: 16 }} onClick={onBack}>
← Zurück
</button>
<h1 style={{ fontSize: 24 }}>{task.title}</h1>
<div className="ar muted">{task.titleAr}</div>
<div className="card" style={{ marginTop: 12 }}>
<p style={{ marginTop: 0, fontWeight: 700 }}>{task.situation}</p>
<Ar block>{task.situationAr}</Ar>
<div style={{ marginTop: 10, fontWeight: 800 }}>Schreiben Sie etwas zu diesen Punkten:</div>
{task.points.map((pt, i) => (
<label key={i} className="row" style={{ marginTop: 6, alignItems: "flex-start", cursor: "pointer" }}>
<input
type="checkbox"
checked={ticked[i]}
onChange={(e) => setTicked((t) => t.map((x, j) => (j === i ? e.target.checked : x)))}
style={{ width: 20, height: 20, marginTop: 2 }}
/>
<span style={{ flex: 1 }}>
{pt.de} <Ar><span className="small muted">{pt.ar}</span></Ar>
</span>
</label>
))}
</div>
<h2>Redemittel • عبارات مفيدة</h2>
<p className="small muted" style={{ marginTop: -6 }}>
Antippen zum Einfügen • اضغط للإدراج
</p>
<div className="row">
{schreibRedemittel[task.aufgabe].map((r, i) => (
<button key={i} className="word-chip" title={r.ar} onClick={() => insert(r.de)}>
{r.de}
</button>
))}
</div>
<div className="row" style={{ marginTop: 16 }}>
<span className="pill">{words} Wörter</span>
<span className="pill yellow timer">⏱ {mm}:{ss}</span>
<span className="spacer" />
<span className="small muted">Entwurf wird automatisch gespeichert</span>
</div>
<textarea ref={ref} rows={11} value={text} onChange={(e) => update(e.target.value)} placeholder="Schreib hier deinen Text … • اكتب نصك هنا" style={{ marginTop: 8, lineHeight: 1.6 }} spellCheck={false} />
<div className="bar green" style={{ marginTop: 8 }}>
<div style={{ width: `${Math.min(100, (words / task.words) * 100)}%` }} />
</div>
<div className="grid grid-2" style={{ marginTop: 14 }}>
<button className="btn green" disabled={words < 10} onClick={runCheck}>
✅ Selbstcheck
</button>
<button className="btn purple" disabled={words < 10 || aiLoading || !aiEnabled} onClick={runAi} title={aiEnabled ? "" : "ANTHROPIC_API_KEY in .env.local setzen"}>
{aiLoading ? "⏳ Prüfe …" : "🤖 KI-Korrektur"}
</button>
</div>
{!aiEnabled && <div className="small muted" style={{ marginTop: 6 }}>🤖 KI-Korrektur: in den Einstellungen erklärt, wie man sie aktiviert.</div>}
{aiError && <div className="feedback no">{aiError}</div>}
{checks && (
<div className="card fade-in" style={{ marginTop: 14 }}>
<h3>Selbstcheck • التحقق الذاتي</h3>
{checks.map((c, i) => (
<div key={i} className={`feedback ${c.ok ? "ok" : "no"}`}>
{c.ok ? "✅" : "⚠️"} {c.de}
{!c.ok && (
<div className="ar" style={{ fontWeight: 600 }}>
{c.ar}
</div>
)}
</div>
))}
</div>
)}
{ai && (
<div className="card fade-in" style={{ marginTop: 14, borderColor: "var(--purple)" }}>
<div className="row">
<h3 style={{ margin: 0 }}>🤖 KI-Feedback</h3>
<span className="spacer" />
<span className="pill purple">{ai.points} / 20 Punkte</span>
</div>
<p>{ai.summaryDe}</p>
<div className="ar">{ai.summaryAr}</div>
{ai.mistakes.length > 0 && (
<>
<h3 style={{ marginTop: 12 }}>Fehler • الأخطاء</h3>
{ai.mistakes.map((m, i) => (
<div key={i} style={{ marginBottom: 8 }}>
<span style={{ textDecoration: "line-through", color: "var(--red)" }}>{m.wrong}</span> → <b style={{ color: "var(--green)" }}>{m.right}</b>
<div className="ar small muted">{m.explainAr}</div>
</div>
))}
</>
)}
<details>
<summary>Korrigierter Text</summary>
<div className="reading" style={{ marginTop: 8 }}>
{ai.corrected}
</div>
</details>
</div>
)}
<div style={{ marginTop: 16 }}>
<button className="btn secondary block" onClick={() => setShowModel((s) => !s)}>
📝 {showModel ? "Musterlösung ausblenden" : "Musterlösung zeigen"} • نموذج الإجابة
</button>
{showModel && (
<div className="card fade-in" style={{ marginTop: 10 }}>
<div className="reading">{task.model}</div>
<hr style={{ border: "none", borderTop: "1px solid var(--line)", margin: "14px 0" }} />
<div className="ar">{task.modelAr}</div>
</div>
)}
</div>
</div>
);
}
+617
View File
@@ -0,0 +1,617 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { chatTopics, planTasks, presentationTasks, sprechRedemittel, sprechTeile, type ChatTopic, type PlanTask, type PresentationTask } from "@/data/sprechen";
import Ar from "@/components/Ar";
import { recordResult } from "@/lib/progress";
import { speak, startListening, stopSpeaking, sttSupported } from "@/lib/speech";
import { fireConfetti } from "@/components/AppShell";
import { sfx } from "@/lib/sfx";
type Mode = (typeof sprechTeile)[number]["id"];
interface Session {
id: string;
title: string;
titleAr: string;
context?: string;
intro?: { de: string; ar: string };
prompts: { de: string; ar: string; sample?: string }[];
points?: { de: string; ar: string }[];
slides?: { de: string; ar: string }[];
}
function fromTopic(t: ChatTopic): Session {
return { id: `frei-${t.id}`, title: `${t.emoji} ${t.de}`, titleAr: t.ar, prompts: t.questions.map((q) => ({ de: q.de, ar: q.ar, sample: q.sample })) };
}
function fromPlan(t: PlanTask): Session {
return {
id: `plan-${t.id}`,
title: t.title,
titleAr: t.titleAr,
context: t.situation,
intro: { de: t.situation, ar: t.situationAr },
points: t.points,
prompts: t.partner.map((p) => ({ de: p.de, ar: p.ar })),
};
}
function fromPresentation(t: PresentationTask): Session {
return {
id: `praes-${t.id}`,
title: t.title,
titleAr: t.titleAr,
context: `Der Lernende hat gerade eine Präsentation zum Thema „${t.question}“ gehalten. Stelle Fragen dazu.`,
slides: t.slides,
prompts: [
{ de: "Vielen Dank für Ihre Präsentation! Ich habe noch ein paar Fragen.", ar: "شكراً جزيلاً على عرضك! لديّ بعض الأسئلة." },
...t.followUps,
],
};
}
export default function SprechenPage() {
const [mode, setMode] = useState<Mode>("frei");
const [session, setSession] = useState<Session | null>(null);
const [mixKey, setMixKey] = useState(0);
if (session) return <SessionView key={session.id + mixKey} session={session} onBack={() => setSession(null)} />;
const randomMix = (): Session => {
const qs = chatTopics.flatMap((t) => t.questions);
const pick = [...qs].sort(() => Math.random() - 0.5).slice(0, 6);
return { id: "frei-mix", title: "🎲 Zufallsfragen", titleAr: "أسئلة عشوائية", prompts: pick.map((q) => ({ de: q.de, ar: q.ar, sample: q.sample })) };
};
return (
<div>
<h1>🗣️ Sprechen</h1>
<p className="sub">
Ein echtes Gespräch mit mir – sprich ins Mikrofon oder schreib. <Ar>محادثة حقيقية معي – تحدّث في الميكروفون أو اكتب.</Ar>
</p>
<div className="tabs">
{sprechTeile.map((t) => (
<button key={t.id} className={mode === t.id ? "active" : ""} onClick={() => setMode(t.id)}>
{t.de}
</button>
))}
</div>
<div className="ar muted" style={{ marginBottom: 10 }}>
{sprechTeile.find((t) => t.id === mode)!.ar}
</div>
{mode === "frei" && (
<div className="grid grid-3">
<button
className="tile"
style={{ background: "linear-gradient(135deg, var(--purple), var(--blue))", color: "#fff" }}
onClick={() => {
setMixKey((k) => k + 1);
setSession(randomMix());
}}
>
<div className="emoji">🎲</div>
<div className="t">Zufall</div>
<div className="s" style={{ color: "#fff" }}>
6 gemischte Fragen
</div>
</button>
{chatTopics.map((t) => (
<button key={t.id} className="tile" onClick={() => setSession(fromTopic(t))}>
<div className="emoji">{t.emoji}</div>
<div className="t">{t.de}</div>
<div className="s ar" style={{ textAlign: "left" }}>
{t.ar}
</div>
</button>
))}
</div>
)}
{mode === "planen" && (
<div className="grid">
<div className="card small" style={{ background: "var(--red-soft)", borderColor: "var(--red)" }}>
<b>So läuft Teil 1:</b> Du planst mit deinem Partner etwas (ca. 3 Min.). Mach Vorschläge, reagiere auf seine Ideen, einigt euch!
<Ar block>تخطط مع شريكك لشيء ما (حوالي 3 دقائق). قدّم اقتراحات، تفاعل مع أفكاره، واتفقا معاً!</Ar>
</div>
{planTasks.map((t) => (
<button key={t.id} className="tile" onClick={() => setSession(fromPlan(t))}>
<div className="t" style={{ marginTop: 0 }}>
🤝 {t.title}
</div>
<div className="s ar" style={{ textAlign: "left" }}>
{t.titleAr}
</div>
</button>
))}
</div>
)}
{mode === "praesentation" && (
<div className="grid">
<div className="card small" style={{ background: "var(--purple-soft)", borderColor: "var(--purple)" }}>
<b>So läuft Teil 2 & 3:</b> Du präsentierst ein Thema mit 5 Folien (ca. 3 Min.). Danach stellt der Prüfer Fragen zu deinem Thema.
<Ar block>تقدّم موضوعاً من خمس شرائح (حوالي 3 دقائق). بعد ذلك يطرح الممتحن أسئلة عن موضوعك.</Ar>
</div>
{presentationTasks.map((t) => (
<button key={t.id} className="tile" onClick={() => setSession(fromPresentation(t))}>
<div className="t" style={{ marginTop: 0 }}>
📊 {t.title}
</div>
<div className="s">{t.question}</div>
<div className="s ar" style={{ textAlign: "left" }}>
{t.titleAr}
</div>
</button>
))}
</div>
)}
<h2>Redemittel • عبارات للمحادثة</h2>
{sprechRedemittel.map((g) => (
<details key={g.title} className="card" style={{ marginTop: 8 }}>
<summary>
{g.title} <span className="ar muted small">{g.titleAr}</span>
</summary>
{g.items.map((r, i) => (
<div key={i} className="row" style={{ marginTop: 8 }}>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 700 }}>{r.de}</div>
<div className="ar small muted">{r.ar}</div>
</div>
<button className="btn secondary small" onClick={() => speak(r.de)}>
🔊
</button>
</div>
))}
</details>
))}
</div>
);
}
// ---------------- Gespräch ----------------
interface Msg {
from: "bot" | "me" | "tip";
de: string;
ar?: string;
sample?: string;
}
const reactions = [
{ de: "Interessant!", ar: "مثير للاهتمام!" },
{ de: "Ah, verstehe.", ar: "آه، فهمت." },
{ de: "Das klingt gut!", ar: "يبدو هذا جيداً!" },
{ de: "Okay, danke!", ar: "حسناً، شكراً!" },
{ de: "Wirklich? Spannend!", ar: "حقاً؟ مشوّق!" },
{ de: "Gute Idee!", ar: "فكرة جيدة!" },
{ de: "Ja, das stimmt.", ar: "نعم، هذا صحيح." },
{ de: "Super, sehr schön gesagt!", ar: "رائع، قلتها بشكل جميل جداً!" },
];
const connectorList = ["weil", "dass", "deshalb", "aber", "außerdem", "obwohl", "wenn", "denn", "trotzdem", "damit", "meiner meinung nach", "zum beispiel", "einerseits", "andererseits", "als", "sondern", "ich finde", "ich schlage vor", "wie wäre es"];
const commonVerbs = "habe|hast|hat|haben|bin|bist|ist|sind|kann|kannst|können|muss|musst|müssen|will|willst|wollen|möchte|möchtest|gehe|gehst|geht|arbeite|arbeitet|lerne|lernt|wohne|wohnt|mache|macht|finde|findet|spiele|spielt";
function analyze(text: string) {
const lower = text.toLowerCase();
const words = lower.split(/\s+/).filter(Boolean).length;
const used = connectorList.filter((c) => new RegExp(`(^|[^a-zäöüß])${c}([^a-zäöüß]|$)`).test(lower));
const wordOrder = new RegExp(`\\b(weil|dass|wenn|obwohl|ob)\\s+(ich|du|er|sie|es|wir|ihr|man)\\s+(${commonVerbs})\\b(?![.,!?]?\\s*$)`).exec(lower);
let score = words >= 25 ? 4 : words >= 14 ? 3 : words >= 7 ? 2 : 1;
if (used.length) score++;
if (wordOrder) score--;
score = Math.max(1, Math.min(5, score));
const tips: { de: string; ar: string }[] = [];
if (words < 7) tips.push({ de: "Etwas kurz! Versuch 2–3 Sätze und eine Begründung.", ar: "قصيرة قليلاً! حاول أن تقول 2–3 جمل مع تعليل." });
if (wordOrder)
tips.push({
de: `Achtung Wortstellung: Nach „${wordOrder[1]}“ steht das Verb am Ende (z. B. „${wordOrder[1]} ${wordOrder[2]} … ${wordOrder[3]}“).`,
ar: `انتبه لترتيب الكلمات: بعد «${wordOrder[1]}» يأتي الفعل في آخر الجملة.`,
});
if (used.length) tips.push({ de: `Toll, du benutzt: ${used.slice(0, 3).join(", ")} 👏`, ar: "ممتاز! استخدمت أدوات الربط." });
else if (words >= 7) tips.push({ de: "Tipp: Verbinde deine Sätze mit „weil“, „deshalb“ oder „außerdem“.", ar: "نصيحة: اربط جملك بـ weil أو deshalb أو außerdem." });
return { score, tips, words };
}
interface AiReply {
reply: string;
replyAr: string;
correction: string;
tipAr: string;
score: number;
}
function SessionView({ session, onBack }: { session: Session; onBack: () => void }) {
const [msgs, setMsgs] = useState<Msg[]>([]);
const [step, setStep] = useState(0);
const [input, setInput] = useState("");
const [listening, setListening] = useState(false);
const [typing, setTyping] = useState(false);
const [autoSpeak, setAutoSpeak] = useState(true);
const [scores, setScores] = useState<number[]>([]);
const [done, setDone] = useState(false);
const [aiAvailable, setAiAvailable] = useState(false);
const [useAi, setUseAi] = useState(false);
const [aiChecked, setAiChecked] = useState(false);
const [slide, setSlide] = useState(session.slides ? 0 : -1);
const [slideNotes, setSlideNotes] = useState<string[]>(() => (session.slides ?? []).map(() => ""));
const [elapsed, setElapsed] = useState(0);
const stopRef = useRef<(() => void) | null>(null);
const endRef = useRef<HTMLDivElement>(null);
const started = useRef(false);
const maxAiTurns = 8;
const inPresentation = slide >= 0 && session.slides !== undefined && slide < session.slides.length;
useEffect(() => {
fetch("/api/coach")
.then((r) => r.json())
.then((d: { enabled: boolean }) => {
setAiAvailable(d.enabled);
setUseAi(d.enabled);
})
.catch(() => {})
.finally(() => setAiChecked(true));
const id = setInterval(() => setElapsed((e) => e + 1), 1000);
return () => {
clearInterval(id);
stopSpeaking();
stopRef.current?.();
};
}, []);
useEffect(() => {
endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
}, [msgs, typing]);
const say = (m: Msg) => {
setMsgs((x) => [...x, m]);
if (m.from === "bot" && autoSpeak) speak(m.de, { gender: "m", rate: 0.95 });
};
const botAsk = (i: number) => {
const pr = session.prompts[i];
if (!pr) return;
setTyping(true);
setTimeout(() => {
setTyping(false);
say({ from: "bot", de: pr.de, ar: pr.ar, sample: pr.sample });
}, 700);
};
const aiTurn = async (history: Msg[]) => {
setTyping(true);
try {
const r = await fetch("/api/coach", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
mode: "chat",
topic: session.title.replace(/^\S+\s/, ""),
context: [session.context, session.prompts.map((p) => p.de).join(" / ")].filter(Boolean).join("\nMögliche Fragen: "),
history: history.filter((m) => m.from !== "tip").map((m) => ({ role: m.from === "bot" ? "assistant" : "user", content: m.de })),
}),
});
if (!r.ok) throw new Error();
const d = (await r.json()) as AiReply;
setTyping(false);
if (d.correction || d.tipAr) setMsgs((x) => [...x, { from: "tip", de: d.correction ? `✏️ Besser: ${d.correction}` : "👍 Gut gesagt!", ar: d.tipAr || undefined }]);
if (d.score) setScores((s) => [...s, d.score]);
say({ from: "bot", de: d.reply, ar: d.replyAr });
} catch {
setTyping(false);
setUseAi(false);
setMsgs((x) => [...x, { from: "tip", de: "KI nicht erreichbar – ich mache offline weiter.", ar: "الذكاء الاصطناعي غير متاح – سأكمل بدون إنترنت." }]);
botAsk(step);
}
};
// Start
useEffect(() => {
if (started.current || inPresentation || !aiChecked) return;
started.current = true;
if (session.intro) setMsgs([{ from: "tip", de: `📋 ${session.intro.de}`, ar: session.intro.ar }]);
if (useAi) void aiTurn([]);
else botAsk(0);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [inPresentation, aiChecked]);
const send = (textRaw?: string) => {
const text = (textRaw ?? input).trim();
if (!text || done) return;
stopSpeaking();
setInput("");
const mine: Msg = { from: "me", de: text };
const history = [...msgs, mine];
setMsgs(history);
const userTurns = history.filter((m) => m.from === "me").length;
if (useAi) {
const a = analyze(text);
recordResult(session.id, "sprechen", a.score * 20, 3 + a.score);
if (userTurns >= maxAiTurns) return finish([...scores, a.score]);
void aiTurn(history);
return;
}
const a = analyze(text);
const newScores = [...scores, a.score];
setScores(newScores);
recordResult(session.id, "sprechen", a.score * 20, 3 + a.score);
if (a.score >= 4) sfx.correct();
const prev = session.prompts[step];
setTimeout(() => {
setMsgs((x) => [...x, { from: "tip", de: `${"⭐".repeat(a.score)} ${a.tips.map((t) => t.de).join(" ")}`, ar: a.tips.map((t) => t.ar).join(" "), sample: prev?.sample }]);
const next = step + 1;
if (next >= session.prompts.length) {
finish(newScores);
return;
}
setStep(next);
const r = reactions[Math.floor(Math.random() * reactions.length)];
const pr = session.prompts[next];
setTyping(true);
setTimeout(() => {
setTyping(false);
say({ from: "bot", de: `${r.de} ${pr.de}`, ar: `${r.ar} ${pr.ar}`, sample: pr.sample });
}, 900);
}, 400);
};
const finish = (all: number[]) => {
setDone(true);
const avg = all.length ? all.reduce((a, b) => a + b, 0) / all.length : 0;
const closing = { from: "bot" as const, de: "Vielen Dank, das war ein schönes Gespräch! Du machst große Fortschritte. 👏", ar: "شكراً جزيلاً، كانت محادثة جميلة! أنت تتقدّم كثيراً." };
setTimeout(() => say(closing), 600);
if (avg >= 3.5) {
fireConfetti();
sfx.win();
}
};
const toggleMic = () => {
if (listening) {
stopRef.current?.();
return;
}
stopSpeaking();
const base = input ? input + " " : "";
const stop = startListening(
(t) => setInput(base + t),
() => {
setListening(false);
stopRef.current = null;
},
);
if (stop) {
stopRef.current = stop;
setListening(true);
}
};
const avg = scores.length ? scores.reduce((a, b) => a + b, 0) / scores.length : 0;
const mm = String(Math.floor(elapsed / 60)).padStart(2, "0");
const ss = String(elapsed % 60).padStart(2, "0");
// ---------- Präsentationsmodus (Folien) ----------
if (inPresentation && session.slides) {
const s = session.slides[slide];
return (
<div>
<button className="btn secondary small" style={{ marginTop: 16 }} onClick={onBack}>
← Zurück
</button>
<h1 style={{ fontSize: 24 }}>📊 {session.title}</h1>
<div className="row">
<span className="pill purple">
Folie {slide + 1} / {session.slides.length}
</span>
<span className="pill yellow timer">⏱ {mm}:{ss}</span>
<span className="small muted">Ziel: ca. 3–4 Minuten</span>
</div>
<div className="bar" style={{ marginTop: 10 }}>
<div style={{ width: `${((slide + 1) / session.slides.length) * 100}%` }} />
</div>
<div className="slide" style={{ marginTop: 14, fontSize: 18 }}>
<b>{s.de}</b>
<Ar block>{s.ar}</Ar>
</div>
<p className="small muted">Sprich laut (Mikrofon) oder schreib Stichpunkte. • تحدّث بصوت عالٍ أو اكتب نقاطاً.</p>
<div className="row" style={{ alignItems: "flex-end" }}>
<textarea
rows={5}
value={slideNotes[slide]}
onChange={(e) => setSlideNotes((n) => n.map((x, i) => (i === slide ? e.target.value : x)))}
placeholder="Was sagst du zu dieser Folie? …"
style={{ flex: 1 }}
/>
{sttSupported() && (
<button
className={`mic ${listening ? "on" : ""}`}
onClick={() => {
if (listening) return stopRef.current?.();
const base = slideNotes[slide] ? slideNotes[slide] + " " : "";
const stop = startListening(
(t) => setSlideNotes((n) => n.map((x, i) => (i === slide ? base + t : x))),
() => setListening(false),
);
if (stop) {
stopRef.current = stop;
setListening(true);
}
}}
aria-label="Mikrofon"
>
{listening ? "⏹" : "🎤"}
</button>
)}
</div>
<div className="row" style={{ marginTop: 14 }}>
<button className="btn secondary" disabled={slide === 0} onClick={() => setSlide((x) => x - 1)}>
← Zurück
</button>
<span className="spacer" />
<button
className="btn purple"
onClick={() => {
stopRef.current?.();
const a = analyze(slideNotes[slide] || "");
recordResult(session.id, "sprechen", a.score * 20, 2 + a.score);
setSlide((x) => x + 1);
}}
>
{slide === session.slides.length - 1 ? "Fertig → Fragen 🎤" : "Nächste Folie →"}
</button>
</div>
</div>
);
}
return (
<div>
<button className="btn secondary small" style={{ marginTop: 16 }} onClick={onBack}>
← Zurück
</button>
<div className="row" style={{ marginTop: 8 }}>
<h1 style={{ fontSize: 22, margin: 0 }}>{session.title}</h1>
<span className="spacer" />
<span className="pill yellow timer">⏱ {mm}:{ss}</span>
</div>
<div className="ar muted">{session.titleAr}</div>
<div className="row small" style={{ marginTop: 8 }}>
<label className="row" style={{ gap: 6 }}>
<input type="checkbox" checked={autoSpeak} onChange={(e) => setAutoSpeak(e.target.checked)} style={{ width: 18, height: 18 }} /> 🔊 Vorlesen
</label>
{aiAvailable && (
<label className="row" style={{ gap: 6 }}>
<input type="checkbox" checked={useAi} onChange={(e) => setUseAi(e.target.checked)} style={{ width: 18, height: 18 }} /> 🤖 KI-Partner
</label>
)}
<span className="spacer" />
{scores.length > 0 && <span className="pill green">Ø {avg.toFixed(1)} ⭐</span>}
</div>
{session.points && (
<div className="card small" style={{ marginTop: 10 }}>
<b>Punkte zum Besprechen:</b>{" "}
{session.points.map((pt, i) => (
<span key={i} className="pill" style={{ margin: 2 }}>
{pt.de}
</span>
))}
</div>
)}
<div className="chat" style={{ marginTop: 14 }}>
{msgs.map((m, i) => (
<Bubble key={i} m={m} />
))}
{typing && (
<div className="bubble bot typing" aria-label="schreibt">
<span />
<span />
<span />
</div>
)}
<div ref={endRef} />
</div>
{done ? (
<div className="card fade-in" style={{ marginTop: 16, textAlign: "center" }}>
<div style={{ fontSize: 48 }}>{avg >= 4 ? "🏆" : avg >= 3 ? "🌟" : "💪"}</div>
<div style={{ fontSize: 22, fontWeight: 900 }}>Gespräch beendet!</div>
<div className="muted">
Durchschnitt: {avg.toFixed(1)} / 5 ⭐ • {scores.length} Antworten • {mm}:{ss} Min.
</div>
<div className="ar">{avg >= 3.5 ? "أداء رائع! استمر هكذا." : "جيد! تدرّب أكثر وحاول أن تقول جملاً أطول."}</div>
<div className="row" style={{ justifyContent: "center", marginTop: 12 }}>
<button className="btn" onClick={onBack}>
Neues Thema
</button>
</div>
</div>
) : (
<div className="composer">
<div className="row" style={{ alignItems: "flex-end", flexWrap: "nowrap" }}>
{sttSupported() && (
<button className={`mic ${listening ? "on" : ""}`} onClick={toggleMic} aria-label="Mikrofon">
{listening ? "⏹" : "🎤"}
</button>
)}
<textarea
rows={2}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
send();
}
}}
placeholder={listening ? "Ich höre zu … 👂" : "Antworte auf Deutsch … • أجب بالألمانية"}
style={{ flex: 1 }}
/>
<button className="btn blue" onClick={() => send()} disabled={!input.trim() || typing}>
➤
</button>
</div>
{!sttSupported() && <div className="small muted" style={{ marginTop: 4 }}>🎤 Spracherkennung: in Chrome oder Edge verfügbar.</div>}
</div>
)}
</div>
);
}
function Bubble({ m }: { m: Msg }) {
const [showSample, setShowSample] = useState(false);
if (m.from === "me") return <div className="bubble me">{m.de}</div>;
if (m.from === "tip")
return (
<div className="bubble tip">
<div>{m.de}</div>
{m.ar && (
<Ar block>
<span className="small">{m.ar}</span>
</Ar>
)}
{m.sample && (
<div style={{ marginTop: 6 }}>
{showSample ? (
<div>
<b>💬 Beispielantwort:</b> {m.sample}{" "}
<button className="btn secondary small" onClick={() => speak(m.sample!)}>
🔊
</button>
</div>
) : (
<button className="btn secondary small" onClick={() => setShowSample(true)}>
💬 Beispielantwort zeigen
</button>
)}
</div>
)}
</div>
);
return (
<div className="bubble bot">
<div className="row" style={{ flexWrap: "nowrap", alignItems: "flex-start" }}>
<span style={{ fontSize: 22 }}>👨‍🏫</span>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 700 }}>{m.de}</div>
{m.ar && (
<Ar block>
<span className="small muted">{m.ar}</span>
</Ar>
)}
</div>
<button className="btn secondary small" onClick={() => speak(m.de, { gender: "m" })} aria-label="Nochmal hören">
🔊
</button>
</div>
</div>
);
}
+551
View File
@@ -0,0 +1,551 @@
"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>
);
}