// games-extras.jsx, negen kindvriendelijke spelletjes voor 1ste/2de leerjaar.
// Elk spel is mobiel-vriendelijk, kort, met positieve feedback en zonder
// veel leestekst om te starten. Iedere component is via SpelModal te openen.

// ─── Gedeelde helpers, opgeleukte versie met confetti, streak, floaters ──

const SHELL_THEMES = {
  groen:  { bg1: "#D6EFC7", bg2: "#A8DAB0", dot: "rgba(0,0,0,0.07)", accent: "#3FA34D" },
  rood:   { bg1: "#FFE4D6", bg2: "#FFB59A", dot: "rgba(0,0,0,0.07)", accent: "#E63946" },
  oranje: { bg1: "#FFE7CE", bg2: "#FFC58A", dot: "rgba(0,0,0,0.07)", accent: "#FF8C1A" },
  geel:   { bg1: "#FFF2BD", bg2: "#FFD96B", dot: "rgba(0,0,0,0.07)", accent: "#FFD23F" },
  blauw:  { bg1: "#CDEBFA", bg2: "#92CFF0", dot: "rgba(0,0,0,0.07)", accent: "#2D9CDB" },
  paars:  { bg1: "#EAD8FF", bg2: "#C8A6F0", dot: "rgba(0,0,0,0.07)", accent: "#8E44D1" },
  roze:   { bg1: "#FFE0EC", bg2: "#FFB6CC", dot: "rgba(0,0,0,0.07)", accent: "#E64980" },
  krijt:  { bg1: "#1F4030", bg2: "#0E2418", dot: "rgba(255,255,255,0.08)", accent: "#FFD23F" },
};

function gameShellStyle(isMobile, theme = "groen") {
  const t = SHELL_THEMES[theme] || SHELL_THEMES.groen;
  return {
    background: `radial-gradient(circle at 20% 0%, ${t.bg2} 0%, ${t.bg1} 55%)`,
    backgroundImage: [
      `radial-gradient(circle, ${t.dot} 1.4px, transparent 1.6px)`,
      `radial-gradient(circle at 20% 0%, ${t.bg2} 0%, ${t.bg1} 55%)`,
    ].join(", "),
    backgroundSize: "14px 14px, 100% 100%",
    border: isMobile ? "none" : "5px solid #1A1A1A",
    boxShadow: isMobile ? "none" : "8px 8px 0 #1A1A1A",
    padding: isMobile ? "20px 14px 28px" : "32px 36px",
    width: isMobile ? "100%" : "min(680px, 94vw)",
    maxWidth: "100%",
    minHeight: isMobile ? "100vh" : "auto",
    position: "relative",
    overflow: "hidden",
    fontFamily: "'Patrick Hand', cursive",
    color: theme === "krijt" ? "#F0FAE6" : "#1A1A1A",
  };
}

function CloseBtn({ onClose, isMobile }) {
  if (!onClose) return null;
  return (
    <button onClick={onClose} aria-label="Sluiten" style={{
      position: "absolute",
      top: isMobile ? 10 : -18,
      right: isMobile ? 10 : -18,
      width: 44, height: 44, borderRadius: "50%",
      background: "#1A1A1A", color: "#F0FAE6",
      border: "3px solid #F0FAE6", boxShadow: "2px 2px 0 #1A1A1A",
      fontFamily: "'Bangers', sans-serif", fontSize: 22,
      cursor: "pointer", zIndex: 5,
    }}>✕</button>
  );
}

function GameTitle({ icon, kleur, children, sub }) {
  return (
    <div style={{ marginBottom: 16, position: "relative" }}>
      {/* gele burst-shape achter de titel */}
      <svg viewBox="0 0 220 60" preserveAspectRatio="none" style={{
        position: "absolute", left: -10, top: -8,
        width: "min(360px, 84%)", height: 60,
        zIndex: 0, pointerEvents: "none",
      }}>
        <path d="M 4 30 L 14 16 L 24 32 L 36 14 L 50 30 L 64 14 L 78 30 L 92 16 L 106 32 L 122 14 L 138 30 L 152 14 L 166 30 L 180 14 L 196 30 L 212 16 L 218 30 L 212 44 L 196 30 L 180 46 L 166 30 L 152 46 L 138 30 L 122 46 L 106 28 L 92 44 L 78 30 L 64 46 L 50 30 L 36 46 L 24 28 L 14 44 Z"
          fill="#FFD23F" stroke="#1A1A1A" strokeWidth="2.2" strokeLinejoin="round" />
      </svg>
      <div style={{
        fontFamily: "'Bangers', sans-serif", fontSize: 38,
        color: kleur || "#E63946", letterSpacing: "0.03em",
        WebkitTextStroke: "1.6px #1A1A1A",
        textShadow: "4px 4px 0 #1A1A1A",
        lineHeight: 1, display: "flex", alignItems: "center", gap: 10,
        position: "relative", zIndex: 1,
        animation: "ge-titlePop 0.55s cubic-bezier(.2,1.4,.4,1.1) both",
      }}>
        {icon && <span style={{
          fontSize: 36, WebkitTextStroke: 0, textShadow: "none",
          animation: "ge-iconWiggle 1.6s ease-in-out infinite",
          display: "inline-block",
        }}>{icon}</span>}
        {children}
      </div>
      {sub && <div style={{
        fontSize: 16, color: "#6B5A3D", marginTop: 6,
        fontFamily: "'Patrick Hand', cursive",
        position: "relative", zIndex: 1,
      }}>{sub}</div>}
      <style>{`
        @keyframes ge-titlePop {
          0% { transform: scale(0.6) rotate(-6deg); opacity: 0; }
          60% { transform: scale(1.06) rotate(1deg); opacity: 1; }
          100% { transform: scale(1) rotate(0deg); opacity: 1; }
        }
        @keyframes ge-iconWiggle {
          0%, 100% { transform: rotate(-8deg); }
          50% { transform: rotate(8deg); }
        }
      `}</style>
    </div>
  );
}

function ScoreBadge({ score, total, kleur = "#FFD23F", pulse = false }) {
  return (
    <div style={{
      display: "inline-block", background: kleur,
      border: "3px solid #1A1A1A", boxShadow: "3px 3px 0 #1A1A1A",
      padding: "6px 14px", fontFamily: "'Bangers', sans-serif",
      fontSize: 20, letterSpacing: "0.04em",
      transition: "transform 0.2s",
      transform: pulse ? "scale(1.1) rotate(-2deg)" : "scale(1)",
    }}>⚡ {score}{total != null ? ` / ${total}` : ""}</div>
  );
}

function StreakBadge({ streak }) {
  if (streak < 2) return null;
  return (
    <div key={streak} style={{
      display: "inline-block", background: "#FF4F2A", color: "#FFF",
      border: "3px solid #1A1A1A", boxShadow: "3px 3px 0 #1A1A1A",
      padding: "6px 12px", fontFamily: "'Bangers', sans-serif",
      fontSize: 18, letterSpacing: "0.04em", marginLeft: 8,
      animation: "ge-streakPop 0.5s ease-out both",
    }}>🔥 {streak}× COMBO!
      <style>{`
        @keyframes ge-streakPop {
          0% { transform: scale(0.6) rotate(-15deg); }
          60% { transform: scale(1.2) rotate(6deg); }
          100% { transform: scale(1) rotate(0deg); }
        }
      `}</style>
    </div>
  );
}

function BigButton({ onClick, color = "#FFD23F", children, disabled, style = {} }) {
  return (
    <button onClick={onClick} disabled={disabled} style={{
      background: `linear-gradient(180deg, ${tint(color, 14)} 0%, ${color} 60%, ${tint(color, -14)} 100%)`,
      border: "4px solid #1A1A1A",
      boxShadow: "4px 4px 0 #1A1A1A",
      fontFamily: "'Bangers', sans-serif",
      fontSize: 28, letterSpacing: "0.04em",
      padding: "14px 22px", cursor: disabled ? "default" : "pointer",
      color: "#1A1A1A", minHeight: 56, minWidth: 56,
      opacity: disabled ? 0.55 : 1,
      position: "relative",
      transition: "transform 0.12s, box-shadow 0.12s",
      ...style,
    }}
    onMouseDown={e => !disabled && (e.currentTarget.style.transform = "translate(3px,3px) rotate(-1deg)", e.currentTarget.style.boxShadow = "1px 1px 0 #1A1A1A")}
    onMouseUp={e => !disabled && (e.currentTarget.style.transform = "", e.currentTarget.style.boxShadow = "4px 4px 0 #1A1A1A")}
    onMouseLeave={e => !disabled && (e.currentTarget.style.transform = "", e.currentTarget.style.boxShadow = "4px 4px 0 #1A1A1A")}>
      {children}
    </button>
  );
}

function tint(hex, amt) {
  // licht-/donkermaken van een hex-kleur, simpel
  if (!hex || hex[0] !== "#" || hex.length !== 7) return hex;
  const r = Math.max(0, Math.min(255, parseInt(hex.slice(1, 3), 16) + amt));
  const g = Math.max(0, Math.min(255, parseInt(hex.slice(3, 5), 16) + amt));
  const b = Math.max(0, Math.min(255, parseInt(hex.slice(5, 7), 16) + amt));
  return `#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`;
}

