// peper-flappy.jsx, Flappy-Bird-variant met Hete Peper en zijn jetpack.
// Tik (of druk op spatie) om te flappen, vlieg tussen pepervuur-buizen door.
// Gravity trekt je naar beneden, buizen komen van rechts. Score = buizen voorbij.

function PeperFlappy({ onClose }) {
  const FIELD_W = 480;
  const FIELD_H = 720;
  const PLAYER_X = 130;
  const PLAYER_W = 76;
  const PLAYER_H = 86;
  const GROUND_H = 80;
  const PIPE_W = 92;
  const GAP_BASE = 240; // grootte van de opening
  const PIPE_SPACING = 360; // afstand tussen pipes
  const PIPE_SPEED = 180; // pixels per seconde
  const GRAVITY = 1500;
  const FLAP_VEL = -490;
  const MAX_FALL = 700;

  const [phase, setPhase] = React.useState("intro"); // intro | playing | dead
  const [score, setScore] = React.useState(0);
  const [best, setBest] = React.useState(() => {
    try { return parseInt(localStorage.getItem("peper-flappy-best") || "0", 10) || 0; }
    catch { return 0; }
  });
  const [scale, setScale] = React.useState(1);
  const [narrow, setNarrow] = React.useState(typeof window !== "undefined" && window.innerWidth <= 600);
  const [, forceRender] = React.useReducer(x => x + 1, 0);

  const wrapRef = React.useRef(null);
  const playerRef = React.useRef({ y: FIELD_H * 0.4, vy: 0, rot: 0, flameT: 0, flap: 0 });
  const pipesRef = React.useRef([]);
  const cloudsRef = React.useRef([]);
  const buildingsRef = React.useRef([]);
  const particlesRef = React.useRef([]);
  const lastFrameRef = React.useRef(0);
  const distanceRef = React.useRef(0);
  const idRef = React.useRef(0);
  const flashRef = React.useRef(0);
  const shakeRef = React.useRef(0);

  // schaling
  React.useEffect(() => {
    function measure() {
      setNarrow(window.innerWidth <= 600);
      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);
    };
  }, []);

  // body-scroll vergrendelen
  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, []);

  // ESC sluit
  React.useEffect(() => {
    function onKey(e) {
      if (e.key === "Escape") { onClose && onClose(); return; }
      if (e.key === " " || e.key === "ArrowUp" || e.key === "w" || e.key === "W") {
        e.preventDefault();
        if (phase === "intro") start();
        else if (phase === "playing") flap();
        else if (phase === "dead") restart();
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [phase]);

  // initiele wolken & gebouwen voor parallax
  React.useEffect(() => {
    cloudsRef.current = Array.from({ length: 6 }, (_, i) => ({
      id: ++idRef.current,
      x: i * 180 + Math.random() * 80,
      y: 50 + Math.random() * 200,
      s: 0.7 + Math.random() * 0.5,
      vx: 12 + Math.random() * 10,
    }));
    buildingsRef.current = Array.from({ length: 14 }, (_, i) => {
      const w = 50 + Math.random() * 40;
      return {
        id: ++idRef.current,
        x: i * 80 + Math.random() * 30,
        w,
        h: 90 + Math.random() * 130,
        c: ["#3D2042", "#4F2A56", "#37254E", "#552E5A"][Math.floor(Math.random() * 4)],
        windows: Math.floor((90 + Math.random() * 130) / 22),
      };
    });
  }, []);

  function reset() {
    // start met een lichte opwaartse boost zodat speler tijd heeft om te reageren
    playerRef.current = { y: FIELD_H * 0.42, vy: -150, rot: 0, flameT: 0, flap: 0 };
    pipesRef.current = [];
    particlesRef.current = [];
    distanceRef.current = 0;
    flashRef.current = 0;
    shakeRef.current = 0;
    setScore(0);
    // spawn de eerste pipe op respectabele afstand zodat de speler tijd heeft
    spawnPipe(FIELD_W + 320);
    spawnPipe(FIELD_W + 320 + PIPE_SPACING);
  }

  function spawnPipe(x) {
    const minTop = 80;
    const maxTop = FIELD_H - GROUND_H - GAP_BASE - 80;
    const topH = minTop + Math.random() * (maxTop - minTop);
    pipesRef.current.push({
      id: ++idRef.current,
      x,
      topH,
      gap: GAP_BASE - Math.min(40, distanceRef.current * 0.005), // gap krimpt traag
      passed: false,
    });
  }

  function start() {
    reset();
    setPhase("playing");
  }

  function restart() {
    reset();
    setPhase("playing");
  }

  function flap() {
    const p = playerRef.current;
    p.vy = FLAP_VEL;
    p.flap = 1;
    // puff onder de peper
    for (let i = 0; i < 6; i++) {
      const ang = Math.PI + (Math.random() - 0.5) * 0.7;
      const v = 80 + Math.random() * 80;
      particlesRef.current.push({
        id: ++idRef.current,
        x: PLAYER_X + 8,
        y: p.y + PLAYER_H * 0.6,
        vx: Math.cos(ang) * v,
        vy: Math.sin(ang) * v + 50,
        life: 0.5 + Math.random() * 0.3,
        r: 3 + Math.random() * 3,
        c: ["#FFD23F", "#FF8C1A", "#E63946"][Math.floor(Math.random() * 3)],
      });
    }
  }

  function die() {
    const p = playerRef.current;
    flashRef.current = 1;
    shakeRef.current = 1;
    // explosie deeltjes
    for (let i = 0; i < 22; i++) {
      const ang = Math.random() * Math.PI * 2;
      const v = 150 + Math.random() * 200;
      particlesRef.current.push({
        id: ++idRef.current,
        x: PLAYER_X + PLAYER_W / 2,
        y: p.y + PLAYER_H / 2,
        vx: Math.cos(ang) * v,
        vy: Math.sin(ang) * v,
        life: 0.8 + Math.random() * 0.4,
        r: 4 + Math.random() * 4,
        c: ["#FFD23F", "#FF8C1A", "#E63946", "#FFF"][Math.floor(Math.random() * 4)],
      });
    }
    setBest(prev => {
      const nv = scoreRef();
      if (nv > prev) {
        try { localStorage.setItem("peper-flappy-best", String(nv)); } catch {}
        return nv;
      }
      return prev;
    });
    setPhase("dead");
  }

  // helper: lees actuele score
  const scoreRefVal = React.useRef(0);
  React.useEffect(() => { scoreRefVal.current = score; }, [score]);
  function scoreRef() { return scoreRefVal.current; }

  // game loop
  React.useEffect(() => {
    if (phase !== "playing") return;
    let raf = 0;
    lastFrameRef.current = performance.now();
    function frame(ts) {
      const dt = Math.min(0.04, (ts - lastFrameRef.current) / 1000);
      lastFrameRef.current = ts;
      distanceRef.current += dt * PIPE_SPEED;

      const p = playerRef.current;
      // physics
      p.vy = Math.min(MAX_FALL, p.vy + GRAVITY * dt);
      p.y += p.vy * dt;
      // doek-rotatie volgt vy
      const targetRot = Math.max(-0.45, Math.min(1.1, p.vy / 700));
      p.rot += (targetRot - p.rot) * Math.min(1, dt * 6);
      p.flameT += dt;
      p.flap *= Math.pow(0.001, dt);

      // pipes verschuiven
      const arr = pipesRef.current;
      for (const pp of arr) {
        pp.x -= PIPE_SPEED * dt;
        if (!pp.passed && pp.x + PIPE_W < PLAYER_X) {
          pp.passed = true;
          setScore(s => s + 1);
        }
      }
      // verwijder pipes die volledig links zijn
      pipesRef.current = arr.filter(pp => pp.x + PIPE_W > -20);
      // spawn nieuwe pipes
      const lastPipe = pipesRef.current[pipesRef.current.length - 1];
      if (!lastPipe || lastPipe.x < FIELD_W - PIPE_SPACING) {
        spawnPipe(FIELD_W + 40);
      }

      // collision check
      const px1 = PLAYER_X + 8, px2 = PLAYER_X + PLAYER_W - 8;
      const py1 = p.y + 10, py2 = p.y + PLAYER_H - 10;

      // grond / plafond
      if (p.y + PLAYER_H >= FIELD_H - GROUND_H) {
        p.y = FIELD_H - GROUND_H - PLAYER_H;
        die();
        forceRender();
        return;
      }
      if (p.y < -40) p.y = -40;

      for (const pp of pipesRef.current) {
        if (pp.x + PIPE_W < px1 || pp.x > px2) continue;
        const gapTop = pp.topH;
        const gapBottom = pp.topH + pp.gap;
        if (py1 < gapTop || py2 > gapBottom) {
          die();
          forceRender();
          return;
        }
      }

      // wolken drift
      cloudsRef.current.forEach(c => {
        c.x -= c.vx * dt * 0.4;
        if (c.x < -120) { c.x = FIELD_W + 60; c.y = 50 + Math.random() * 200; }
      });
      // gebouwen scrollen langzamer (parallax)
      buildingsRef.current.forEach(b => {
        b.x -= PIPE_SPEED * dt * 0.25;
        if (b.x + b.w < -60) b.x = FIELD_W + 40;
      });

      // jetpack vlam-deeltjes
      if (Math.random() < 0.7) {
        particlesRef.current.push({
          id: ++idRef.current,
          x: PLAYER_X + 14 + Math.random() * 6,
          y: p.y + PLAYER_H * 0.6 + Math.random() * 6,
          vx: -60 - Math.random() * 100,
          vy: 60 + Math.random() * 80,
          life: 0.35 + Math.random() * 0.25,
          r: 3 + Math.random() * 3,
          c: Math.random() > 0.5 ? "#FFD23F" : "#FF8C1A",
        });
      }
      // particles update
      particlesRef.current = particlesRef.current
        .map(d => ({
          ...d,
          x: d.x + d.vx * dt,
          y: d.y + d.vy * dt,
          vy: d.vy + 600 * dt,
          life: d.life - dt,
        }))
        .filter(d => d.life > 0);

      // flash en shake decay
      flashRef.current = Math.max(0, flashRef.current - dt * 3);
      shakeRef.current = Math.max(0, shakeRef.current - dt * 2.5);

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

  // ook bij dood: deeltjes en flash blijven decayen
  React.useEffect(() => {
    if (phase !== "dead") return;
    let raf = 0;
    lastFrameRef.current = performance.now();
    function frame(ts) {
      const dt = Math.min(0.04, (ts - lastFrameRef.current) / 1000);
      lastFrameRef.current = ts;
      particlesRef.current = particlesRef.current
        .map(d => ({
          ...d,
          x: d.x + d.vx * dt,
          y: d.y + d.vy * dt,
          vy: d.vy + 600 * dt,
          life: d.life - dt,
        }))
        .filter(d => d.life > 0);
      flashRef.current = Math.max(0, flashRef.current - dt * 3);
      shakeRef.current = Math.max(0, shakeRef.current - dt * 2.5);
      forceRender();
      raf = requestAnimationFrame(frame);
    }
    raf = requestAnimationFrame(frame);
    return () => cancelAnimationFrame(raf);
  }, [phase]);

  function handleTap() {
    if (phase === "intro") start();
    else if (phase === "playing") flap();
    else if (phase === "dead") restart();
  }

  const p = playerRef.current;
  const shake = shakeRef.current;
  const sx = (Math.random() - 0.5) * shake * 8;
  const sy = (Math.random() - 0.5) * shake * 8;

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "#1A2330",
      fontFamily: "'Patrick Hand', cursive",
      color: "#1A1A1A",
      display: "flex", flexDirection: "column",
      overscrollBehavior: "contain",
      touchAction: "none",
    }}>
      <div style={{
        flexShrink: 0,
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: narrow ? "8px 10px" : "10px 16px",
        gap: 8,
        background: "rgba(255, 245, 220, 0.96)",
        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 ? "FLAPPY" : "PEPER FLAPPY"}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: narrow ? 6 : 10 }}>
          <Pill bg="#FFD23F" color="#1A1A1A" narrow={narrow}>⚡ {score}</Pill>
          <Pill bg="#FF8C1A" color="#FFF" narrow={narrow}>🏆 {best}</Pill>
          <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>

      <div ref={wrapRef} onPointerDown={handleTap} style={{
        flex: 1, position: "relative",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 6, overflow: "hidden", cursor: "pointer",
      }}>
        <div style={{
          width: FIELD_W * scale, height: FIELD_H * scale,
          position: "relative",
          transform: `translate(${sx}px, ${sy}px)`,
        }}>
          <svg
            viewBox={`0 0 ${FIELD_W} ${FIELD_H}`}
            preserveAspectRatio="none"
            width={FIELD_W * scale}
            height={FIELD_H * scale}
            style={{
              display: "block",
              border: "4px solid #1A1A1A",
              boxShadow: "5px 5px 0 #1A1A1A",
              touchAction: "none", userSelect: "none",
            }}>
            <defs>
              <linearGradient id="pf-sky" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#FFB37D" />
                <stop offset="35%" stopColor="#FF8C42" />
                <stop offset="70%" stopColor="#9C5DA8" />
                <stop offset="100%" stopColor="#3D2A6E" />
              </linearGradient>
              <linearGradient id="pf-pipe" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0%" stopColor="#A01B26" />
                <stop offset="20%" stopColor="#E63946" />
                <stop offset="50%" stopColor="#FF6B5A" />
                <stop offset="80%" stopColor="#E63946" />
                <stop offset="100%" stopColor="#A01B26" />
              </linearGradient>
              <linearGradient id="pf-pipe-cap" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0%" stopColor="#7C0F1A" />
                <stop offset="50%" stopColor="#E63946" />
                <stop offset="100%" stopColor="#7C0F1A" />
              </linearGradient>
              <linearGradient id="pf-ground" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#5A3A18" />
                <stop offset="100%" stopColor="#321F0C" />
              </linearGradient>
              <linearGradient id="pf-grass" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#5BB85B" />
                <stop offset="100%" stopColor="#2E7B2E" />
              </linearGradient>
              <radialGradient id="pf-sun" cx="0.5" cy="0.5" r="0.5">
                <stop offset="0%" stopColor="#FFE56F" />
                <stop offset="60%" stopColor="#FFB347" />
                <stop offset="100%" stopColor="rgba(255, 140, 26, 0)" />
              </radialGradient>
              <radialGradient id="pf-glow" cx="0.5" cy="0.5" r="0.5">
                <stop offset="0%" stopColor="#FFE56F" stopOpacity="0.6" />
                <stop offset="100%" stopColor="#FFE56F" stopOpacity="0" />
              </radialGradient>
              <filter id="pf-shadow" x="-30%" y="-30%" width="160%" height="160%">
                <feGaussianBlur stdDeviation="3" />
              </filter>
            </defs>

            {/* lucht */}
            <rect x="0" y="0" width={FIELD_W} height={FIELD_H} fill="url(#pf-sky)" />

            {/* zon */}
            <g>
              <circle cx={FIELD_W * 0.78} cy={130} r={140} fill="url(#pf-sun)" opacity="0.7" />
              <circle cx={FIELD_W * 0.78} cy={130} r={48} fill="#FFE56F" stroke="#1A1A1A" strokeWidth="2.5" />
              <circle cx={FIELD_W * 0.78 - 12} cy={120} r={14} fill="rgba(255,255,255,0.55)" />
            </g>

            {/* skyline silhouet (parallax 0.25) */}
            <g>
              {buildingsRef.current.map(b => (
                <g key={b.id}>
                  <rect x={b.x} y={FIELD_H - GROUND_H - b.h}
                    width={b.w} height={b.h}
                    fill={b.c} stroke="#1A1A1A" strokeWidth="2" />
                  {/* daklijn */}
                  <rect x={b.x - 2} y={FIELD_H - GROUND_H - b.h - 6}
                    width={b.w + 4} height={6}
                    fill={b.c} stroke="#1A1A1A" strokeWidth="2" />
                  {/* raampjes */}
                  {Array.from({ length: b.windows }).map((_, i) => {
                    const wy = FIELD_H - GROUND_H - b.h + 16 + i * 22;
                    return Array.from({ length: 2 }).map((_, j) => (
                      <rect key={`${i}-${j}`}
                        x={b.x + 10 + j * 22}
                        y={wy}
                        width={10} height={12}
                        fill={Math.random() > 0.3 ? "#FFD23F" : "#5C3A1A"}
                        stroke="#1A1A1A" strokeWidth="1" />
                    ));
                  })}
                </g>
              ))}
            </g>

            {/* wolken */}
            {cloudsRef.current.map(c => (
              <g key={c.id} transform={`translate(${c.x} ${c.y}) scale(${c.s})`} opacity="0.85">
                <ellipse cx="0" cy="0" rx="40" ry="18" fill="#FFF8EC" stroke="#1A1A1A" strokeWidth="2" />
                <ellipse cx="-22" cy="6" rx="18" ry="11" fill="#FFF8EC" stroke="#1A1A1A" strokeWidth="2" />
                <ellipse cx="24" cy="6" rx="20" ry="13" fill="#FFF8EC" stroke="#1A1A1A" strokeWidth="2" />
              </g>
            ))}

            {/* pipes */}
            {pipesRef.current.map(pp => (
              <g key={pp.id}>
                {/* boven-pipe */}
                <rect x={pp.x} y={0} width={PIPE_W} height={pp.topH - 22}
                  fill="url(#pf-pipe)" stroke="#1A1A1A" strokeWidth="3" />
                <rect x={pp.x - 6} y={pp.topH - 22} width={PIPE_W + 12} height="22"
                  fill="url(#pf-pipe-cap)" stroke="#1A1A1A" strokeWidth="3" />
                {/* glow boven gap */}
                <ellipse cx={pp.x + PIPE_W / 2} cy={pp.topH + 4} rx={PIPE_W / 2 + 6} ry="8"
                  fill="#FFE56F" opacity="0.45" />
                {/* onder-pipe */}
                <rect x={pp.x} y={pp.topH + pp.gap + 22} width={PIPE_W} height={FIELD_H - GROUND_H - (pp.topH + pp.gap + 22)}
                  fill="url(#pf-pipe)" stroke="#1A1A1A" strokeWidth="3" />
                <rect x={pp.x - 6} y={pp.topH + pp.gap} width={PIPE_W + 12} height="22"
                  fill="url(#pf-pipe-cap)" stroke="#1A1A1A" strokeWidth="3" />
                {/* glow onder gap */}
                <ellipse cx={pp.x + PIPE_W / 2} cy={pp.topH + pp.gap - 4} rx={PIPE_W / 2 + 6} ry="8"
                  fill="#FFE56F" opacity="0.45" />
                {/* vuur-detail in pipe */}
                <path d={`M ${pp.x + 18} ${pp.topH - 28} q 4 -10 8 -2 q 4 -8 8 0 q 4 -6 8 -1`}
                  stroke="#FFD23F" strokeWidth="2" fill="none" strokeLinecap="round" />
                <path d={`M ${pp.x + 18} ${pp.topH + pp.gap + 32} q 4 10 8 2 q 4 8 8 0 q 4 6 8 1`}
                  stroke="#FFD23F" strokeWidth="2" fill="none" strokeLinecap="round" />
              </g>
            ))}

            {/* grond */}
            <g>
              <rect x={0} y={FIELD_H - GROUND_H} width={FIELD_W} height={20}
                fill="url(#pf-grass)" stroke="#1A1A1A" strokeWidth="2.5" />
              <rect x={0} y={FIELD_H - GROUND_H + 18} width={FIELD_W} height={GROUND_H - 18}
                fill="url(#pf-ground)" stroke="#1A1A1A" strokeWidth="2.5" />
              {/* gras-stippels */}
              {Array.from({ length: Math.ceil(FIELD_W / 24) }).map((_, i) => (
                <path key={i}
                  d={`M ${i * 24 + 10} ${FIELD_H - GROUND_H + 1} l 3 -6 l 3 6`}
                  stroke="#1F6826" strokeWidth="1.5" fill="none" />
              ))}
            </g>

            {/* deeltjes */}
            {particlesRef.current.map(d => (
              <circle key={d.id} cx={d.x} cy={d.y} r={d.r}
                fill={d.c} opacity={Math.max(0, d.life * 1.3)} />
            ))}

            {/* speler */}
            {phase !== "dead" && (
              <g transform={`translate(${PLAYER_X + PLAYER_W / 2} ${p.y + PLAYER_H / 2}) rotate(${(p.rot * 180 / Math.PI).toFixed(1)})`}>
                {/* schaduw */}
                <ellipse cx="0" cy={PLAYER_H * 0.55} rx={PLAYER_W * 0.4} ry="4" fill="rgba(0,0,0,0.3)" />
                {/* jetpack vlam (achter de peper) */}
                <g transform={`translate(${-PLAYER_W * 0.45} 0)`}>
                  <ellipse cx={0} cy={0}
                    rx={14 + Math.sin(p.flameT * 12) * 3 + p.flap * 8}
                    ry={9 + Math.sin(p.flameT * 18) * 2}
                    fill="#FFD23F" opacity="0.85" />
                  <ellipse cx={-2} cy={0}
                    rx={9 + Math.sin(p.flameT * 14) * 2}
                    ry={5}
                    fill="#FF8C1A" />
                  <ellipse cx={-4} cy={0}
                    rx={5} ry={3}
                    fill="#FFF" opacity="0.8" />
                </g>
                {/* hete peper sprite */}
                <image href="/assets/peper-raket.png"
                  x={-PLAYER_W / 2} y={-PLAYER_H / 2}
                  width={PLAYER_W} height={PLAYER_H}
                  preserveAspectRatio="xMidYMid meet"
                  style={{ filter: "drop-shadow(2px 4px 0 rgba(0,0,0,0.4))" }} />
              </g>
            )}

            {/* flash bij dood */}
            {flashRef.current > 0 && (
              <rect x={0} y={0} width={FIELD_W} height={FIELD_H}
                fill="#FFF" opacity={flashRef.current * 0.6} />
            )}
          </svg>

          {/* score-overlay groot in beeld bij playing */}
          {phase === "playing" && (
            <div style={{
              position: "absolute", top: 30, left: 0, right: 0,
              textAlign: "center",
              fontFamily: "'Bangers', sans-serif",
              fontSize: 64 * scale,
              color: "#FFF",
              WebkitTextStroke: `${2 * scale}px #1A1A1A`,
              textShadow: `${4 * scale}px ${4 * scale}px 0 #1A1A1A`,
              letterSpacing: "0.05em",
              pointerEvents: "none",
            }}>{score}</div>
          )}

          {phase === "intro" && (
            <Overlay>
              <Title color="#E63946">PEPER FLAPPY</Title>
              <p style={overlayText}>
                Tik (of druk op <strong>spatie</strong>) om te flappen.
                Vlieg met Hete Peper tussen de pepervuur-buizen door, raak ze niet aan!
                Hoeveel buizen passeer je?
              </p>
              <BigButton onClick={start} color="#5BB85B" style={{ color: "#FFF" }}>
                ▶ START
              </BigButton>
            </Overlay>
          )}

          {phase === "dead" && (
            <Overlay>
              <Title color="#E63946">BOEM!</Title>
              <p style={overlayText}>
                Je passeerde <strong>{score}</strong> {score === 1 ? "buis" : "buizen"}.
                {score >= best && score > 0 && <><br /><span style={{ color: "#FF8C1A", fontWeight: "bold" }}>🏆 NIEUW RECORD!</span></>}
                {score < best && <><br />Beste: <strong>{best}</strong></>}
              </p>
              <BigButton onClick={restart} color="#5BB85B" style={{ color: "#FFF" }}>
                ↻ NOG EENS
              </BigButton>
            </Overlay>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PeperFlappy });
