// peper-game.jsx, werkend rekenspel: "Hete Peper Wiskunde-Missie"

function RekenSpel({ onClose }) {
  const [level, setLevel] = React.useState(1);
  const [score, setScore] = React.useState(0);
  const [lives, setLives] = React.useState(3);
  const [q, setQ] = React.useState(null);
  const [userAnswer, setUserAnswer] = React.useState("");
  const [feedback, setFeedback] = React.useState(null); // 'goed' | 'fout' | null
  const [streak, setStreak] = React.useState(0);
  const inputRef = React.useRef(null);

  function newQuestion(lvl) {
    const max = 5 + lvl * 3;
    const a = Math.floor(Math.random() * max) + 1;
    const b = Math.floor(Math.random() * max) + 1;
    const ops = lvl <= 1 ? ["+"] : lvl <= 3 ? ["+", "-"] : ["+", "-", "×"];
    const op = ops[Math.floor(Math.random() * ops.length)];
    let answer;
    let first = a, second = b;
    if (op === "+") answer = a + b;
    if (op === "-") { first = Math.max(a, b); second = Math.min(a, b); answer = first - second; }
    if (op === "×") { first = Math.min(a, 10); second = Math.min(b, 10); answer = first * second; }
    return { first, second, op, answer };
  }

  React.useEffect(() => { setQ(newQuestion(level)); }, []);
  React.useEffect(() => { inputRef.current?.focus(); }, [q]);

  function submit(e) {
    e?.preventDefault();
    if (!q || userAnswer === "") return;
    const correct = parseInt(userAnswer, 10) === q.answer;
    if (correct) {
      const bonus = 10 + streak * 2;
      setScore(s => s + bonus);
      setStreak(s => s + 1);
      setFeedback("goed");
      setTimeout(() => {
        setFeedback(null);
        setUserAnswer("");
        const newStreak = streak + 1;
        const newLevel = Math.min(5, 1 + Math.floor(newStreak / 3));
        setLevel(newLevel);
        setQ(newQuestion(newLevel));
      }, 900);
    } else {
      setLives(l => l - 1);
      setStreak(0);
      setFeedback("fout");
      setTimeout(() => {
        setFeedback(null);
        setUserAnswer("");
        if (lives - 1 <= 0) {
          // game over reset
          setLives(3); setLevel(1); setScore(0);
        }
        setQ(newQuestion(level));
      }, 1100);
    }
  }

  if (!q) return null;

  return (
    <div style={{
      background: "#D6EFC7",
      border: "6px solid #1A1A1A",
      boxShadow: "10px 10px 0 #1A1A1A",
      padding: "36px 40px",
      width: "min(880px, 92vw)",
      position: "relative",
      fontFamily: "'Patrick Hand', cursive",
    }}>
      {/* Sluit */}
      {onClose && (
        <button onClick={onClose} style={{
          position: "absolute", top: -18, right: -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",
        }}>✕</button>
      )}

      {/* Header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 18, gap: 14 }}>
        <div>
          <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 48, color: "#E63946", WebkitTextStroke: "1.5px #1A1A1A", textShadow: "4px 4px 0 #1A1A1A", letterSpacing: "0.03em", lineHeight: 0.95 }}>
            Wiskunde-Missie
          </div>
          <div style={{ fontSize: 22, color: "#6B5A3D", marginTop: 6 }}>Help Hete Peper de boze wasknijper verslaan!</div>
        </div>
        <PeperMascotte size={110} mood="determined" fire={feedback === "goed"} />
      </div>

      {/* Stats */}
      <div style={{
        display: "flex", gap: 10, marginBottom: 22, flexWrap: "wrap",
      }}>
        <div style={pillStyle("#FFD23F")}>LEVEL {level}</div>
        <div style={pillStyle("#3FA34D", "#F0FAE6")}>⚡ {score}</div>
        <div style={pillStyle("#E63946", "#F0FAE6")}>{"♥".repeat(lives)}{"♡".repeat(Math.max(0, 3 - lives))}</div>
        {streak >= 2 && <div style={pillStyle("#FF8C1A")}>🔥 {streak} op rij!</div>}
      </div>

      {/* Vraag */}
      <div style={{
        background: "#F0FAE6", border: "5px solid #1A1A1A",
        padding: "40px 24px", textAlign: "center", position: "relative",
        marginBottom: 20,
      }}>
        <div style={{
          fontFamily: "'Bangers', sans-serif",
          fontSize: 110, color: "#1A1A1A", letterSpacing: "0.04em", lineHeight: 1,
        }}>
          {q.first} {q.op} {q.second} = <span style={{ color: "#E63946" }}>?</span>
        </div>
        {feedback === "goed" && (
          <div style={{
            position: "absolute", top: -20, right: -20,
            transform: "rotate(-10deg)",
          }}>
            <Burst color="#3FA34D" size={110} rotate={-10}>
              <span style={{ color: "#F0FAE6" }}>JUIST!</span>
            </Burst>
          </div>
        )}
        {feedback === "fout" && (
          <div style={{
            position: "absolute", top: -20, right: -20,
            transform: "rotate(8deg)",
          }}>
            <Burst color="#E63946" size={110} rotate={8}>
              <span style={{ color: "#F0FAE6" }}>OEPS!</span>
            </Burst>
          </div>
        )}
      </div>

      {/* Input */}
      <form onSubmit={submit} style={{ display: "flex", gap: 14 }}>
        <input
          ref={inputRef}
          type="number"
          value={userAnswer}
          onChange={e => setUserAnswer(e.target.value)}
          placeholder="Typ je antwoord..."
          style={{
            flex: 1, padding: "18px 22px", fontSize: 38,
            fontFamily: "'Patrick Hand', cursive",
            border: "5px solid #1A1A1A", background: "#F0FAE6",
            outline: "none", boxShadow: "4px 4px 0 #1A1A1A",
          }}
        />
        <button type="submit" className="btn-comic rood" style={{ fontSize: 32, padding: "14px 32px" }}>
          🔥 VUUR!
        </button>
      </form>

      {/* Hint */}
      <div style={{ marginTop: 16, fontSize: 18, color: "#6B5A3D", textAlign: "center" }}>
        3 op rij = level omhoog · Druk op Enter om te vuren
      </div>
    </div>
  );
}