// Confetti, kort en speels, gestart via prop `trigger`. Renders 36 stukjes
// die naar beneden vallen en draaien. Verdwijnen vanzelf na ongeveer 2.5s.
function Confetti({ trigger }) {
  const [bursts, setBursts] = React.useState([]);
  React.useEffect(() => {
    if (!trigger) return;
    const id = Date.now() + Math.random();
    const colors = ["#E63946", "#FFD23F", "#3FA34D", "#2D9CDB", "#FF8C1A", "#8E44D1", "#FF80AF"];
    const pieces = Array.from({ length: 38 }).map((_, i) => ({
      id: id + "_" + i,
      left: Math.random() * 100,
      delay: Math.random() * 0.3,
      dur: 1.4 + Math.random() * 1.2,
      color: colors[i % colors.length],
      rot: Math.random() * 360,
      shape: i % 3,
    }));
    setBursts(b => [...b, { id, pieces }]);
    const t = setTimeout(() => {
      setBursts(b => b.filter(x => x.id !== id));
    }, 3000);
    return () => clearTimeout(t);
  }, [trigger]);
  return (
    <div style={{
      position: "absolute", inset: 0,
      pointerEvents: "none", overflow: "hidden", zIndex: 6,
    }}>
      {bursts.map(burst => burst.pieces.map(p => (
        <div key={p.id} style={{
          position: "absolute",
          left: p.left + "%", top: -20,
          width: p.shape === 2 ? 14 : 10,
          height: p.shape === 1 ? 6 : 14,
          background: p.color,
          border: "1.5px solid #1A1A1A",
          borderRadius: p.shape === 2 ? "50%" : "2px",
          animation: `ge-confettiFall ${p.dur}s linear ${p.delay}s forwards`,
          transform: `rotate(${p.rot}deg)`,
        }} />
      )))}
      <style>{`
        @keyframes ge-confettiFall {
          0% { transform: translateY(0) rotate(0deg); opacity: 1; }
          100% { transform: translateY(120vh) rotate(720deg); opacity: 0.4; }
        }
      `}</style>
    </div>
  );
}

// Drijvende score-tekst die opwaarts vervaagt. Setter wordt teruggegeven.
function useFloaters() {
  const [list, setList] = React.useState([]);
  const idRef = React.useRef(0);
  function pop(text, opts = {}) {
    const id = ++idRef.current;
    setList(arr => [...arr, {
      id, text,
      x: opts.x != null ? opts.x : 50,
      y: opts.y != null ? opts.y : 50,
      color: opts.color || "#FFD23F",
      drift: (Math.random() - 0.5) * 12,
    }]);
    setTimeout(() => setList(arr => arr.filter(f => f.id !== id)), 1200);
  }
  const node = (
    <div style={{
      position: "absolute", inset: 0,
      pointerEvents: "none", overflow: "visible", zIndex: 4,
    }}>
      {list.map(f => (
        <div key={f.id} style={{
          position: "absolute",
          left: f.x + "%", top: f.y + "%",
          transform: "translate(-50%, -50%)",
          fontFamily: "'Bangers', sans-serif",
          fontSize: 30, letterSpacing: "0.04em",
          color: f.color,
          WebkitTextStroke: "1.5px #1A1A1A",
          textShadow: "2px 2px 0 #1A1A1A",
          animation: `ge-floatUp 1.1s ease-out forwards`,
          ["--ge-drift"]: f.drift + "px",
        }}>{f.text}</div>
      ))}
      <style>{`
        @keyframes ge-floatUp {
          0% { transform: translate(-50%, -50%) scale(0.6); opacity: 0; }
          25% { transform: translate(calc(-50% + var(--ge-drift)), -75%) scale(1.15); opacity: 1; }
          100% { transform: translate(calc(-50% + var(--ge-drift)), -160%) scale(1); opacity: 0; }
        }
      `}</style>
    </div>
  );
  return { pop, node };
}

// Reactiekop, peper-emoji die kort animeert bij goed/fout antwoord.
function ReactionFace({ mood, key: k }) {
  if (!mood) return null;
  const emoji = mood === "good" ? "😆" : mood === "wow" ? "🤩" : mood === "sad" ? "😅" : "🌶️";
  return (
    <div key={k} style={{
      display: "inline-block", fontSize: 38, lineHeight: 1,
      animation: "ge-reactionPop 0.7s ease-out both",
    }}>{emoji}
      <style>{`
        @keyframes ge-reactionPop {
          0% { transform: scale(0.4) rotate(-20deg); opacity: 0; }
          60% { transform: scale(1.3) rotate(8deg); opacity: 1; }
          100% { transform: scale(1) rotate(0deg); opacity: 1; }
        }
      `}</style>
    </div>
  );
}

// Hoek-stickers, rendert in achtergrond van de shell voor extra fleur.
function ShellDecor({ theme = "groen" }) {
  const t = SHELL_THEMES[theme] || SHELL_THEMES.groen;
  return (
    <div aria-hidden="true" style={{
      position: "absolute", inset: 0, pointerEvents: "none",
      overflow: "hidden", zIndex: 0,
    }}>
      {/* schuine streep linksboven */}
      <div style={{
        position: "absolute", top: -80, left: -120,
        width: 320, height: 60,
        background: t.accent, opacity: 0.18,
        transform: "rotate(-18deg)",
      }} />
      {/* sticker rechtsboven */}
      <div style={{
        position: "absolute", top: 14, right: 60,
        fontSize: 32, opacity: 0.4, transform: "rotate(18deg)",
      }}>⭐</div>
      {/* sticker rechtsonder */}
      <div style={{
        position: "absolute", bottom: 14, right: 16,
        fontSize: 26, opacity: 0.35, transform: "rotate(-12deg)",
      }}>🌶️</div>
      {/* sticker linksonder */}
      <div style={{
        position: "absolute", bottom: 24, left: 14,
        fontSize: 22, opacity: 0.3, transform: "rotate(8deg)",
      }}>✨</div>
    </div>
  );
}

