"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("frei"); const [session, setSession] = useState(null); const [mixKey, setMixKey] = useState(0); if (session) return 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 (

🗣️ Sprechen

Ein echtes Gespräch mit mir – sprich ins Mikrofon oder schreib. محادثة حقيقية معي – تحدّث في الميكروفون أو اكتب.

{sprechTeile.map((t) => ( ))}
{sprechTeile.find((t) => t.id === mode)!.ar}
{mode === "frei" && (
{chatTopics.map((t) => ( ))}
)} {mode === "planen" && (
So läuft Teil 1: Du planst mit deinem Partner etwas (ca. 3 Min.). Mach Vorschläge, reagiere auf seine Ideen, einigt euch! تخطط مع شريكك لشيء ما (حوالي 3 دقائق). قدّم اقتراحات، تفاعل مع أفكاره، واتفقا معاً!
{planTasks.map((t) => ( ))}
)} {mode === "praesentation" && (
So läuft Teil 2 & 3: Du präsentierst ein Thema mit 5 Folien (ca. 3 Min.). Danach stellt der Prüfer Fragen zu deinem Thema. تقدّم موضوعاً من خمس شرائح (حوالي 3 دقائق). بعد ذلك يطرح الممتحن أسئلة عن موضوعك.
{presentationTasks.map((t) => ( ))}
)}

Redemittel • عبارات للمحادثة

{sprechRedemittel.map((g) => (
{g.title} {g.titleAr} {g.items.map((r, i) => (
{r.de}
{r.ar}
))}
))}
); } // ---------------- 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([]); 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([]); 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(() => (session.slides ?? []).map(() => "")); const [elapsed, setElapsed] = useState(0); const stopRef = useRef<(() => void) | null>(null); const endRef = useRef(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 (

📊 {session.title}

Folie {slide + 1} / {session.slides.length} ⏱ {mm}:{ss} Ziel: ca. 3–4 Minuten
{s.de} {s.ar}

Sprich laut (Mikrofon) oder schreib Stichpunkte. • تحدّث بصوت عالٍ أو اكتب نقاطاً.