// peper-raket.jsx, Hete Peper vliegt met zijn jetpack omhoog en moet
// vijanden uit Pepperoni City ontwijken (wasknijpers, ijsblokjes, slakken).
// Pepers en bliksems geven extra punten. Bestuur met vinger of muis.
// Speelt schermvullend, schaalt mee met portrait/landscape op telefoon en tablet.

function PeperRaket({ onClose }) {
  const FIELD_W = 360;
  const FIELD_H = 540;
  const PLAYER_W = 64;
  const PLAYER_H = 86;
  const PLAYER_Y = FIELD_H - PLAYER_H - 36;

  const [running, setRunning] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [score, setScore] = React.useState(0);
  const [best, setBest] = React.useState(() => {
    try { return parseInt(localStorage.getItem("peper-raket-best") || "0", 10) || 0; }
    catch { return 0; }
  });
  const [, forceRender] = React.useReducer(x => x + 1, 0);
  const [scale, setScale] = React.useState(1);
  const [narrow, setNarrow] = React.useState(typeof window !== "undefined" && window.innerWidth <= 480);

  const wrapRef = React.useRef(null);
  const fieldRef = React.useRef(null);
  const playerXRef = React.useRef(FIELD_W / 2);
  const targetXRef = React.useRef(FIELD_W / 2);
  const obstaclesRef = React.useRef([]);
  const pickupsRef = React.useRef([]);
  const starsRef = React.useRef([]);
  const lastSpawnRef = React.useRef(0);
  const lastPickupRef = React.useRef(0);
  const altitudeRef = React.useRef(0);
  const speedRef = React.useRef(160);
  const scoreRef = React.useRef(0);
  const idRef = React.useRef(0);
  const lastFrameRef = React.useRef(0);
  const heldRef = React.useRef({ left: false, right: false });

  const OBSTACLES = ["🪣", "🧊", "❄️", "💧", "🐌", "🪨", "🥶"];

  // meet de beschikbare ruimte en bereken de schaalfactor zodat het hele
  // speelveld zichtbaar blijft, in zowel portrait als landscape
  React.useEffect(() => {
    function measure() {
      setNarrow(window.innerWidth <= 480);
      if (!wrapRef.current) return;
      const r = wrapRef.current.getBoundingClientRect();
      if (r.width > 0 && r.height > 0) {
        setScale(Math.max(0.3, Math.min(r.width / FIELD_W, r.height / FIELD_H)));
      }
    }
    measure();
    let ro;
    if (typeof ResizeObserver !== "undefined" && wrapRef.current) {
      ro = new ResizeObserver(measure);
      ro.observe(wrapRef.current);
    }
    window.addEventListener("resize", measure);
    window.addEventListener("orientationchange", measure);
    return () => {
      if (ro) ro.disconnect();
      window.removeEventListener("resize", measure);
      window.removeEventListener("orientationchange", measure);
    };
  }, []);

  // tijdens het spelen, blokkeer body-scroll zodat iOS niet bouncet
  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, []);

  // sluit met Escape
  React.useEffect(() => {
    function onKey(e) { if (e.key === "Escape") onClose && onClose(); }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  function reset() {
    playerXRef.current = FIELD_W / 2;
    targetXRef.current = FIELD_W / 2;
    obstaclesRef.current = [];
    pickupsRef.current = [];
    starsRef.current = Array.from({ length: 36 }, () => ({
      id: ++idRef.current,
      x: Math.random() * FIELD_W,
      y: Math.random() * FIELD_H,
      r: 0.8 + Math.random() * 1.8,
      o: 0.35 + Math.random() * 0.55,
    }));
    lastSpawnRef.current = 0;
    lastPickupRef.current = 0;
    altitudeRef.current = 0;
    speedRef.current = 160;
    scoreRef.current = 0;
    setScore(0);
  }

  function start() {
    reset();
    setDone(false);
    setRunning(true);
  }

  React.useEffect(() => {
    if (!running) return;
    lastFrameRef.current = performance.now();
    let raf = 0;

    function frame(ts) {
      const dt = Math.min(0.05, (ts - lastFrameRef.current) / 1000);
      lastFrameRef.current = ts;

      // toetsenbord-besturing, blijven duwen zolang de toets ingedrukt is
      const keySpeed = 360;
      if (heldRef.current.left) targetXRef.current -= keySpeed * dt;
      if (heldRef.current.right) targetXRef.current += keySpeed * dt;

      // klem en versoepel beweging
      const halfW = PLAYER_W / 2;
      targetXRef.current = Math.max(halfW, Math.min(FIELD_W - halfW, targetXRef.current));
      playerXRef.current += (targetXRef.current - playerXRef.current) * Math.min(1, dt * 14);

      // moeilijkheid loopt op met hoogte
      altitudeRef.current += speedRef.current * dt;
      speedRef.current = Math.min(440, 160 + altitudeRef.current * 0.018);
      scoreRef.current += speedRef.current * dt * 0.16;

      // entiteiten bewegen mee met de "scroll" naar beneden
      obstaclesRef.current = obstaclesRef.current
        .map(o => ({
          ...o,
          y: o.y + (speedRef.current + (o.dy || 0)) * dt,
          x: o.x + (o.dx || 0) * dt,
          rot: (o.rot || 0) + (o.spin || 0) * dt,
        }))
        .filter(o => o.y < FIELD_H + 80 && o.x > -50 && o.x < FIELD_W + 50);

      pickupsRef.current = pickupsRef.current
        .map(p => ({ ...p, y: p.y + speedRef.current * dt }))
        .filter(p => p.y < FIELD_H + 40);

      starsRef.current.forEach(s => {
        s.y += speedRef.current * dt * 0.55;
        if (s.y > FIELD_H + 4) { s.y = -2; s.x = Math.random() * FIELD_W; }
      });

      // spawn vijanden, sneller naarmate je hoger komt
      const spawnInterval = Math.max(340, 850 - altitudeRef.current * 0.08);
      lastSpawnRef.current += dt * 1000;
      if (lastSpawnRef.current >= spawnInterval) {
        lastSpawnRef.current = 0;
        const t = OBSTACLES[Math.floor(Math.random() * OBSTACLES.length)];
        obstaclesRef.current.push({
          id: ++idRef.current,
          type: t,
          x: 24 + Math.random() * (FIELD_W - 48),
          y: -40,
          dx: (Math.random() - 0.5) * 50,
          spin: (Math.random() - 0.5) * 2,
          rot: 0,
          size: 40,
        });
      }

      // pickups, iets minder vaak
      lastPickupRef.current += dt * 1000;
      if (lastPickupRef.current >= 1400 + Math.random() * 600) {
        lastPickupRef.current = 0;
        const t = Math.random() > 0.78 ? "⚡" : "🌶️";
        pickupsRef.current.push({
          id: ++idRef.current,
          type: t,
          x: 24 + Math.random() * (FIELD_W - 48),
          y: -30,
          size: 32,
        });
      }

      // botsing, ronde hitbox iets kleiner dan visueel
      const px = playerXRef.current;
      const py = PLAYER_Y + PLAYER_H * 0.42;
      const playerR = PLAYER_W * 0.32;

      const survivors = [];
      let bonus = 0;
      for (const p of pickupsRef.current) {
        const d = Math.hypot(p.x - px, p.y - py);
        if (d < playerR + p.size * 0.45) bonus += p.type === "⚡" ? 30 : 12;
        else survivors.push(p);
      }
      pickupsRef.current = survivors;
      if (bonus) scoreRef.current += bonus;

      let crashed = false;
      for (const o of obstaclesRef.current) {
        const d = Math.hypot(o.x - px, o.y - py);
        if (d < playerR + o.size * 0.34) { crashed = true; break; }
      }

      setScore(Math.floor(scoreRef.current));

      if (crashed) {
        setRunning(false);
        setDone(true);
        const final = Math.floor(scoreRef.current);
        setBest(prev => {
          if (final > prev) {
            try { localStorage.setItem("peper-raket-best", String(final)); } catch {}
            return final;
          }
          return prev;
        });
        return;
      }

      forceRender();
      raf = requestAnimationFrame(frame);
    }

    raf = requestAnimationFrame(frame);
    return () => cancelAnimationFrame(raf);
  }, [running]);

  // toetsenbord, pijltjes en A/D
  React.useEffect(() => {
    if (!running) return;
    function down(e) {
      if (e.key === "ArrowLeft" || e.key === "a" || e.key === "A") { heldRef.current.left = true; e.preventDefault(); }
      if (e.key === "ArrowRight" || e.key === "d" || e.key === "D") { heldRef.current.right = true; e.preventDefault(); }
    }
    function up(e) {
      if (e.key === "ArrowLeft" || e.key === "a" || e.key === "A") heldRef.current.left = false;
      if (e.key === "ArrowRight" || e.key === "d" || e.key === "D") heldRef.current.right = false;
    }
    window.addEventListener("keydown", down);
    window.addEventListener("keyup", up);
    return () => {
      window.removeEventListener("keydown", down);
      window.removeEventListener("keyup", up);
      heldRef.current.left = false;
      heldRef.current.right = false;
    };
  }, [running]);

  function pointerToTarget(e) {
    if (!fieldRef.current) return;
    const rect = fieldRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    targetXRef.current = (x / Math.max(1, rect.width)) * FIELD_W;
  }

  function onPointerDown(e) {
    if (!running) return;
    if (e.currentTarget.setPointerCapture) {
      try { e.currentTarget.setPointerCapture(e.pointerId); } catch {}
    }
    pointerToTarget(e);
  }

  function onPointerMove(e) {
    if (!running) return;
    pointerToTarget(e);
  }

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "#0E1747",
      fontFamily: "'Patrick Hand', cursive",
      color: "#FFF",
      display: "flex", flexDirection: "column",
      overscrollBehavior: "contain",
      touchAction: "none",
    }}>
      {/* compacte balk met titel, score, best en sluiten */}
      <div style={{
        flexShrink: 0,
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: narrow ? "8px 10px" : "10px 16px",
        gap: 8,
        background: "rgba(20, 34, 90, 0.85)",
        borderBottom: "3px solid #1A1A1A",
      }}>
        <div style={{
          fontFamily: "'Bangers', sans-serif",
          fontSize: narrow ? 22 : 28, letterSpacing: "0.04em",
          color: "#E63946",
          WebkitTextStroke: "1.2px #1A1A1A",
          textShadow: "2px 2px 0 #1A1A1A",
          display: "flex", alignItems: "center", gap: 6,
          whiteSpace: "nowrap",
        }}>
          <span style={{ fontSize: narrow ? 20 : 24, WebkitTextStroke: 0, textShadow: "none" }}>🚀</span>
          {narrow ? "RAKET" : "PEPER RAKET"}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: narrow ? 6 : 10 }}>
          <div style={{
            background: "#FFD23F", color: "#1A1A1A",
            border: "3px solid #1A1A1A", boxShadow: "3px 3px 0 #1A1A1A",
            padding: narrow ? "4px 10px" : "6px 14px",
            fontFamily: "'Bangers', sans-serif",
            fontSize: narrow ? 16 : 18, letterSpacing: "0.04em",
            whiteSpace: "nowrap",
          }}>⚡ {score}</div>
          <div style={{
            background: "#3FA34D", color: "#FFF",
            border: "3px solid #1A1A1A", boxShadow: "3px 3px 0 #1A1A1A",
            padding: narrow ? "4px 10px" : "6px 14px",
            fontFamily: "'Bangers', sans-serif",
            fontSize: narrow ? 16 : 18, letterSpacing: "0.04em",
            whiteSpace: "nowrap",
          }}>🏆 {best}</div>
          <button onClick={onClose} aria-label="Sluiten" style={{
            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", flexShrink: 0,
          }}>✕</button>
        </div>
      </div>

      {/* speelveld neemt al de overige ruimte in en wordt geschaald */}
      <div ref={wrapRef} style={{
        flex: 1, position: "relative",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 6, overflow: "hidden",
      }}>
        <div style={{
          width: FIELD_W * scale, height: FIELD_H * scale,
          position: "relative",
        }}>
          <div ref={fieldRef}
            onPointerDown={onPointerDown}
            onPointerMove={onPointerMove}
            style={{
              position: "absolute", left: 0, top: 0,
              width: FIELD_W, height: FIELD_H,
              transform: `scale(${scale})`,
              transformOrigin: "top left",
              background: "linear-gradient(180deg, #14225A 0%, #2C4A8C 45%, #5C8FCF 80%, #9CC8F0 100%)",
              border: "4px solid #1A1A1A",
              boxShadow: "5px 5px 0 #1A1A1A",
              overflow: "hidden",
              touchAction: "none", userSelect: "none",
              cursor: running ? "grab" : "default",
            }}>

            {/* sterren */}
            {starsRef.current.map(s => (
              <div key={s.id} style={{
                position: "absolute",
                left: s.x - s.r, top: s.y - s.r,
                width: s.r * 2, height: s.r * 2, borderRadius: "50%",
                background: `rgba(255,255,255,${s.o})`,
                pointerEvents: "none",
              }} />
            ))}

            {/* hoogte-meter */}
            {running && (
              <div style={{
                position: "absolute", top: 8, left: 8,
                background: "rgba(26,26,26,0.55)", color: "#FFD23F",
                border: "2px solid #FFD23F", padding: "2px 8px",
                fontFamily: "'Bangers', sans-serif", fontSize: 14,
                letterSpacing: "0.04em", pointerEvents: "none",
              }}>
                ⬆ {Math.floor(altitudeRef.current)}m
              </div>
            )}

            {/* speler raket */}
            <img src="/assets/peper-raket.png" alt="Peper Raket" draggable={false}
              style={{
                position: "absolute",
                left: playerXRef.current - PLAYER_W / 2,
                top: PLAYER_Y,
                width: PLAYER_W, height: PLAYER_H,
                objectFit: "contain",
                pointerEvents: "none",
                filter: "drop-shadow(2px 4px 0 rgba(0,0,0,0.4))",
                animation: running ? "peper-raket-bob 0.45s ease-in-out infinite alternate" : "none",
              }} />

            {/* obstakels */}
            {obstaclesRef.current.map(o => (
              <div key={o.id} style={{
                position: "absolute",
                left: o.x - o.size / 2, top: o.y - o.size / 2,
                width: o.size, height: o.size,
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: o.size * 0.85, lineHeight: 1,
                transform: `rotate(${(o.rot || 0).toFixed(2)}rad)`,
                pointerEvents: "none",
                filter: "drop-shadow(2px 3px 0 rgba(0,0,0,0.35))",
              }}>{o.type}</div>
            ))}

            {/* pickups */}
            {pickupsRef.current.map(p => (
              <div key={p.id} style={{
                position: "absolute",
                left: p.x - p.size / 2, top: p.y - p.size / 2,
                width: p.size, height: p.size,
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: p.size * 0.9, lineHeight: 1,
                pointerEvents: "none",
                filter: p.type === "⚡"
                  ? "drop-shadow(0 0 10px rgba(255,210,63,0.95))"
                  : "drop-shadow(0 0 8px rgba(255,140,26,0.85))",
                animation: "peper-raket-pulse 0.7s ease-in-out infinite alternate",
              }}>{p.type}</div>
            ))}

            {/* start-overlay */}
            {!running && !done && (
              <div style={{
                position: "absolute", inset: 0,
                display: "flex", alignItems: "center", justifyContent: "center",
                flexDirection: "column", gap: 14, padding: 22, textAlign: "center",
                background: "rgba(0,0,0,0.5)", color: "#FFF",
              }}>
                <div style={{ fontSize: 64, lineHeight: 1 }}>🚀</div>
                <div style={{
                  fontFamily: "'Bangers', sans-serif", fontSize: 28,
                  color: "#FFD23F", letterSpacing: "0.04em", lineHeight: 1.1,
                  WebkitTextStroke: "1.2px #1A1A1A", textShadow: "3px 3px 0 #1A1A1A",
                }}>VLIEG OMHOOG!</div>
                <div style={{ fontSize: 16, maxWidth: 280, lineHeight: 1.3 }}>
                  Sleep met je vinger of beweeg de muis (← → werkt ook).
                  Wijk uit aan 🪣 🧊 ❄️ 💧 🐌 🪨 en pak 🌶️ ⚡ voor extra punten!
                </div>
                <BigButton onClick={start} color="#5BB85B" style={{ color: "#FFF" }}>
                  ▶ START
                </BigButton>
              </div>
            )}

            {/* game-over overlay */}
            {done && (
              <div style={{
                position: "absolute", inset: 0,
                display: "flex", alignItems: "center", justifyContent: "center",
                flexDirection: "column", gap: 10, padding: 22, textAlign: "center",
                background: "rgba(0,0,0,0.6)", color: "#FFF",
              }}>
                <div style={{ fontSize: 60, lineHeight: 1 }}>💥</div>
                <div style={{
                  fontFamily: "'Bangers', sans-serif", fontSize: 30,
                  color: "#FFD23F", letterSpacing: "0.04em", lineHeight: 1,
                  WebkitTextStroke: "1.2px #1A1A1A", textShadow: "3px 3px 0 #1A1A1A",
                }}>BOEM!</div>
                <div style={{
                  fontFamily: "'Bangers', sans-serif", fontSize: 22,
                  color: "#FFF", letterSpacing: "0.04em",
                }}>JE SCOORDE {score}</div>
                <div style={{ fontSize: 15 }}>
                  {score >= best && score > 0 ? "🏆 NIEUW RECORD!" : `Beste score: ${best}`}
                </div>
                <BigButton onClick={start} color="#5BB85B" style={{ color: "#FFF" }}>
                  ↻ NOG EENS
                </BigButton>
              </div>
            )}
          </div>
        </div>
      </div>

      <style>{`
        @keyframes peper-raket-pulse {
          from { transform: scale(0.9); }
          to { transform: scale(1.1); }
        }
        @keyframes peper-raket-bob {
          from { transform: translateY(0px); }
          to { transform: translateY(-3px); }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { PeperRaket });