function GameDoneScreen({ score, total, onReplay, onClose, message, perfectMessage, onChangeDifficulty }) {
  const perfect = total != null && score === total;
  return (
    <div style={{
      textAlign: "center", padding: "24px 14px",
      background: "#FFF8EC", border: "4px solid #1A1A1A",
      boxShadow: "5px 5px 0 #1A1A1A", marginTop: 16,
      position: "relative", overflow: "hidden",
    }}>
      <Confetti trigger={true} />
      <div style={{ fontSize: 64, lineHeight: 1, marginBottom: 6, position: "relative", zIndex: 1,
        animation: "ge-trophy 0.7s cubic-bezier(.2,1.4,.4,1.1) both",
      }}>{perfect ? "🏆" : "🎉"}</div>
      <div style={{
        fontFamily: "'Bangers', sans-serif", fontSize: 34,
        color: "#E63946", WebkitTextStroke: "1.4px #1A1A1A",
        textShadow: "4px 4px 0 #1A1A1A", letterSpacing: "0.04em",
        lineHeight: 1, marginBottom: 10, position: "relative", zIndex: 1,
      }}>
        {perfect ? (perfectMessage || "PERFECT!") : "GOED GEDAAN!"}
      </div>
      <div style={{ fontSize: 20, marginBottom: 16, position: "relative", zIndex: 1 }}>
        {message || `Je had ${score}${total != null ? ` van de ${total}` : ""} goed!`}
      </div>
      <div style={{ display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap", position: "relative", zIndex: 1 }}>
        <BigButton onClick={onReplay} color="#3FA34D" style={{ color: "#FFF" }}>↻ NOG EENS</BigButton>
        {onChangeDifficulty && <BigButton onClick={onChangeDifficulty} color="#FFD23F">🌶️ PIT VERANDEREN</BigButton>}
        {onClose && <BigButton onClick={onClose} color="#FFF8EC">SLUITEN</BigButton>}
      </div>
      <style>{`
        @keyframes ge-trophy {
          0% { transform: scale(0.4) rotate(-20deg); }
          60% { transform: scale(1.25) rotate(8deg); }
          100% { transform: scale(1) rotate(0deg); }
        }
      `}</style>
    </div>
  );
}

// QuestionCard, gedeelde omkadering voor de vraag in elk spel met een
// schud-animatie bij fout antwoord en een kleine glow bij goed.
function QuestionCard({ children, status, theme = "paper" }) {
  const bg = theme === "chalk" ? "#1F4030" : "#F0FAE6";
  const fg = theme === "chalk" ? "#FFF8EC" : "#1A1A1A";
  return (
    <div style={{
      background: bg,
      border: "4px solid #1A1A1A",
      boxShadow: status === "good"
        ? "0 0 0 6px rgba(91,184,91,0.6), 4px 4px 0 #1A1A1A"
        : status === "bad"
        ? "0 0 0 6px rgba(230,57,70,0.6), 4px 4px 0 #1A1A1A"
        : "4px 4px 0 #1A1A1A",
      padding: "26px 16px", textAlign: "center",
      margin: "16px 0", color: fg,
      position: "relative",
      animation: status === "bad" ? "ge-shake 0.4s ease" :
                 status === "good" ? "ge-pulse 0.5s ease" : "none",
      transition: "box-shadow 0.2s",
    }}>
      {children}
      <style>{`
        @keyframes ge-shake {
          0%, 100% { transform: translateX(0); }
          15% { transform: translateX(-8px) rotate(-1deg); }
          30% { transform: translateX(8px) rotate(1deg); }
          45% { transform: translateX(-6px) rotate(-0.5deg); }
          60% { transform: translateX(6px) rotate(0.5deg); }
          75% { transform: translateX(-3px); }
        }
        @keyframes ge-pulse {
          0% { transform: scale(1); }
          50% { transform: scale(1.04); }
          100% { transform: scale(1); }
        }
      `}</style>
    </div>
  );
}

// ─── Moeilijkheidskiezer ──────────────────────────────────────────────
// Gedeelde helpers voor alle educatieve spelletjes. Toont een keuzescherm
// (mild, pittig, vlammend) en onthoudt de keuze in localStorage per spel.

const DIFFICULTY_LEVELS = [
  { id: "mild",     label: "MILD",     icon: "🌶️",       sub: "Voor beginners",  color: "#5BB85B" },
  { id: "pittig",   label: "PITTIG",   icon: "🌶️🌶️",     sub: "Standaard",       color: "#FF8C1A" },
  { id: "vlammend", label: "VLAMMEND", icon: "🌶️🌶️🌶️",   sub: "Voor de straffe", color: "#E63946" },
];

function useDifficulty(gameId, defaultLevel = "pittig") {
  const key = `hp_diff_${gameId}`;
  const [level, setLevel] = React.useState(() => {
    try {
      const saved = window.localStorage.getItem(key);
      if (saved && DIFFICULTY_LEVELS.some(d => d.id === saved)) return saved;
    } catch (e) {}
    return defaultLevel;
  });
  const [chosen, setChosen] = React.useState(false);
  function choose(id) {
    setLevel(id);
    setChosen(true);
    try { window.localStorage.setItem(key, id); } catch (e) {}
  }
  function reopen() { setChosen(false); }
  return { level, chosen, choose, reopen };
}

function DifficultyPicker({ onChoose, currentLevel, sub = "Hoe pittig wil je het?" }) {
  return (
    <div style={{
      background: "#FFF8EC", border: "4px solid #1A1A1A",
      boxShadow: "5px 5px 0 #1A1A1A", padding: "18px 14px",
      margin: "16px 0", textAlign: "center",
      position: "relative", zIndex: 1,
    }}>
      <div style={{
        fontFamily: "'Bangers', sans-serif", fontSize: 28,
        color: "#E63946", letterSpacing: "0.04em",
        WebkitTextStroke: "1.2px #1A1A1A", textShadow: "3px 3px 0 #1A1A1A",
        marginBottom: 4,
      }}>KIES JE PIT</div>
      <div style={{ fontSize: 16, color: "#6B5A3D", marginBottom: 14 }}>{sub}</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {DIFFICULTY_LEVELS.map(d => (
          <button key={d.id} onClick={() => onChoose(d.id)}
            style={{
              background: `linear-gradient(180deg, ${tint(d.color, 14)} 0%, ${d.color} 60%, ${tint(d.color, -14)} 100%)`,
              border: currentLevel === d.id ? "5px solid #1A1A1A" : "4px solid #1A1A1A",
              boxShadow: currentLevel === d.id ? "2px 2px 0 #1A1A1A" : "4px 4px 0 #1A1A1A",
              padding: "12px 16px", cursor: "pointer",
              display: "flex", alignItems: "center", justifyContent: "flex-start",
              gap: 12, fontFamily: "'Bangers', sans-serif",
              fontSize: 24, letterSpacing: "0.04em",
              color: "#FFF", WebkitTextStroke: "0.6px #1A1A1A",
              textShadow: "2px 2px 0 #1A1A1A",
              transition: "transform 0.1s, box-shadow 0.1s",
            }}>
            <span style={{ WebkitTextStroke: 0, textShadow: "none", fontSize: 22, lineHeight: 1 }}>{d.icon}</span>
            <span style={{ flex: 1, textAlign: "left" }}>{d.label}</span>
            <span style={{
              fontFamily: "'Patrick Hand', cursive", fontSize: 14,
              WebkitTextStroke: 0, textShadow: "none",
              background: "rgba(255,255,255,0.92)", color: "#1A1A1A",
              padding: "2px 10px", border: "2px solid #1A1A1A",
              fontWeight: "normal", whiteSpace: "nowrap",
            }}>{d.sub}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function DifficultyBadge({ level }) {
  const d = DIFFICULTY_LEVELS.find(x => x.id === level) || DIFFICULTY_LEVELS[1];
  return (
    <span style={{
      display: "inline-block",
      background: d.color, color: "#FFF",
      border: "3px solid #1A1A1A", boxShadow: "3px 3px 0 #1A1A1A",
      padding: "6px 12px",
      fontFamily: "'Bangers', sans-serif", fontSize: 16,
      letterSpacing: "0.04em",
      WebkitTextStroke: "0.4px #1A1A1A",
    }}>
      <span style={{ WebkitTextStroke: 0 }}>{d.icon}</span> {d.label}
    </span>
  );
}

// ─── 1. Tafels van Peper ─────────────────────────────────────────────

const TAFELS_DIFF = {
  mild:     { tafelMax: 2,  factorMax: 5  },
  pittig:   { tafelMax: 5,  factorMax: 10 },
  vlammend: { tafelMax: 10, factorMax: 10 },
};

function TafelsSpel({ onClose }) {
  const isMobile = useIsMobile();
  const diff = useDifficulty("tafels-peper", "pittig");
  const TOTAL = 10;
  const [score, setScore] = React.useState(0);
  const [round, setRound] = React.useState(0);
  const [q, setQ] = React.useState(null);
  const [feedback, setFeedback] = React.useState(null);
  const [done, setDone] = React.useState(false);

  const newQ = React.useCallback(() => {
    const cfg = TAFELS_DIFF[diff.level];
    const tafel = Math.floor(Math.random() * cfg.tafelMax) + 1;
    const factor = Math.floor(Math.random() * cfg.factorMax) + 1;
    const correct = tafel * factor;
    const opts = new Set([correct]);
    while (opts.size < 4) {
      const range = Math.max(5, Math.floor(correct / 2));
      const w = correct + (Math.floor(Math.random() * (range * 2 + 1)) - range);
      if (w !== correct && w > 0) opts.add(w);
    }
    setQ({ tafel, factor, correct, opts: Array.from(opts).sort(() => Math.random() - 0.5) });
    setFeedback(null);
  }, [diff.level]);

  React.useEffect(newQ, [newQ]);

  function pick(v) {
    if (feedback) return;
    const correct = v === q.correct;
    setFeedback({ correct, choice: v });
    if (correct) setScore(s => s + 1);
    setTimeout(() => {
      const next = round + 1;
      if (next >= TOTAL) setDone(true);
      else { setRound(next); newQ(); }
    }, 1300);
  }

  function reset() { setScore(0); setRound(0); setDone(false); newQ(); }

  if (!diff.chosen) {
    return (
      <div style={gameShellStyle(isMobile)}>
        <CloseBtn onClose={onClose} isMobile={isMobile} />
        <GameTitle icon="✖" kleur="#E63946" sub="Hoe pittig wil je de tafels?">
          TAFELS VAN PEPER
        </GameTitle>
        <DifficultyPicker
          onChoose={(id) => { diff.choose(id); setScore(0); setRound(0); setDone(false); }}
          currentLevel={diff.level}
          sub="Mild = tafels van 1 en 2. Vlammend = tot tafel 10."
        />
      </div>
    );
  }

  if (!q) return null;
  return (
    <div style={gameShellStyle(isMobile)}>
      <CloseBtn onClose={onClose} isMobile={isMobile} />
      <GameTitle icon="✖" kleur="#E63946" sub={`Vraag ${Math.min(round + 1, TOTAL)} van ${TOTAL}`}>
        TAFELS VAN PEPER
      </GameTitle>
      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
        <ScoreBadge score={score} total={TOTAL} />
        <DifficultyBadge level={diff.level} />
      </div>

      {done ? (
        <GameDoneScreen score={score} total={TOTAL} onReplay={reset} onClose={onClose}
          onChangeDifficulty={() => { diff.reopen(); }} />
      ) : (
        <>
          <div style={{
            background: "#F0FAE6", border: "4px solid #1A1A1A",
            boxShadow: "4px 4px 0 #1A1A1A",
            padding: "30px 16px", textAlign: "center",
            margin: "16px 0",
          }}>
            <div style={{
              fontFamily: '"Trebuchet MS", Verdana, Tahoma, sans-serif',
              fontWeight: 900,
              fontSize: isMobile ? 56 : 78,
              color: "#1A1A1A", lineHeight: 1, letterSpacing: "0.06em",
              fontVariantNumeric: "tabular-nums",
            }}>
              {q.tafel} × {q.factor} = <span style={{ color: "#E63946" }}>?</span>
            </div>
          </div>
          <div style={{
            display: "grid", gridTemplateColumns: "repeat(2, 1fr)",
            gap: 10,
          }}>
            {q.opts.map(o => {
              const isCorrect = feedback && o === q.correct;
              const isUserWrong = feedback && feedback.choice === o && !feedback.correct;
              return (
                <BigButton key={o} onClick={() => pick(o)}
                  color={isCorrect ? "#5BB85B" : isUserWrong ? "#E63946" : "#FFD23F"}
                  style={{
                    fontFamily: '"Trebuchet MS", Verdana, Tahoma, sans-serif',
                    fontWeight: 900,
                    fontSize: 32, padding: "16px",
                    fontVariantNumeric: "tabular-nums",
                    color: (isCorrect || isUserWrong) ? "#FFF" : "#1A1A1A",
                    border: isUserWrong ? "5px solid #1A1A1A" : "4px solid #1A1A1A",
                  }}>
                  {o}
                </BigButton>
              );
            })}
          </div>
          {feedback && feedback.correct && (
            <div style={{ marginTop: 12, fontFamily: '"Trebuchet MS", Verdana, Tahoma, sans-serif', fontWeight: 900, fontSize: 24, color: "#3FA34D", fontVariantNumeric: "tabular-nums" }}>🎉 JUIST! {q.tafel} × {q.factor} = {q.correct}</div>
          )}
          {feedback && !feedback.correct && (
            <div style={{ marginTop: 12, fontFamily: '"Trebuchet MS", Verdana, Tahoma, sans-serif', fontWeight: 900, fontSize: 22, color: "#B23A2E", fontVariantNumeric: "tabular-nums" }}>OEPS! Jij koos {feedback.choice}, het was {q.correct}</div>
          )}
        </>
      )}
    </div>
  );
}

// ─── 2. Tel de Pepers ─────────────────────────────────────────────────

const TEL_DIFF = {
  mild:     { min: 1,  max: 8,  optRange: 3 },
  pittig:   { min: 2,  max: 15, optRange: 3 },
  vlammend: { min: 8,  max: 25, optRange: 5 },
};

function TelPepers({ onClose }) {
  const isMobile = useIsMobile();
  const diff = useDifficulty("tel-pepers", "pittig");
  const TOTAL = 10;
  const [score, setScore] = React.useState(0);
  const [round, setRound] = React.useState(0);
  const [q, setQ] = React.useState(null);
  const [feedback, setFeedback] = React.useState(null);
  const [done, setDone] = React.useState(false);

  const newQ = React.useCallback(() => {
    const cfg = TEL_DIFF[diff.level];
    const n = Math.floor(Math.random() * (cfg.max - cfg.min + 1)) + cfg.min;
    const opts = new Set([n]);
    while (opts.size < 4) {
      const w = n + (Math.floor(Math.random() * (cfg.optRange * 2 + 1)) - cfg.optRange);
      if (w > 0 && w <= cfg.max + 5) opts.add(w);
    }
    setQ({ n, opts: Array.from(opts).sort(() => Math.random() - 0.5) });
    setFeedback(null);
  }, [diff.level]);

  React.useEffect(newQ, [newQ]);

  function pick(v) {
    if (feedback) return;
    const correct = v === q.n;
    setFeedback({ correct, choice: v });
    if (correct) setScore(s => s + 1);
    setTimeout(() => {
      const next = round + 1;
      if (next >= TOTAL) setDone(true);
      else { setRound(next); newQ(); }
    }, 1300);
  }

  function reset() { setScore(0); setRound(0); setDone(false); newQ(); }

  if (!diff.chosen) {
    return (
      <div style={gameShellStyle(isMobile)}>
        <CloseBtn onClose={onClose} isMobile={isMobile} />
        <GameTitle icon="🌶️" kleur="#FF8C1A" sub="Hoeveel pepers wil je tellen?">
          TEL DE PEPERS
        </GameTitle>
        <DifficultyPicker
          onChoose={(id) => { diff.choose(id); setScore(0); setRound(0); setDone(false); }}
          currentLevel={diff.level}
          sub="Mild = 1 tot 8 pepers. Vlammend = tot 25 pepers."
        />
      </div>
    );
  }

  if (!q) return null;
  const pepperSize = q.n > 18 ? 26 : q.n > 12 ? 32 : 38;
  return (
    <div style={gameShellStyle(isMobile)}>
      <CloseBtn onClose={onClose} isMobile={isMobile} />
      <GameTitle icon="🌶️" kleur="#FF8C1A" sub={`Ronde ${Math.min(round + 1, TOTAL)} van ${TOTAL}`}>
        TEL DE PEPERS
      </GameTitle>
      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
        <ScoreBadge score={score} total={TOTAL} />
        <DifficultyBadge level={diff.level} />
      </div>

      {done ? (
        <GameDoneScreen score={score} total={TOTAL} onReplay={reset} onClose={onClose}
          onChangeDifficulty={() => { diff.reopen(); }} />
      ) : (
        <>
          <div style={{
            background: "#F0FAE6", border: "4px solid #1A1A1A",
            boxShadow: "4px 4px 0 #1A1A1A",
            padding: "20px 14px", margin: "16px 0",
            display: "flex", flexWrap: "wrap", gap: 6,
            justifyContent: "center", minHeight: 140,
          }}>
            {Array.from({ length: q.n }).map((_, i) => (
              <span key={i} style={{ fontSize: pepperSize, lineHeight: 1 }}>🌶️</span>
            ))}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10 }}>
            {q.opts.map(o => {
              const isCorrect = feedback && o === q.n;
              const isUserWrong = feedback && feedback.choice === o && !feedback.correct;
              return (
                <BigButton key={o} onClick={() => pick(o)}
                  color={isCorrect ? "#5BB85B" : isUserWrong ? "#E63946" : "#FFD23F"}
                  style={{
                    fontFamily: '"Trebuchet MS", Verdana, Tahoma, sans-serif',
                    fontWeight: 900,
                    fontSize: 36,
                    fontVariantNumeric: "tabular-nums",
                    color: (isCorrect || isUserWrong) ? "#FFF" : "#1A1A1A",
                    border: isUserWrong ? "5px solid #1A1A1A" : "4px solid #1A1A1A",
                  }}>
                  {o}
                </BigButton>
              );
            })}
          </div>
          {feedback && feedback.correct && (
            <div style={{ marginTop: 12, fontFamily: '"Trebuchet MS", Verdana, Tahoma, sans-serif', fontWeight: 900, fontSize: 24, color: "#3FA34D", fontVariantNumeric: "tabular-nums" }}>🎉 JUIST! Het waren er {q.n}</div>
          )}
          {feedback && !feedback.correct && (
            <div style={{ marginTop: 12, fontFamily: '"Trebuchet MS", Verdana, Tahoma, sans-serif', fontWeight: 900, fontSize: 22, color: "#B23A2E", fontVariantNumeric: "tabular-nums" }}>OEPS! Jij koos {feedback.choice}, het waren er {q.n}</div>
          )}
        </>
      )}
    </div>
  );
}

// ─── 3. Peper Memory ──────────────────────────────────────────────────

const MEMORY_DIFF = {
  mild:     { pairs: 6,  cols: 4 },
  pittig:   { pairs: 10, cols: 5 },
  vlammend: { pairs: 15, cols: 6 },
};
const MEMORY_SYMBOLS = [
  "🌶️", "🧠", "🔥", "⭐", "🦸", "🧥", "🥶", "💥",
  "🍕", "👻", "🍄", "🐝", "🦄", "🌈", "⚡", "🎩", "🚀", "🍩",
];

function PeperMemory({ onClose }) {
  const isMobile = useIsMobile();
  const diff = useDifficulty("peper-memory", "pittig");
  const [cards, setCards] = React.useState([]);
  const [flipped, setFlipped] = React.useState([]);
  const [matched, setMatched] = React.useState(new Set());
  const [moves, setMoves] = React.useState(0);
  const [done, setDone] = React.useState(false);

  const reset = React.useCallback(() => {
    const cfg = MEMORY_DIFF[diff.level];
    const symbols = MEMORY_SYMBOLS.slice(0, cfg.pairs);
    const deck = symbols.flatMap(s => [s, s]).sort(() => Math.random() - 0.5);
    setCards(deck);
    setFlipped([]); setMatched(new Set()); setMoves(0); setDone(false);
  }, [diff.level]);

  React.useEffect(reset, [reset]);

  function flip(i) {
    if (flipped.includes(i) || matched.has(i)) return;
    if (flipped.length === 2) return;
    const next = [...flipped, i];
    setFlipped(next);
    if (next.length === 2) {
      setMoves(m => m + 1);
      const [a, b] = next;
      if (cards[a] === cards[b]) {
        setTimeout(() => {
          setMatched(prev => {
            const s = new Set(prev); s.add(a); s.add(b);
            if (s.size === cards.length) setDone(true);
            return s;
          });
          setFlipped([]);
        }, 500);
      } else {
        setTimeout(() => setFlipped([]), 800);
      }
    }
  }

  if (!diff.chosen) {
    return (
      <div style={gameShellStyle(isMobile)}>
        <CloseBtn onClose={onClose} isMobile={isMobile} />
        <GameTitle icon="🧠" kleur="#8E44D1" sub="Hoeveel paren wil je zoeken?">
          PEPER MEMORY
        </GameTitle>
        <DifficultyPicker
          onChoose={(id) => { diff.choose(id); }}
          currentLevel={diff.level}
          sub="Mild = 6 paren. Pittig = 10 paren. Vlammend = 15 paren."
        />
      </div>
    );
  }

  const cols = MEMORY_DIFF[diff.level].cols;
  return (
    <div style={gameShellStyle(isMobile)}>
      <CloseBtn onClose={onClose} isMobile={isMobile} />
      <GameTitle icon="🧠" kleur="#8E44D1" sub="Vind alle paren">
        PEPER MEMORY
      </GameTitle>
      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
        <ScoreBadge score={moves} kleur="#E1C4FF" />
        <span style={{ fontSize: 16, color: "#6B5A3D" }}>beurten</span>
        <DifficultyBadge level={diff.level} />
      </div>

      {done ? (
        <GameDoneScreen
          score={moves}
          message={(() => {
            const pairs = MEMORY_DIFF[diff.level].pairs;
            const fast = Math.ceil(pairs * 1.5);
            const ok = Math.ceil(pairs * 2.5);
            const verdict = moves <= fast ? "Wow, supersnel!" : moves <= ok ? "Lekker bezig!" : "Goed volgehouden!";
            return `Klaar in ${moves} beurten! ${verdict}`;
          })()}
          onReplay={reset}
          onClose={onClose}
          onChangeDifficulty={() => { diff.reopen(); }}
        />
      ) : (
        <div style={{
          display: "grid",
          gridTemplateColumns: `repeat(${cols}, 1fr)`,
          gap: 8, marginTop: 16,
        }}>
          {cards.map((c, i) => {
            const open = flipped.includes(i) || matched.has(i);
            return (
              <button key={i} onClick={() => flip(i)}
                aria-label={open ? c : "Verborgen kaart"}
                style={{
                  aspectRatio: "1",
                  background: open ? "#FFF8EC" : "#E63946",
                  border: "4px solid #1A1A1A",
                  boxShadow: "3px 3px 0 #1A1A1A",
                  fontSize: isMobile ? 30 : 40,
                  cursor: open ? "default" : "pointer",
                  opacity: matched.has(i) ? 0.55 : 1,
                  transition: "background 0.15s, opacity 0.2s",
                }}>
                {open ? c : ""}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── 4. Welke Letter Mist? ────────────────────────────────────────────

const LETTER_WORDS = {
  mild: [
    ["KAT", 1], ["BAL", 1], ["PET", 1], ["KIP", 1], ["ZON", 1],
    ["BOM", 1], ["KOE", 1], ["AAP", 1], ["AUTO", 1], ["JAS", 1],
  ],
  pittig: [
    ["PEPER", 1], ["VUUR", 2], ["HELD", 0], ["KAT", 1], ["BAL", 1],
    ["PET", 1], ["BOOM", 1], ["MAAN", 1], ["HOND", 0], ["KIP", 1],
  ],
  vlammend: [
    ["KASTEEL", 3], ["VOGELTJE", 4], ["SCHOOL", 2], ["PAARDJE", 3], ["BLOEMEN", 2],
    ["TANDPASTA", 4], ["PINGUIN", 3], ["DRAKEN", 2], ["KAARSEN", 3], ["RIDDER", 1],
  ],
};

function LetterMist({ onClose }) {
  const isMobile = useIsMobile();
  const diff = useDifficulty("letter-mist", "pittig");
  const WORDS = LETTER_WORDS[diff.level];
  const TOTAL = WORDS.length;
  const [order, setOrder] = React.useState([]);
  const [opts, setOpts] = React.useState([]);
  const [round, setRound] = React.useState(0);
  const [score, setScore] = React.useState(0);
  const [feedback, setFeedback] = React.useState(null); // null | { correct, choice }
  const [done, setDone] = React.useState(false);

  function buildOpts(missing) {
    const set = new Set([missing]);
    const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    while (set.size < 4) set.add(alphabet[Math.floor(Math.random() * alphabet.length)]);
    return Array.from(set).sort(() => Math.random() - 0.5);
  }

  const reset = React.useCallback(() => {
    const idxs = WORDS.map((_, i) => i).sort(() => Math.random() - 0.5);
    const [w0, mi0] = WORDS[idxs[0]];
    setOrder(idxs);
    setOpts(buildOpts(w0[mi0]));
    setRound(0); setScore(0); setFeedback(null); setDone(false);
  }, [diff.level]);

  React.useEffect(reset, [reset]);

  if (!diff.chosen) {
    return (
      <div style={gameShellStyle(isMobile)}>
        <CloseBtn onClose={onClose} isMobile={isMobile} />
        <GameTitle icon="🔤" kleur="#FF8C1A" sub="Hoe lange woorden wil je?">
          WELKE LETTER MIST?
        </GameTitle>
        <DifficultyPicker
          onChoose={(id) => { diff.choose(id); }}
          currentLevel={diff.level}
          sub="Mild = korte woordjes (3 letters). Vlammend = lange woorden."
        />
      </div>
    );
  }

  if (!order.length) return null;
  const [word, missingIdx] = WORDS[order[round]];
  const missing = word[missingIdx];

  function pick(letter) {
    if (feedback) return;
    const correct = letter === missing;
    setFeedback({ correct, choice: letter });
    if (correct) setScore(s => s + 1);
    setTimeout(() => {
      const next = round + 1;
      if (next >= TOTAL) setDone(true);
      else {
        const [wn, min] = WORDS[order[next]];
        setOpts(buildOpts(wn[min]));
        setRound(next);
        setFeedback(null);
      }
    }, 1300);
  }

  const wordFontSize = word.length > 6 ? (isMobile ? 32 : 48) : (isMobile ? 44 : 64);
  return (
    <div style={gameShellStyle(isMobile)}>
      <CloseBtn onClose={onClose} isMobile={isMobile} />
      <GameTitle icon="🔤" kleur="#FF8C1A" sub={`Woord ${Math.min(round + 1, TOTAL)} van ${TOTAL}`}>
        WELKE LETTER MIST?
      </GameTitle>
      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
        <ScoreBadge score={score} total={TOTAL} />
        <DifficultyBadge level={diff.level} />
      </div>

      {done ? (
        <GameDoneScreen score={score} total={TOTAL} onReplay={reset} onClose={onClose}
          onChangeDifficulty={() => { diff.reopen(); }} />
      ) : (
        <>
          <div style={{
            background: "#F0FAE6", border: "4px solid #1A1A1A",
            boxShadow: "4px 4px 0 #1A1A1A",
            padding: "26px 12px", textAlign: "center",
            margin: "16px 0",
          }}>
            <div style={{
              fontFamily: "'Bangers', sans-serif",
              fontSize: wordFontSize,
              letterSpacing: word.length > 6 ? "0.10em" : "0.15em", color: "#1A1A1A",
            }}>
              {word.split("").map((l, i) => {
                const isSlot = i === missingIdx;
                const slotBg = !feedback ? "#FFD23F"
                  : feedback.correct ? "#5BB85B" : "#E63946";
                return (
                  <span key={i} style={{
                    display: "inline-block", margin: "0 3px",
                    background: isSlot ? slotBg : "transparent",
                    border: isSlot ? "3px solid #1A1A1A" : "none",
                    padding: isSlot ? "2px 10px" : 0,
                    color: isSlot && feedback ? "#FFF" : "#1A1A1A",
                    minWidth: isSlot ? 40 : "auto",
                  }}>
                    {isSlot ? (feedback ? l : "_") : l}
                  </span>
                );
              })}
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
            {opts.map(l => {
              const isCorrect = feedback && l === missing;
              const isUserWrong = feedback && feedback.choice === l && !feedback.correct;
              return (
                <BigButton key={l} onClick={() => pick(l)}
                  color={isCorrect ? "#5BB85B" : isUserWrong ? "#E63946" : "#FFD23F"}
                  style={{
                    fontSize: 32,
                    color: (isCorrect || isUserWrong) ? "#FFF" : "#1A1A1A",
                    border: isUserWrong ? "5px solid #1A1A1A" : "4px solid #1A1A1A",
                  }}>{l}</BigButton>
              );
            })}
          </div>
          {feedback && feedback.correct && (
            <div style={{ marginTop: 14, fontFamily: "'Bangers', sans-serif", fontSize: 26, color: "#3FA34D", letterSpacing: "0.04em" }}>
              🎉 JUIST! De letter was {missing}.
            </div>
          )}
          {feedback && !feedback.correct && (
            <div style={{ marginTop: 14, fontFamily: "'Bangers', sans-serif", fontSize: 24, color: "#B23A2E", letterSpacing: "0.04em" }}>
              OEPS! Jij koos {feedback.choice}, maar de letter was {missing}.
            </div>
          )}
        </>
      )}
    </div>
  );
}

// ─── 5. Rijm met Peper ────────────────────────────────────────────────

const RIJM_ROUNDS_BASE = [
  { word: "PET",  correct: "NET",  wrong: ["KAT",   "BAL",   "POT"] },
  { word: "KAT",  correct: "MAT",  wrong: ["BOOT",  "HOND",  "KIP"] },
  { word: "BAL",  correct: "VAL",  wrong: ["AUTO",  "BOOM",  "BIL"] },
  { word: "BOOM", correct: "ROOM", wrong: ["VIS",   "PET",   "BIK"] },
  { word: "MAAN", correct: "BAAN", wrong: ["KAT",   "BIL",   "MAAR"] },
  { word: "PEER", correct: "BEER", wrong: ["AUTO",  "HUIS",  "TROL"] },
  { word: "VUUR", correct: "MUUR", wrong: ["KIP",   "BAL",   "VEER"] },
  { word: "MUIS", correct: "HUIS", wrong: ["VIS",   "AAP",   "MOS"] },
];
const RIJM_ROUNDS_HARD = [
  { word: "DEUR",  correct: "KLEUR", wrong: ["BLAD",  "PIANO",  "DOEL"] },
  { word: "PAD",   correct: "BLAD",  wrong: ["BIJL",  "BLAUW",  "BOEK"] },
  { word: "LICHT", correct: "ZICHT", wrong: ["WOLK",  "SCHAAR", "LIED"] },
  { word: "BOEK",  correct: "DOEK",  wrong: ["VOET",  "MAAND",  "BAK"] },
];
const RIJM_DIFF = {
  mild:     { rounds: RIJM_ROUNDS_BASE,                              wrongs: 1 },
  pittig:   { rounds: RIJM_ROUNDS_BASE,                              wrongs: 2 },
  vlammend: { rounds: [...RIJM_ROUNDS_BASE, ...RIJM_ROUNDS_HARD],    wrongs: 3 },
};

function RijmSpel({ onClose }) {
  const isMobile = useIsMobile();
  const diff = useDifficulty("rijm-spel", "pittig");
  const cfg = RIJM_DIFF[diff.level];
  const ROUNDS = cfg.rounds;
  const TOTAL = ROUNDS.length;
  const [order, setOrder] = React.useState([]);
  const [opts, setOpts] = React.useState([]);
  const [round, setRound] = React.useState(0);
  const [score, setScore] = React.useState(0);
  const [feedback, setFeedback] = React.useState(null);
  const [done, setDone] = React.useState(false);

  function buildOpts(r) {
    const wrongs = r.wrong.slice(0, cfg.wrongs);
    return [r.correct, ...wrongs].sort(() => Math.random() - 0.5);
  }

  const reset = React.useCallback(() => {
    const idx = ROUNDS.map((_, i) => i).sort(() => Math.random() - 0.5);
    setOrder(idx);
    setOpts(buildOpts(ROUNDS[idx[0]]));
    setRound(0); setScore(0); setFeedback(null); setDone(false);
  }, [diff.level]);

  React.useEffect(reset, [reset]);

  if (!diff.chosen) {
    return (
      <div style={gameShellStyle(isMobile)}>
        <CloseBtn onClose={onClose} isMobile={isMobile} />
        <GameTitle icon="🎵" kleur="#2D9CDB" sub="Hoeveel keuzes wil je?">
          RIJM MET PEPER
        </GameTitle>
        <DifficultyPicker
          onChoose={(id) => { diff.choose(id); }}
          currentLevel={diff.level}
          sub="Mild = 2 keuzes. Vlammend = 4 keuzes en moeilijke woorden."
        />
      </div>
    );
  }

  if (!order.length) return null;
  const r = ROUNDS[order[round]];

  function pick(v) {
    if (feedback) return;
    const correct = v === r.correct;
    setFeedback({ choice: v, correct });
    if (correct) setScore(s => s + 1);
    setTimeout(() => {
      const next = round + 1;
      if (next >= TOTAL) setDone(true);
      else {
        setOpts(buildOpts(ROUNDS[order[next]]));
        setRound(next);
        setFeedback(null);
      }
    }, 1400);
  }

  return (
    <div style={gameShellStyle(isMobile)}>
      <CloseBtn onClose={onClose} isMobile={isMobile} />
      <GameTitle icon="🎵" kleur="#2D9CDB" sub={`Vraag ${Math.min(round + 1, TOTAL)} van ${TOTAL}`}>
        RIJM MET PEPER
      </GameTitle>
      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
        <ScoreBadge score={score} total={TOTAL} />
        <DifficultyBadge level={diff.level} />
      </div>

      {done ? (
        <GameDoneScreen score={score} total={TOTAL} onReplay={reset} onClose={onClose}
          onChangeDifficulty={() => { diff.reopen(); }} />
      ) : (
        <>
          <div style={{
            background: "#F0FAE6", border: "4px solid #1A1A1A",
            boxShadow: "4px 4px 0 #1A1A1A",
            padding: "20px 12px", textAlign: "center", margin: "16px 0",
          }}>
            <div style={{ fontSize: 18, color: "#6B5A3D", marginBottom: 6 }}>Welk woord rijmt op:</div>
            <div style={{
              fontFamily: "'Bangers', sans-serif",
              fontSize: isMobile ? 42 : 56,
              color: "#E63946",
              WebkitTextStroke: "1.5px #1A1A1A",
              textShadow: "3px 3px 0 #1A1A1A",
              letterSpacing: "0.04em", lineHeight: 1,
            }}>
              {r.word}
            </div>
          </div>
          <div style={{
            display: "grid",
            gridTemplateColumns: isMobile
              ? (opts.length === 2 ? "1fr 1fr" : "1fr")
              : `repeat(${opts.length}, 1fr)`,
            gap: 10,
          }}>
            {opts.map(o => {
              const isCorrect = feedback && o === r.correct;
              const isUserWrong = feedback && feedback.choice === o && !feedback.correct;
              return (
                <BigButton key={o} onClick={() => pick(o)}
                  color={isCorrect ? "#5BB85B" : isUserWrong ? "#E63946" : "#FFD23F"}
                  style={{
                    fontSize: 22,
                    color: (isCorrect || isUserWrong) ? "#FFF" : "#1A1A1A",
                    border: isUserWrong ? "5px solid #1A1A1A" : "4px solid #1A1A1A",
                  }}>
                  {o}
                </BigButton>
              );
            })}
          </div>
          {feedback && feedback.correct && (
            <div style={{ marginTop: 14, fontFamily: "'Bangers', sans-serif", fontSize: 26, color: "#3FA34D", letterSpacing: "0.04em" }}>
              🎉 JUIST! {r.correct} rijmt op {r.word}.
            </div>
          )}
          {feedback && !feedback.correct && (
            <div style={{ marginTop: 14, fontFamily: "'Bangers', sans-serif", fontSize: 22, color: "#B23A2E", letterSpacing: "0.04em" }}>
              OEPS! Jij koos {feedback.choice}, het juiste woord was {r.correct}.
            </div>
          )}
        </>
      )}
    </div>
  );
}

// ─── 6. Pittigheidsmeter Quiz ─────────────────────────────────────────

const PIT_QUIZ_BASE = [
  { v: "Hete Peper draagt een groene pet.", a: true },
  { v: "Hete Peper houdt van ijs en sneeuw.", a: false },
  { v: "De grootste vijand van Hete Peper is een wasknijper.", a: true },
  { v: "Hete Peper kan vuur spuwen.", a: true },
  { v: "Hete Peper woont onder water.", a: false },
  { v: "Oliver is de grootste fan van Hete Peper.", a: true },
  { v: "Hete Peper is bang van het donker.", a: false },
  { v: "Een peper bestaat echt en kan pittig zijn.", a: true },
];
const PIT_QUIZ_HARD = [
  { v: "Een ijsheks kan zelf vuur spuwen.", a: false },
  { v: "Hete Peper wordt sterker als hij een slijmpje opeet.", a: false },
  { v: "Pepperoni City heeft een eigen burgemeester.", a: true },
  { v: "Hete Peper kan zwemmen, al doet hij het niet graag.", a: true },
];
const PIT_QUIZ_DIFF = {
  mild:     PIT_QUIZ_BASE.slice(0, 5),
  pittig:   PIT_QUIZ_BASE,
  vlammend: [...PIT_QUIZ_BASE, ...PIT_QUIZ_HARD],
};

function PitQuiz({ onClose }) {
  const isMobile = useIsMobile();
  const diff = useDifficulty("pit-quiz", "pittig");
  const QUESTIONS = PIT_QUIZ_DIFF[diff.level];
  const TOTAL = QUESTIONS.length;
  const [order, setOrder] = React.useState([]);
  const [round, setRound] = React.useState(0);
  const [score, setScore] = React.useState(0);
  const [feedback, setFeedback] = React.useState(null);
  const [done, setDone] = React.useState(false);

  const reset = React.useCallback(() => {
    const idx = QUESTIONS.map((_, i) => i).sort(() => Math.random() - 0.5);
    setOrder(idx); setRound(0); setScore(0); setFeedback(null); setDone(false);
  }, [diff.level]);

  React.useEffect(reset, [reset]);

  if (!diff.chosen) {
    return (
      <div style={gameShellStyle(isMobile)}>
        <CloseBtn onClose={onClose} isMobile={isMobile} />
        <GameTitle icon="🤔" kleur="#FFD23F" sub="Hoe veel vragen wil je?">
          PITTIGHEIDSMETER
        </GameTitle>
        <DifficultyPicker
          onChoose={(id) => { diff.choose(id); }}
          currentLevel={diff.level}
          sub="Mild = 5 vragen. Vlammend = 12 vragen, ook strikvragen."
        />
      </div>
    );
  }

  if (!order.length) return null;
  const q = QUESTIONS[order[round]];

  function pick(v) {
    if (feedback) return;
    const correct = v === q.a;
    setFeedback({ correct, choice: v });
    if (correct) setScore(s => s + 1);
    setTimeout(() => {
      const next = round + 1;
      if (next >= TOTAL) setDone(true);
      else { setRound(next); setFeedback(null); }
    }, 1400);
  }

  function userPickedThis(val) {
    return feedback && feedback.choice === val;
  }

  return (
    <div style={gameShellStyle(isMobile)}>
      <CloseBtn onClose={onClose} isMobile={isMobile} />
      <GameTitle icon="🤔" kleur="#FFD23F" sub={`Vraag ${Math.min(round + 1, TOTAL)} van ${TOTAL}`}>
        PITTIGHEIDSMETER
      </GameTitle>
      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
        <ScoreBadge score={score} total={TOTAL} />
        <DifficultyBadge level={diff.level} />
      </div>

      {done ? (
        <GameDoneScreen score={score} total={TOTAL} onReplay={reset} onClose={onClose}
          onChangeDifficulty={() => { diff.reopen(); }} />
      ) : (
        <>
          <div style={{
            background: "#F0FAE6", border: "4px solid #1A1A1A",
            boxShadow: "4px 4px 0 #1A1A1A",
            padding: "22px 16px", textAlign: "center",
            margin: "16px 0",
          }}>
            <div style={{ fontSize: 22, lineHeight: 1.3, color: "#1A1A1A" }}>{q.v}</div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <BigButton onClick={() => pick(true)}
              color={feedback ? (q.a === true ? "#5BB85B" : (userPickedThis(true) ? "#E63946" : "#FFD23F")) : "#5BB85B"}
              style={{
                color: feedback ? ((q.a === true || userPickedThis(true)) ? "#FFF" : "#1A1A1A") : "#FFF",
                border: userPickedThis(true) && !feedback.correct ? "5px solid #1A1A1A" : "4px solid #1A1A1A",
              }}>✓ WAAR</BigButton>
            <BigButton onClick={() => pick(false)}
              color={feedback ? (q.a === false ? "#5BB85B" : (userPickedThis(false) ? "#E63946" : "#FFD23F")) : "#E63946"}
              style={{
                color: feedback ? ((q.a === false || userPickedThis(false)) ? "#FFF" : "#1A1A1A") : "#FFF",
                border: userPickedThis(false) && !feedback.correct ? "5px solid #1A1A1A" : "4px solid #1A1A1A",
              }}>✗ NIET WAAR</BigButton>
          </div>
          {feedback && feedback.correct && (
            <div style={{ marginTop: 12, fontFamily: "'Bangers', sans-serif", fontSize: 22, color: "#3FA34D" }}>🎉 JUIST! Het was {q.a ? "waar" : "niet waar"}.</div>
          )}
          {feedback && !feedback.correct && (
            <div style={{ marginTop: 12, fontFamily: "'Bangers', sans-serif", fontSize: 20, color: "#B23A2E" }}>OEPS! Jij koos {feedback.choice ? '"waar"' : '"niet waar"'}, maar het was {q.a ? "waar" : "niet waar"}.</div>
          )}
        </>
      )}
    </div>
  );
}

// ─── 7. Peper Doolhof ─────────────────────────────────────────────────

// 0=open, 1=muur, 2=uitgang
const DOOLHOF_DIFF = {
  mild: [
    [
      [0,0,0,1,0],
      [1,1,0,1,0],
      [0,0,0,1,0],
      [0,1,1,1,0],
      [0,0,0,0,2],
    ],
  ],
  pittig: [
    [
      [0,1,0,0,0],
      [0,1,0,1,0],
      [0,0,0,1,0],
      [1,1,0,1,0],
      [0,0,0,0,2],
    ],
    [
      [0,0,1,0,0,0],
      [1,0,1,0,1,0],
      [1,0,0,0,1,0],
      [0,0,1,1,0,0],
      [0,1,1,0,0,1],
      [0,0,0,0,1,2],
    ],
  ],
  vlammend: [
    [
      [0,1,0,0,0,1,0],
      [0,1,0,1,0,1,0],
      [0,0,0,1,0,0,0],
      [1,1,0,1,1,1,0],
      [0,0,0,0,0,1,0],
      [0,1,1,1,0,1,0],
      [0,0,0,0,0,0,2],
    ],
    [
      [0,0,0,1,0,0,0,0],
      [1,1,0,1,0,1,1,0],
      [0,0,0,1,0,1,0,0],
      [0,1,1,1,0,1,0,1],
      [0,0,0,0,0,0,0,0],
      [1,1,1,1,1,1,1,0],
      [0,0,0,0,0,0,0,0],
      [0,1,1,1,1,1,1,2],
    ],
  ],
};

function Doolhof({ onClose }) {
  const isMobile = useIsMobile();
  const diff = useDifficulty("doolhof", "pittig");
  const LEVELS = DOOLHOF_DIFF[diff.level];
  const [level, setLevel] = React.useState(0);
  const [pos, setPos] = React.useState([0, 0]);
  const [moves, setMoves] = React.useState(0);
  const [done, setDone] = React.useState(false);

  const grid = LEVELS[level];
  const N = grid.length;

  const reset = React.useCallback(() => {
    setPos([0, 0]); setMoves(0); setDone(false);
  }, []);

  function move(dr, dc) {
    if (done) return;
    setPos(([r, c]) => {
      const nr = r + dr, nc = c + dc;
      if (nr < 0 || nr >= N || nc < 0 || nc >= grid[0].length) return [r, c];
      if (grid[nr][nc] === 1) return [r, c];
      setMoves(m => m + 1);
      if (grid[nr][nc] === 2) setTimeout(() => setDone(true), 100);
      return [nr, nc];
    });
  }

  React.useEffect(() => {
    function onKey(e) {
      if (e.key === "ArrowUp") { e.preventDefault(); move(-1, 0); }
      if (e.key === "ArrowDown") { e.preventDefault(); move(1, 0); }
      if (e.key === "ArrowLeft") { e.preventDefault(); move(0, -1); }
      if (e.key === "ArrowRight") { e.preventDefault(); move(0, 1); }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [done, level]);

  function nextLevel() {
    if (level + 1 < LEVELS.length) {
      setLevel(level + 1); reset();
    }
  }

  const cellSize = isMobile
    ? Math.min(50, Math.floor(280 / grid[0].length))
    : Math.min(50, Math.floor(420 / grid[0].length));

  if (!diff.chosen) {
    return (
      <div style={gameShellStyle(isMobile)}>
        <CloseBtn onClose={onClose} isMobile={isMobile} />
        <GameTitle icon="🧩" kleur="#2D9CDB" sub="Hoe groot wil je het doolhof?">
          PEPER DOOLHOF
        </GameTitle>
        <DifficultyPicker
          onChoose={(id) => { diff.choose(id); setLevel(0); setPos([0,0]); setMoves(0); setDone(false); }}
          currentLevel={diff.level}
          sub="Mild = klein doolhof. Vlammend = groot doolhof, twee levels."
        />
      </div>
    );
  }

  return (
    <div style={gameShellStyle(isMobile)}>
      <CloseBtn onClose={onClose} isMobile={isMobile} />
      <GameTitle icon="🧩" kleur="#2D9CDB" sub={`Level ${level + 1} · ${moves} stappen`}>
        PEPER DOOLHOF
      </GameTitle>
      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
        <DifficultyBadge level={diff.level} />
      </div>

      <div style={{
        background: "#F0FAE6", border: "4px solid #1A1A1A",
        boxShadow: "4px 4px 0 #1A1A1A",
        padding: 12, margin: "14px 0",
        display: "inline-block",
      }}>
        <div style={{
          display: "grid",
          gridTemplateColumns: `repeat(${grid[0].length}, ${cellSize}px)`,
          gridTemplateRows: `repeat(${N}, ${cellSize}px)`,
          gap: 2,
        }}>
          {grid.flatMap((row, r) => row.map((cell, c) => {
            const isPeper = pos[0] === r && pos[1] === c;
            const isExit = cell === 2;
            const isWall = cell === 1;
            return (
              <div key={`${r}-${c}`} style={{
                background: isWall ? "#1A1A1A" : isExit ? "#FFD23F" : "#FFF",
                border: "2px solid #1A1A1A",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: cellSize * 0.6, lineHeight: 1,
              }}>
                {isPeper ? "🌶️" : isExit ? "🏁" : ""}
              </div>
            );
          }))}
        </div>
      </div>

      {done ? (
        <div style={{
          background: "#FFF8EC", border: "4px solid #1A1A1A",
          boxShadow: "5px 5px 0 #1A1A1A",
          padding: 16, marginTop: 10, textAlign: "center",
        }}>
          <div style={{
            fontFamily: "'Bangers', sans-serif", fontSize: 28,
            color: "#3FA34D", letterSpacing: "0.04em", marginBottom: 8,
          }}>🎉 GEHAALD IN {moves} STAPPEN!</div>
          <div style={{ display: "flex", gap: 8, justifyContent: "center", flexWrap: "wrap" }}>
            {level + 1 < LEVELS.length
              ? <BigButton onClick={nextLevel} color="#5BB85B" style={{ color: "#FFF" }}>VOLGEND LEVEL →</BigButton>
              : <BigButton onClick={() => { setLevel(0); reset(); }} color="#5BB85B" style={{ color: "#FFF" }}>↻ NOG EENS</BigButton>}
            <BigButton onClick={reset}>↻ OPNIEUW</BigButton>
            <BigButton onClick={() => { diff.reopen(); }} color="#FFD23F">🌶️ PIT VERANDEREN</BigButton>
          </div>
        </div>
      ) : (
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(3, 56px)",
          gridTemplateRows: "repeat(3, 56px)",
          gap: 6, justifyContent: "center", marginTop: 12,
        }}>
          <div></div>
          <BigButton onClick={() => move(-1, 0)}>↑</BigButton>
          <div></div>
          <BigButton onClick={() => move(0, -1)}>←</BigButton>
          <div></div>
          <BigButton onClick={() => move(0, 1)}>→</BigButton>
          <div></div>
          <BigButton onClick={() => move(1, 0)}>↓</BigButton>
          <div></div>
        </div>
      )}
    </div>
  );
}

// ─── 8. Vang de Pepers ────────────────────────────────────────────────

function VangPepers({ onClose }) {
  const isMobile = useIsMobile();
  const DURATION = 30;
  const [running, setRunning] = React.useState(false);
  const [tijd, setTijd] = React.useState(DURATION);
  const [score, setScore] = React.useState(0);
  const [items, setItems] = React.useState([]);
  const [done, setDone] = React.useState(false);
  const idRef = React.useRef(0);
  const fieldRef = React.useRef(null);

  React.useEffect(() => {
    if (!running) return;
    const tick = setInterval(() => {
      setTijd(t => {
        if (t <= 1) { clearInterval(tick); setRunning(false); setDone(true); return 0; }
        return t - 1;
      });
    }, 1000);
    return () => clearInterval(tick);
  }, [running]);

  React.useEffect(() => {
    if (!running) return;
    const spawn = setInterval(() => {
      const isPeper = Math.random() > 0.3;
      const id = ++idRef.current;
      const left = Math.random() * 80 + 5;
      const dur = 2200 + Math.random() * 1300;
      setItems(arr => [...arr, { id, isPeper, left, dur, startedAt: Date.now() }]);
      setTimeout(() => {
        setItems(arr => arr.filter(x => x.id !== id));
      }, dur);
    }, 700);
    return () => clearInterval(spawn);
  }, [running]);

  function tap(item) {
    if (item.isPeper) setScore(s => s + 1);
    else setScore(s => Math.max(0, s - 2));
    setItems(arr => arr.filter(x => x.id !== item.id));
  }

  function start() {
    setScore(0); setTijd(DURATION); setItems([]); setDone(false); setRunning(true);
  }

  return (
    <div style={gameShellStyle(isMobile)}>
      <CloseBtn onClose={onClose} isMobile={isMobile} />
      <GameTitle icon="⚡" kleur="#3FA34D" sub="Tik 🌶️, vermijd 🪣">
        VANG DE PEPERS
      </GameTitle>
      <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
        <ScoreBadge score={score} kleur="#5BB85B" />
        <div style={{
          background: "#FFD23F", border: "3px solid #1A1A1A",
          boxShadow: "3px 3px 0 #1A1A1A",
          padding: "6px 14px",
          fontFamily: "'Bangers', sans-serif", fontSize: 18,
        }}>⏱ {tijd}s</div>
      </div>

      <div ref={fieldRef} style={{
        position: "relative",
        background: "#F0FAE6", border: "4px solid #1A1A1A",
        boxShadow: "4px 4px 0 #1A1A1A",
        height: 360, margin: "16px 0",
        overflow: "hidden", touchAction: "manipulation",
      }}>
        {!running && !done && (
          <div style={{
            position: "absolute", inset: 0,
            display: "flex", alignItems: "center", justifyContent: "center",
            flexDirection: "column", gap: 12, padding: 14, textAlign: "center",
          }}>
            <div style={{ fontSize: 50 }}>🌶️</div>
            <div style={{ fontSize: 18, color: "#3A3025" }}>
              Tik op de pepers (🌶️) en vermijd de wasknijpers (🪣).<br/>
              <b>30 seconden</b> om zo veel mogelijk te vangen!
            </div>
            <BigButton onClick={start} color="#5BB85B" style={{ color: "#FFF" }}>▶ START</BigButton>
          </div>
        )}

        {done && (
          <div style={{
            position: "absolute", inset: 0,
            display: "flex", alignItems: "center", justifyContent: "center",
            flexDirection: "column", gap: 10, textAlign: "center", padding: 14,
            background: "rgba(240,250,230,0.95)",
          }}>
            <div style={{ fontSize: 50 }}>{score >= 15 ? "🏆" : score >= 5 ? "🎉" : "🌶️"}</div>
            <div style={{
              fontFamily: "'Bangers', sans-serif", fontSize: 28,
              color: "#E63946", textShadow: "3px 3px 0 #1A1A1A",
              WebkitTextStroke: "1.2px #1A1A1A", letterSpacing: "0.04em",
            }}>JE VING {score} PEPERS!</div>
            <BigButton onClick={start} color="#5BB85B" style={{ color: "#FFF" }}>↻ NOG EENS</BigButton>
          </div>
        )}

        {running && items.map(it => (
          <button key={it.id} onClick={() => tap(it)}
            aria-label={it.isPeper ? "Peper" : "Wasknijper"}
            style={{
              position: "absolute", left: `${it.left}%`,
              top: -50,
              width: 48, height: 48, fontSize: 36, lineHeight: 1,
              background: "transparent", border: "none", cursor: "pointer",
              animation: `vang-fall ${it.dur}ms linear`,
              padding: 0,
            }}>
            {it.isPeper ? "🌶️" : "🪣"}
          </button>
        ))}
      </div>

      <style>{`
        @keyframes vang-fall {
          from { transform: translateY(0); }
          to { transform: translateY(420px); }
        }
      `}</style>
    </div>
  );
}

// ─── 9. Kleurplaat ────────────────────────────────────────────────────

function Kleurplaat({ onClose }) {
  const isMobile = useIsMobile();
  const COLORS = ["#E63946", "#3FA34D", "#FFD23F", "#FF8C1A", "#2D9CDB", "#8E44D1", "#1A1A1A", "#FFF8EC"];
  const PARTS = ["body", "pet", "klep", "knop", "achtergrond"];
  const [color, setColor] = React.useState(COLORS[0]);
  const [fills, setFills] = React.useState({
    body: "#FFF8EC", pet: "#FFF8EC", klep: "#FFF8EC",
    knop: "#FFF8EC", achtergrond: "#FFF8EC",
  });

  function paint(part) {
    setFills(f => ({ ...f, [part]: color }));
  }

  function reset() {
    setFills({ body: "#FFF8EC", pet: "#FFF8EC", klep: "#FFF8EC", knop: "#FFF8EC", achtergrond: "#FFF8EC" });
  }

  return (
    <div style={gameShellStyle(isMobile)}>
      <CloseBtn onClose={onClose} isMobile={isMobile} />
      <GameTitle icon="🎨" kleur="#FFD23F" sub="Tik op een kleur, dan op een vlak">
        KLEUR JE PEPER
      </GameTitle>

      <div style={{
        background: "#F0FAE6", border: "4px solid #1A1A1A",
        boxShadow: "4px 4px 0 #1A1A1A", padding: 12,
        margin: "14px 0", display: "flex", justifyContent: "center",
      }}>
        <svg viewBox="0 0 240 320" width="100%" style={{ maxWidth: 280, height: "auto" }}>
          <rect x="0" y="0" width="240" height="320" fill={fills.achtergrond}
            onClick={() => paint("achtergrond")} style={{ cursor: "pointer" }} />
          <path
            d="M 70 70 Q 120 30 170 70 L 180 95 L 60 97 Z"
            fill={fills.pet} stroke="#1A1A1A" strokeWidth="4" strokeLinejoin="round"
            onClick={() => paint("pet")} style={{ cursor: "pointer" }} />
          <path
            d="M 55 95 Q 120 92 185 95 L 192 105 Q 120 110 50 105 Z"
            fill={fills.klep} stroke="#1A1A1A" strokeWidth="4" strokeLinejoin="round"
            onClick={() => paint("klep")} style={{ cursor: "pointer" }} />
          <circle cx="120" cy="50" r="6" fill={fills.knop} stroke="#1A1A1A" strokeWidth="3"
            onClick={() => paint("knop")} style={{ cursor: "pointer" }} />
          <path
            d="M 120 100
               C 65 102, 60 175, 80 240
               C 90 275, 110 300, 120 305
               C 130 300, 150 275, 160 240
               C 180 175, 175 102, 120 100 Z"
            fill={fills.body} stroke="#1A1A1A" strokeWidth="5" strokeLinejoin="round"
            onClick={() => paint("body")} style={{ cursor: "pointer" }} />
          <circle cx="105" cy="155" r="9" fill="#FFF" stroke="#1A1A1A" strokeWidth="3" />
          <circle cx="135" cy="155" r="9" fill="#FFF" stroke="#1A1A1A" strokeWidth="3" />
          <circle cx="106" cy="156" r="3.5" fill="#1A1A1A" />
          <circle cx="136" cy="156" r="3.5" fill="#1A1A1A" />
          <path d="M 105 195 Q 120 210 135 195" stroke="#1A1A1A" strokeWidth="3.5" fill="none" strokeLinecap="round" />
        </svg>
      </div>

      <div style={{
        display: "flex", flexWrap: "wrap", gap: 8, justifyContent: "center",
        marginBottom: 10,
      }}>
        {COLORS.map(c => (
          <button key={c} onClick={() => setColor(c)}
            aria-label={`Kleur ${c}`}
            style={{
              width: 44, height: 44, borderRadius: "50%",
              background: c,
              border: c === color ? "4px solid #1A1A1A" : "3px solid #1A1A1A",
              boxShadow: c === color ? "0 0 0 3px #FFD23F, 3px 3px 0 #1A1A1A" : "3px 3px 0 #1A1A1A",
              cursor: "pointer",
            }} />
        ))}
      </div>
      <div style={{ textAlign: "center" }}>
        <BigButton onClick={reset} color="#FFF8EC" style={{ fontSize: 20 }}>↻ OPNIEUW BEGINNEN</BigButton>
      </div>
    </div>
  );
}

// ─── Registratie ──────────────────────────────────────────────────────

Object.assign(window, {
  TafelsSpel, TelPepers, PeperMemory, LetterMist, RijmSpel,
  PitQuiz, Doolhof, VangPepers, Kleurplaat,
});
