import React, { useEffect, useMemo, useState } from "react"; import { styles } from "../styles/styles"; import { stylesTokens } from "../styles/theme"; export default function NewGameModal({ open, onClose, onCreate, onJoin, // ✅ neu: currentCode = "", gameFinished = false, hasGame = false, }) { // modes: running | choice | create | join const [mode, setMode] = useState("choice"); const [joinCode, setJoinCode] = useState(""); const [err, setErr] = useState(""); const [created, setCreated] = useState(null); // { code } const [toast, setToast] = useState(""); const canJoin = useMemo(() => joinCode.trim().length >= 4, [joinCode]); // ✅ wichtig: beim Öffnen entscheidet der Modus anhand "läuft vs beendet" useEffect(() => { if (!open) return; setErr(""); setToast(""); setJoinCode(""); setCreated(null); // Wenn ein Spiel läuft (und nicht finished) -> nur Code anzeigen if (hasGame && !gameFinished) { setMode("running"); } else { setMode("choice"); } }, [open, hasGame, gameFinished]); if (!open) return null; const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(""), 1100); }; const doCreate = async () => { setErr(""); try { const res = await onCreate(); setCreated({ code: res.code }); setMode("create"); } catch (e) { setErr("❌ Fehler: " + (e?.message || "unknown")); } }; const doJoin = async () => { setErr(""); try { await onJoin(joinCode.trim().toUpperCase()); onClose(); } catch (e) { setErr("❌ Fehler: " + (e?.message || "unknown")); } }; const copyText = async (text, okMsg = "✅ Code kopiert") => { try { await navigator.clipboard.writeText(text || ""); showToast(okMsg); } catch { showToast("❌ Copy nicht möglich"); } }; const codeToShow = (created?.code || "").trim() || (currentCode || "").trim(); return (