function pillStyle(bg, color = "#1A1A1A") {
  return {
    background: bg,
    color,
    border: "3px solid #1A1A1A",
    padding: "8px 18px",
    fontFamily: "'Bangers', sans-serif",
    fontSize: 24,
    letterSpacing: "0.04em",
    boxShadow: "3px 3px 0 #1A1A1A",
  };
}

// Kleine speling woordjes-spel (placeholder preview)
function WoordjesPreview() {
  const woorden = ["VUUR", "PEPER", "HELD", "STAD", "PET"];
  const [idx, setIdx] = React.useState(0);
  const w = woorden[idx];
  return (
    <div style={{ textAlign: "center" }}>
      <div style={{ fontFamily: "'Bangers', sans-serif", fontSize: 48, letterSpacing: "0.15em", color: "#1A1A1A" }}>
        {w.split("").map((l, i) => (
          <span key={i} style={{
            display: "inline-block", margin: "0 4px",
            background: i === 1 ? "#FFD23F" : "#F0FAE6",
            border: "3px solid #1A1A1A", padding: "6px 12px",
            boxShadow: "3px 3px 0 #1A1A1A",
          }}>{i === 1 ? "_" : l}</span>
        ))}
      </div>
      <div style={{ marginTop: 14, fontSize: 18, color: "#6B5A3D" }}>
        Welke letter mist? Binnenkort speelbaar!
      </div>
      <button onClick={() => setIdx((idx + 1) % woorden.length)}
        className="btn-comic oranje" style={{ marginTop: 14, fontSize: 18 }}>
        Volgend woord →
      </button>
    </div>
  );
}

Object.assign(window, { RekenSpel, WoordjesPreview });
