// unicorn-race.jsx, Allie rijdt op de regenboog-eenhoorn over obstakels.
// Eindeloze runner: spring met spatie, pijltje omhoog of een tik op het scherm
// over koekjes, taarten, hekken en plassen. Snoephartjes geven bonuspunten.
// Roze, glittery wereld met regenboog en sterren. Schaalt in landscape op
// telefoon, tablet en desktop.

function UnicornRace({ onClose }) {
  const FIELD_W = 900;
  const FIELD_H = 420;
  const GROUND_H = 70;
  const PLAYER_W = 150;
  const PLAYER_H = 130;
  const FLOOR_Y = FIELD_H - GROUND_H;
  const PLAYER_X = 110;

  const DIFFICULTIES = {
    superMakkelijk: {
      label: "Super makkelijk",
      icon: "🌈",
      color: "#B36BFF",
      startSpeed: 160,
      maxSpeed: 200,
      ramp: 0,
      gravity: 1500,
      jump1: -700,
      jump2: -600,
      spawnBase: 99,
      spawnMin: 99,
      stackChance: 0,
      obstacles: false,
      heartGapBase: 1.1,
      heartGapVar: 0.7,
      heartLow: 40,
      heartRange: 60,
      heartHighChance: 0.4,
      heartHighLow: 160,
      heartHighRange: 50,
    },
    makkelijk: {
      label: "Makkelijk",
      icon: "🌸",
      color: "#3FA34D",
      startSpeed: 200,
      maxSpeed: 320,
      ramp: 0.015,
      gravity: 1500,
      jump1: -700,
      jump2: -600,
      spawnBase: 2.0,
      spawnMin: 1.4,
      stackChance: 0,
    },
    normaal: {
      label: "Normaal",
      icon: "💖",
      color: "#FF7AC1",
      startSpeed: 320,
      maxSpeed: 540,
      ramp: 0.03,
      gravity: 1700,
      jump1: -730,
      jump2: -620,
      spawnBase: 1.6,
      spawnMin: 0.95,
      stackChance: 0.10,
    },
    moeilijk: {
      label: "Moeilijk",
      icon: "🔥",
      color: "#E63946",
      startSpeed: 420,
      maxSpeed: 820,
      ramp: 0.045,
      gravity: 1900,
      jump1: -780,
      jump2: -660,
      spawnBase: 1.3,
      spawnMin: 0.6,
      stackChance: 0.22,
    },
  };

  const [difficulty, setDifficulty] = React.useState(() => {
    try {
      const saved = localStorage.getItem("unicorn-race-difficulty");
      if (saved && DIFFICULTIES[saved]) return saved;
    } catch {}
    return "makkelijk";
  });
  const diff = DIFFICULTIES[difficulty];

  const [running, setRunning] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const [score, setScore] = React.useState(0);
  const [hearts, setHearts] = React.useState(0);
  const [best, setBest] = React.useState(() => {
    try { return parseInt(localStorage.getItem(`unicorn-race-best-${difficulty}`) || "0", 10) || 0; }
    catch { return 0; }
  });

  React.useEffect(() => {
    try {
      localStorage.setItem("unicorn-race-difficulty", difficulty);
      setBest(parseInt(localStorage.getItem(`unicorn-race-best-${difficulty}`) || "0", 10) || 0);
    } catch {}
  }, [difficulty]);
  const [, forceRender] = React.useReducer(x => x + 1, 0);
  const [scale, setScale] = React.useState(1);
  const [narrow, setNarrow] = React.useState(typeof window !== "undefined" && window.innerWidth <= 600);

  const wrapRef = React.useRef(null);
  const fieldRef = React.useRef(null);
  const playerYRef = React.useRef(FLOOR_Y - PLAYER_H);
  const playerVYRef = React.useRef(0);
  const onGroundRef = React.useRef(true);
  const jumpsRef = React.useRef(0);
  const obstaclesRef = React.useRef([]);
  const heartsRef = React.useRef([]);
  const cloudsRef = React.useRef([]);
  const sparklesRef = React.useRef([]);
  const groundOffsetRef = React.useRef(0);
  const lastSpawnRef = React.useRef(0);
  const lastHeartRef = React.useRef(0);
  const speedRef = React.useRef(360);
  const distRef = React.useRef(0);
  const scoreRef = React.useRef(0);
  const heartCountRef = React.useRef(0);
  const idRef = React.useRef(0);
  const lastFrameRef = React.useRef(0);
  const flashRef = React.useRef(0);

  const OBSTACLES = [
    { e: "🍪", w: 56, h: 50, label: "koekje" },
    { e: "🧁", w: 56, h: 64, label: "cupcake" },
    { e: "🍰", w: 64, h: 60, label: "taart" },
    { e: "🍩", w: 60, h: 54, label: "donut" },
    { e: "🍭", w: 58, h: 80, label: "lolly" },
  ];

  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);
    };
  }, []);

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

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

  function reset() {
    playerYRef.current = FLOOR_Y - PLAYER_H;
    playerVYRef.current = 0;
    onGroundRef.current = true;
    jumpsRef.current = 0;
    obstaclesRef.current = [];
    heartsRef.current = [];
    cloudsRef.current = [
      { id: ++idRef.current, x: 100, y: 60, s: 1, sp: 0.25 },
      { id: ++idRef.current, x: 380, y: 110, s: 0.8, sp: 0.2 },
      { id: ++idRef.current, x: 640, y: 40, s: 1.2, sp: 0.3 },
      { id: ++idRef.current, x: 820, y: 140, s: 0.9, sp: 0.22 },
    ];
    sparklesRef.current = Array.from({ length: 24 }, () => ({
      id: ++idRef.current,
      x: Math.random() * FIELD_W,
      y: Math.random() * (FLOOR_Y - 30),
      r: 1.2 + Math.random() * 2.4,
      sp: 0.4 + Math.random() * 0.8,
      tw: Math.random() * Math.PI * 2,
    }));
    groundOffsetRef.current = 0;
    lastSpawnRef.current = 0;
    lastHeartRef.current = 0;
    speedRef.current = diff.startSpeed;
    distRef.current = 0;
    scoreRef.current = 0;
    heartCountRef.current = 0;
    flashRef.current = 0;
    setScore(0);
    setHearts(0);
  }

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

  function jump() {
    if (!running) return;
    if (jumpsRef.current >= 2) return;
    playerVYRef.current = jumpsRef.current === 0 ? diff.jump1 : diff.jump2;
    jumpsRef.current += 1;
    onGroundRef.current = false;
  }

  function endGame() {
    setRunning(false);
    setDone(true);
    const finalScore = Math.floor(scoreRef.current);
    if (finalScore > best) {
      setBest(finalScore);
      try { localStorage.setItem(`unicorn-race-best-${difficulty}`, String(finalScore)); } catch {}
    }
  }

  React.useEffect(() => {
    if (!running) return;
    lastFrameRef.current = performance.now();
    let raf;
    function frame(t) {
      const dt = Math.min(0.05, (t - lastFrameRef.current) / 1000);
      lastFrameRef.current = t;

      // snelheid stijgt langzaam met de afstand
      speedRef.current = Math.min(diff.maxSpeed, diff.startSpeed + distRef.current * diff.ramp);
      distRef.current += speedRef.current * dt;
      scoreRef.current += speedRef.current * dt * 0.06;
      setScore(Math.floor(scoreRef.current));

      // zwaartekracht en sprong
      playerVYRef.current += diff.gravity * dt;
      playerYRef.current += playerVYRef.current * dt;
      if (playerYRef.current >= FLOOR_Y - PLAYER_H) {
        playerYRef.current = FLOOR_Y - PLAYER_H;
        playerVYRef.current = 0;
        onGroundRef.current = true;
        jumpsRef.current = 0;
      }

      // grond-scrolling, alleen voor de strepen
      groundOffsetRef.current = (groundOffsetRef.current + speedRef.current * dt) % 60;

      // wolken parallax
      for (const c of cloudsRef.current) {
        c.x -= c.sp * speedRef.current * dt;
        if (c.x < -120) { c.x = FIELD_W + Math.random() * 80; c.y = 30 + Math.random() * 130; }
      }

      // sterren / glitter
      for (const s of sparklesRef.current) {
        s.x -= s.sp * speedRef.current * dt;
        s.tw += dt * 4;
        if (s.x < -10) { s.x = FIELD_W + Math.random() * 30; s.y = Math.random() * (FLOOR_Y - 30); }
      }

      // obstakels spawnen op een minimaal-tijds interval, sneller bij hogere snelheid
      if (diff.obstacles !== false) {
        lastSpawnRef.current += dt;
        const spawnGap = Math.max(diff.spawnMin, diff.spawnBase - distRef.current * 0.0002);
        if (lastSpawnRef.current >= spawnGap) {
          lastSpawnRef.current = 0;
          const stack = diff.stackChance > 0 && Math.random() < diff.stackChance && distRef.current > 600 ? 2 : 1;
          const ob = OBSTACLES[Math.floor(Math.random() * OBSTACLES.length)];
          obstaclesRef.current.push({
            id: ++idRef.current,
            x: FIELD_W + 20,
            y: FLOOR_Y - ob.h * stack,
            w: ob.w,
            h: ob.h * stack,
            stack,
            ob,
          });
        }
      }

      // hartjes spawnen op grotere intervallen, op spronghoogte
      lastHeartRef.current += dt;
      const heartGapBase = diff.heartGapBase ?? 2.6;
      const heartGapVar = diff.heartGapVar ?? 1.5;
      if (lastHeartRef.current >= heartGapBase + Math.random() * heartGapVar) {
        lastHeartRef.current = 0;
        const useHigh = diff.heartHighChance && Math.random() < diff.heartHighChance;
        const heartLow = useHigh ? (diff.heartHighLow ?? 160) : (diff.heartLow ?? 130);
        const heartRange = useHigh ? (diff.heartHighRange ?? 50) : (diff.heartRange ?? 80);
        heartsRef.current.push({
          id: ++idRef.current,
          x: FIELD_W + 20,
          y: FLOOR_Y - heartLow - Math.random() * heartRange,
          got: false,
        });
      }

      // beweeg obstakels en hartjes
      for (const o of obstaclesRef.current) o.x -= speedRef.current * dt;
      for (const h of heartsRef.current) h.x -= speedRef.current * dt;
      obstaclesRef.current = obstaclesRef.current.filter(o => o.x + o.w > -20);
      heartsRef.current = heartsRef.current.filter(h => h.x > -20 && !h.got);

      // botsing speler vs obstakel, met een wat strakker hitbox
      const playerHitbox = {
        x: PLAYER_X + 32,
        y: playerYRef.current + 30,
        w: PLAYER_W - 56,
        h: PLAYER_H - 38,
      };
      for (const o of obstaclesRef.current) {
        if (
          playerHitbox.x < o.x + o.w - 6 &&
          playerHitbox.x + playerHitbox.w > o.x + 6 &&
          playerHitbox.y < o.y + o.h - 4 &&
          playerHitbox.y + playerHitbox.h > o.y + 4
        ) {
          flashRef.current = 0.6;
          endGame();
          return;
        }
      }

      // hartjes ophalen
      for (const h of heartsRef.current) {
        if (h.got) continue;
        if (
          playerHitbox.x < h.x + 36 &&
          playerHitbox.x + playerHitbox.w > h.x + 4 &&
          playerHitbox.y < h.y + 36 &&
          playerHitbox.y + playerHitbox.h > h.y + 4
        ) {
          h.got = true;
          heartCountRef.current += 1;
          scoreRef.current += 25;
          setHearts(heartCountRef.current);
        }
      }

      if (flashRef.current > 0) flashRef.current = Math.max(0, flashRef.current - dt);

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

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

  // bedien met spatie / pijltje omhoog / W
  React.useEffect(() => {
    function down(e) {
      if (e.key === " " || e.key === "ArrowUp" || e.key === "w" || e.key === "W") {
        if (!running && !done) { start(); e.preventDefault(); return; }
        if (running) { jump(); e.preventDefault(); return; }
        if (done) { start(); e.preventDefault(); }
      }
    }
    window.addEventListener("keydown", down);
    return () => window.removeEventListener("keydown", down);
  }, [running, done]);

  function onPointerDown(e) {
    e.preventDefault();
    if (!running && !done) { start(); return; }
    if (running) { jump(); return; }
    if (done) { start(); return; }
  }

  // styling helpers, uitgedrukt in veld-coördinaten
  const playerY = playerYRef.current;
  const inAir = !onGroundRef.current;

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "linear-gradient(180deg, #FFD7EE 0%, #FFB3D9 45%, #FF7AC1 100%)",
      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,255,255,0.55)",
        borderBottom: "3px solid #1A1A1A",
        backdropFilter: "blur(4px)",
      }}>
        <div style={{
          fontFamily: "'Bangers', sans-serif",
          fontSize: narrow ? 22 : 30, letterSpacing: "0.04em",
          color: "#E91E63",
          WebkitTextStroke: "1.4px #1A1A1A",
          textShadow: "2px 2px 0 #1A1A1A",
          display: "flex", alignItems: "center", gap: 6,
          whiteSpace: "nowrap",
        }}>
          <span style={{ fontSize: narrow ? 22 : 26, WebkitTextStroke: 0, textShadow: "none" }}>🦄</span>
          {narrow ? "ALLIE" : "ALLIE'S UNICORN-RACE"}
        </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: "#FF4FA3", 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",
          }}>💖 {hearts}</div>
          {!narrow && (
            <div style={{
              background: "#7E57FF", color: "#FFF",
              border: "3px solid #1A1A1A", boxShadow: "3px 3px 0 #1A1A1A",
              padding: "6px 14px",
              fontFamily: "'Bangers', sans-serif",
              fontSize: 18, letterSpacing: "0.04em",
              whiteSpace: "nowrap",
            }}>🏆 {best}</div>
          )}
          <button onClick={onClose} aria-label="Sluiten" style={{
            width: 44, height: 44, borderRadius: "50%",
            background: "#1A1A1A", color: "#FFE4F2",
            border: "3px solid #FFE4F2", boxShadow: "2px 2px 0 #1A1A1A",
            fontFamily: "'Bangers', sans-serif", fontSize: 22,
            cursor: "pointer", flexShrink: 0,
          }}>✕</button>
        </div>
      </div>

      <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}
            style={{
              position: "absolute",
              width: FIELD_W, height: FIELD_H,
              left: 0, top: 0,
              transform: `scale(${scale})`,
              transformOrigin: "0 0",
              background: "linear-gradient(180deg, #C9F2FF 0%, #FFE4F8 50%, #FFB6E1 100%)",
              border: "5px solid #1A1A1A",
              boxShadow: "0 8px 0 #1A1A1A, inset 0 0 0 3px rgba(255,255,255,0.5)",
              overflow: "hidden",
              cursor: running ? "pointer" : "default",
            }}>
            {/* regenboog op de achtergrond */}
            <div aria-hidden="true" style={{
              position: "absolute",
              left: -120, top: 30,
              width: 720, height: 720,
              borderRadius: "50%",
              border: "26px solid #FF4FA3",
              boxShadow: `
                inset 0 0 0 22px #FF8C42,
                inset 0 0 0 44px #FFD23F,
                inset 0 0 0 66px #6FCE6B,
                inset 0 0 0 88px #4FB7FF,
                inset 0 0 0 110px #B36BFF
              `,
              opacity: 0.55,
              clipPath: `polygon(0 0, 100% 0, 100% ${(FIELD_H - 80) / 720 * 100}%, 0 ${(FIELD_H - 80) / 720 * 100}%)`,
              pointerEvents: "none",
            }} />

            {/* glitter sterretjes */}
            {sparklesRef.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,
                background: "#FFF",
                borderRadius: "50%",
                opacity: 0.5 + 0.5 * Math.abs(Math.sin(s.tw)),
                boxShadow: "0 0 6px #FFF",
                pointerEvents: "none",
              }} />
            ))}

            {/* wolken */}
            {cloudsRef.current.map(c => (
              <div key={c.id} aria-hidden="true" style={{
                position: "absolute",
                left: c.x, top: c.y,
                fontSize: 70 * c.s,
                filter: "drop-shadow(2px 2px 0 rgba(0,0,0,0.08))",
                pointerEvents: "none",
              }}>☁️</div>
            ))}

            {/* hartjes om te pakken */}
            {heartsRef.current.map(h => (
              <div key={h.id} aria-hidden="true" style={{
                position: "absolute",
                left: h.x, top: h.y,
                width: 36, height: 36,
                fontSize: 36, lineHeight: 1,
                filter: "drop-shadow(2px 2px 0 rgba(0,0,0,0.18))",
                animation: "uniSpin 1.6s linear infinite",
                pointerEvents: "none",
              }}>💖</div>
            ))}

            {/* obstakels */}
            {obstaclesRef.current.map(o => (
              <div key={o.id} aria-hidden="true" style={{
                position: "absolute",
                left: o.x, top: o.y,
                width: o.w, height: o.h,
                pointerEvents: "none",
                display: "flex", flexDirection: "column",
                alignItems: "center", justifyContent: "flex-end",
              }}>
                {o.stack === 2 && (
                  <div style={{
                    fontSize: o.ob.h * 0.95, lineHeight: 1,
                    filter: "drop-shadow(2px 2px 0 rgba(0,0,0,0.22))",
                  }}>{o.ob.e}</div>
                )}
                <div style={{
                  fontSize: o.ob.h * 0.95, lineHeight: 1,
                  filter: "drop-shadow(3px 3px 0 rgba(0,0,0,0.22))",
                }}>{o.ob.e}</div>
              </div>
            ))}

            {/* speler, Allie op de eenhoorn */}
            <div style={{
              position: "absolute",
              left: PLAYER_X, top: playerY,
              width: PLAYER_W, height: PLAYER_H,
              transform: `rotate(${inAir ? -8 : Math.sin(distRef.current / 90) * 1.2}deg) translateY(${onGroundRef.current ? Math.sin(distRef.current / 60) * 2 : 0}px)`,
              filter: "drop-shadow(4px 4px 0 rgba(0,0,0,0.25))",
              pointerEvents: "none",
            }}>
              <img src="/assets/unicorn.png" alt="Allie op de eenhoorn"
                style={{ width: "100%", height: "100%", objectFit: "contain", display: "block" }} />
            </div>

            {/* grondbalk met strepen */}
            <div aria-hidden="true" style={{
              position: "absolute",
              left: 0, top: FLOOR_Y,
              width: FIELD_W, height: GROUND_H,
              background: "linear-gradient(180deg, #FF7AC1 0%, #E91E63 100%)",
              borderTop: "4px solid #1A1A1A",
              overflow: "hidden",
            }}>
              <div style={{
                position: "absolute",
                left: -groundOffsetRef.current,
                top: 14,
                width: FIELD_W + 120, height: 6,
                backgroundImage: "repeating-linear-gradient(90deg, #FFF 0 22px, transparent 22px 60px)",
                opacity: 0.7,
              }} />
              <div style={{
                position: "absolute",
                left: -groundOffsetRef.current * 0.6, bottom: 10,
                width: FIELD_W + 120, height: 4,
                backgroundImage: "repeating-linear-gradient(90deg, #FFD23F 0 14px, transparent 14px 36px)",
                opacity: 0.85,
              }} />
            </div>

            {/* schade-flits */}
            {flashRef.current > 0 && (
              <div aria-hidden="true" style={{
                position: "absolute", inset: 0,
                background: "rgba(255,255,255,1)",
                opacity: flashRef.current,
                pointerEvents: "none",
              }} />
            )}

            {/* start-overlay */}
            {!running && !done && (
              <div style={{
                position: "absolute", inset: 0,
                background: "rgba(255, 200, 230, 0.85)",
                display: "flex", flexDirection: "column",
                alignItems: "center", justifyContent: "center",
                gap: 14, padding: 20, textAlign: "center",
              }}>
                <div style={{
                  fontFamily: "'Bangers', sans-serif",
                  fontSize: 64, lineHeight: 1,
                  color: "#E91E63",
                  WebkitTextStroke: "2.5px #1A1A1A",
                  textShadow: "5px 5px 0 #1A1A1A",
                  letterSpacing: "0.03em",
                  transform: "rotate(-2deg)",
                }}>UNICORN-RACE</div>
                <div style={{
                  fontFamily: "'Bangers', sans-serif",
                  fontSize: 26, color: "#7E57FF",
                  WebkitTextStroke: "1px #1A1A1A",
                  textShadow: "2px 2px 0 #1A1A1A",
                  letterSpacing: "0.04em",
                }}>VOOR ALLIE ✨💖✨</div>
                <div style={{
                  background: "#FFF", border: "4px solid #1A1A1A",
                  boxShadow: "5px 5px 0 #1A1A1A",
                  padding: "12px 20px",
                  fontFamily: "'Patrick Hand', cursive", fontSize: 18,
                  maxWidth: 520, lineHeight: 1.35,
                }}>
                  {diff.obstacles === false ? (
                    <>Pak alle <b>💖 hartjes</b> die je tegenkomt! Geen snoepjes
                    om over te springen, gewoon lekker rijden. Tik of druk op
                    <b> spatie</b> voor een sprongetje.</>
                  ) : (
                    <>Spring met <b>spatie</b>, <b>↑</b> of een <b>tik</b> over
                    de snoepjes. Pak <b>💖 hartjes</b> voor bonuspunten. Twee
                    sprongen = dubbele sprong!</>
                  )}
                </div>

                <div style={{
                  display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
                }}>
                  <div style={{
                    fontFamily: "'Bangers', sans-serif",
                    fontSize: 18, color: "#1A1A1A",
                    letterSpacing: "0.1em",
                  }}>KIES JE SNELHEID</div>
                  <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "center" }}>
                    {Object.entries(DIFFICULTIES).map(([key, d]) => (
                      <button key={key}
                        onClick={() => setDifficulty(key)}
                        style={{
                          background: difficulty === key ? d.color : "#FFF",
                          color: difficulty === key ? "#FFF" : "#1A1A1A",
                          border: "4px solid #1A1A1A",
                          boxShadow: difficulty === key ? "2px 2px 0 #1A1A1A" : "4px 4px 0 #1A1A1A",
                          padding: "8px 14px",
                          fontFamily: "'Bangers', sans-serif",
                          fontSize: 18, letterSpacing: "0.05em",
                          cursor: "pointer",
                          WebkitTextStroke: difficulty === key ? "0.8px #1A1A1A" : 0,
                          textShadow: difficulty === key ? "1.5px 1.5px 0 #1A1A1A" : "none",
                          transform: difficulty === key ? "translate(2px,2px)" : "none",
                          display: "inline-flex", alignItems: "center", gap: 6,
                          transition: "all 0.1s",
                        }}>
                        <span style={{ fontSize: 18, WebkitTextStroke: 0, textShadow: "none" }}>{d.icon}</span>
                        {d.label.toUpperCase()}
                      </button>
                    ))}
                  </div>
                </div>

                <button onClick={start} style={{
                  background: "linear-gradient(180deg, #FF7AC1 0%, #E91E63 60%, #B91566 100%)",
                  color: "#FFF",
                  fontFamily: "'Bangers', sans-serif",
                  fontSize: 32, letterSpacing: "0.05em",
                  padding: "14px 36px",
                  border: "5px solid #1A1A1A",
                  boxShadow: "6px 6px 0 #1A1A1A",
                  cursor: "pointer",
                  WebkitTextStroke: "1.2px #1A1A1A",
                  textShadow: "2px 2px 0 #1A1A1A",
                }}>🦄 RIJDEN!</button>
              </div>
            )}

            {/* game-over */}
            {done && (
              <div style={{
                position: "absolute", inset: 0,
                background: "rgba(126, 87, 255, 0.88)",
                display: "flex", flexDirection: "column",
                alignItems: "center", justifyContent: "center",
                gap: 12, padding: 20, textAlign: "center",
                color: "#FFF",
              }}>
                <div style={{
                  fontFamily: "'Bangers', sans-serif",
                  fontSize: 60, lineHeight: 1,
                  color: "#FFD23F",
                  WebkitTextStroke: "2.4px #1A1A1A",
                  textShadow: "5px 5px 0 #1A1A1A",
                  letterSpacing: "0.03em",
                  transform: "rotate(-2deg)",
                }}>OEPS!</div>
                <div style={{
                  fontFamily: "'Patrick Hand', cursive",
                  fontSize: 22,
                }}>De eenhoorn struikelde over een snoepje.</div>
                <div style={{
                  display: "flex", gap: 14, marginTop: 8, flexWrap: "wrap",
                  justifyContent: "center",
                }}>
                  <div style={{
                    background: "#FFD23F", color: "#1A1A1A",
                    border: "4px solid #1A1A1A", boxShadow: "4px 4px 0 #1A1A1A",
                    padding: "8px 18px",
                    fontFamily: "'Bangers', sans-serif", fontSize: 24,
                  }}>✨ {Math.floor(scoreRef.current)}</div>
                  <div style={{
                    background: "#FF4FA3", color: "#FFF",
                    border: "4px solid #1A1A1A", boxShadow: "4px 4px 0 #1A1A1A",
                    padding: "8px 18px",
                    fontFamily: "'Bangers', sans-serif", fontSize: 24,
                  }}>💖 {hearts}</div>
                  <div style={{
                    background: "#7E57FF", color: "#FFF",
                    border: "4px solid #FFD23F", boxShadow: "4px 4px 0 #1A1A1A",
                    padding: "8px 18px",
                    fontFamily: "'Bangers', sans-serif", fontSize: 24,
                  }}>🏆 {best}</div>
                </div>
                <button onClick={start} style={{
                  marginTop: 8,
                  background: "linear-gradient(180deg, #FF7AC1 0%, #E91E63 60%, #B91566 100%)",
                  color: "#FFF",
                  fontFamily: "'Bangers', sans-serif",
                  fontSize: 28, letterSpacing: "0.05em",
                  padding: "12px 28px",
                  border: "5px solid #1A1A1A",
                  boxShadow: "5px 5px 0 #1A1A1A",
                  cursor: "pointer",
                  WebkitTextStroke: "1.1px #1A1A1A",
                  textShadow: "2px 2px 0 #1A1A1A",
                }}>🦄 NOG EEN KEER!</button>
              </div>
            )}
          </div>
        </div>
      </div>

      <style>{`
        @keyframes uniSpin {
          0%, 100% { transform: translateY(0) rotate(-6deg) scale(1); }
          50%      { transform: translateY(-4px) rotate(8deg) scale(1.06); }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { UnicornRace });
