// hartjes-regen.jsx, Allie tikt op vallende hartjes en sterren.
// Geen obstakels, geen verliesscherm, eindeloos rustig spel voor heel jonge
// kinderen. Hartjes geven 1 punt, sterren 3, regenbogen 5.

function HartjesRegen({ onClose }) {
  const FIELD_W = 900;
  const FIELD_H = 540;

  const [score, setScore] = React.useState(0);
  const [best, setBest] = React.useState(() => {
    try { return parseInt(localStorage.getItem("hartjes-regen-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 <= 600);

  const wrapRef = React.useRef(null);
  const fieldRef = React.useRef(null);
  const itemsRef = React.useRef([]);
  const sparklesRef = React.useRef([]);
  const cloudsRef = React.useRef([]);
  const unicornXRef = React.useRef(FIELD_W / 2);
  const unicornDirRef = React.useRef(1);
  const lastSpawnRef = React.useRef(0);
  const lastFrameRef = React.useRef(0);
  const idRef = React.useRef(0);
  const scoreRef = React.useRef(0);

  const KINDS = [
    { e: "💖", points: 1, weight: 0.65, size: 56, fall: 90 },
    { e: "⭐", points: 3, weight: 0.25, size: 56, fall: 110 },
    { e: "🌈", points: 5, weight: 0.10, size: 64, fall: 70 },
  ];

  function pickKind() {
    const r = Math.random();
    let acc = 0;
    for (const k of KINDS) { acc += k.weight; if (r <= acc) return k; }
    return KINDS[0];
  }

  function spawnSparkles(x, y, n, color) {
    for (let i = 0; i < n; i++) {
      sparklesRef.current.push({
        id: ++idRef.current,
        x, y,
        vx: (Math.random() - 0.5) * 240,
        vy: -120 - Math.random() * 180,
        life: 0.8 + Math.random() * 0.4,
        max: 1.2,
        color,
        size: 4 + Math.random() * 6,
      });
    }
  }

  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]);

  React.useEffect(() => {
    cloudsRef.current = [
      { id: ++idRef.current, x: 100, y: 50, s: 1, sp: 8 },
      { id: ++idRef.current, x: 380, y: 30, s: 0.8, sp: 6 },
      { id: ++idRef.current, x: 640, y: 70, s: 1.2, sp: 10 },
      { id: ++idRef.current, x: 820, y: 20, s: 0.9, sp: 7 },
    ];
    lastFrameRef.current = performance.now();
    let raf;
    function frame(t) {
      const dt = Math.min(0.05, (t - lastFrameRef.current) / 1000);
      lastFrameRef.current = t;

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

      // unicorn loopt traag heen-en-weer onderin (decoratief)
      unicornXRef.current += unicornDirRef.current * 60 * dt;
      if (unicornXRef.current > FIELD_W - 160) unicornDirRef.current = -1;
      if (unicornXRef.current < 20) unicornDirRef.current = 1;

      // items spawnen
      lastSpawnRef.current += dt;
      const spawnGap = 0.55 + Math.random() * 0.45;
      if (lastSpawnRef.current >= spawnGap) {
        lastSpawnRef.current = 0;
        const k = pickKind();
        itemsRef.current.push({
          id: ++idRef.current,
          x: 30 + Math.random() * (FIELD_W - 60),
          y: -k.size,
          vx: (Math.random() - 0.5) * 30,
          vy: k.fall + Math.random() * 30,
          k,
          rot: 0,
          rotSp: (Math.random() - 0.5) * 60,
          got: false,
        });
      }

      // beweeg items
      for (const it of itemsRef.current) {
        it.x += it.vx * dt;
        it.y += it.vy * dt;
        it.rot += it.rotSp * dt;
      }
      itemsRef.current = itemsRef.current.filter(it => !it.got && it.y < FIELD_H + 80);

      // beweeg sparkles
      for (const s of sparklesRef.current) {
        s.x += s.vx * dt;
        s.y += s.vy * dt;
        s.vy += 320 * dt;
        s.life -= dt;
      }
      sparklesRef.current = sparklesRef.current.filter(s => s.life > 0);

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

  function onFieldPointerDown(e) {
    if (!fieldRef.current) return;
    const r = fieldRef.current.getBoundingClientRect();
    const px = (e.clientX - r.left) / scale;
    const py = (e.clientY - r.top) / scale;
    e.preventDefault();
    let caught = null;
    for (const it of itemsRef.current) {
      if (it.got) continue;
      const cx = it.x + it.k.size / 2;
      const cy = it.y + it.k.size / 2;
      const radius = it.k.size * 0.7;
      const dx = px - cx, dy = py - cy;
      if (dx * dx + dy * dy <= radius * radius) {
        if (!caught || it.y > caught.y) caught = it;
      }
    }
    if (caught) {
      caught.got = true;
      scoreRef.current += caught.k.points;
      setScore(scoreRef.current);
      if (scoreRef.current > best) {
        setBest(scoreRef.current);
        try { localStorage.setItem("hartjes-regen-best", String(scoreRef.current)); } catch {}
      }
      const color = caught.k.e === "💖" ? "#FF4FA3" : caught.k.e === "⭐" ? "#FFD23F" : "#B36BFF";
      spawnSparkles(caught.x + caught.k.size / 2, caught.y + caught.k.size / 2, 10, color);
    }
  }

  return (
    <div onClick={e => e.stopPropagation()} style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "linear-gradient(180deg, #C9F2FF 0%, #FFE4F8 50%, #FFB6E1 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" : "HARTJES-REGEN"}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: narrow ? 6 : 10 }}>
          <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",
          }}>💖 {score}</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={onFieldPointerDown}
            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 60%, #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: "pointer",
            }}>

            {/* regenboog op de achtergrond */}
            <div aria-hidden="true" style={{
              position: "absolute",
              left: -120, top: 60,
              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.45,
              clipPath: `polygon(0 0, 100% 0, 100% 75%, 0 75%)`,
              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>
            ))}

            {/* vallende items */}
            {itemsRef.current.map(it => (
              <div key={it.id} aria-hidden="true" style={{
                position: "absolute",
                left: it.x, top: it.y,
                width: it.k.size, height: it.k.size,
                fontSize: it.k.size, lineHeight: 1,
                transform: `rotate(${it.rot}deg)`,
                filter: "drop-shadow(3px 3px 0 rgba(0,0,0,0.18))",
                pointerEvents: "none",
                animation: "hrFloat 1.6s ease-in-out infinite",
              }}>{it.k.e}</div>
            ))}

            {/* sparkles */}
            {sparklesRef.current.map(s => (
              <div key={s.id} aria-hidden="true" style={{
                position: "absolute",
                left: s.x - s.size / 2, top: s.y - s.size / 2,
                width: s.size, height: s.size,
                background: s.color,
                borderRadius: "50%",
                opacity: Math.max(0, s.life / s.max),
                boxShadow: `0 0 8px ${s.color}`,
                pointerEvents: "none",
              }} />
            ))}

            {/* unicorn die rondloopt onderin */}
            <div style={{
              position: "absolute",
              left: unicornXRef.current, top: FIELD_H - 140,
              width: 140, height: 120,
              transform: `scaleX(${unicornDirRef.current})`,
              filter: "drop-shadow(4px 4px 0 rgba(0,0,0,0.22))",
              pointerEvents: "none",
            }}>
              <img src="/assets/unicorn.png" alt="Allie op de eenhoorn"
                style={{ width: "100%", height: "100%", objectFit: "contain", display: "block" }} />
            </div>

            {/* grasstrook */}
            <div aria-hidden="true" style={{
              position: "absolute",
              left: 0, top: FIELD_H - 28,
              width: FIELD_W, height: 28,
              background: "linear-gradient(180deg, #FF7AC1 0%, #E91E63 100%)",
              borderTop: "4px solid #1A1A1A",
            }} />
          </div>
        </div>
      </div>

      <style>{`
        @keyframes hrFloat {
          0%, 100% { filter: drop-shadow(3px 3px 0 rgba(0,0,0,0.18)) brightness(1); }
          50%      { filter: drop-shadow(3px 3px 0 rgba(0,0,0,0.18)) brightness(1.15); }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { HartjesRegen });
