// Planet Pet-Feeder — kid mini-game.
// Saturn loves ice cubes, Jupiter loves storm-clouds, Mars loves dust.
// Drag a food chip from the tray onto its matching planet for a giggle.

const PET_FEEDER_PLANETS = [
  {
    id: "saturn",
    name: "Saturn",
    food: "ice",
    surface:
      "radial-gradient(circle at 35% 30%, #f8e7b9 0%, #d6b07a 45%, #8a6230 100%)",
    ring: true,
    happy: "Saturn slurps the ice — tee hee!",
  },
  {
    id: "jupiter",
    name: "Jupiter",
    food: "storm",
    surface:
      "radial-gradient(circle at 35% 30%, #fde2c0 0%, #d8945a 35%, #a14a2c 70%, #6b2a1a 100%)",
    bands: true,
    happy: "Jupiter rumbles with thunder — boom giggle!",
  },
  {
    id: "mars",
    name: "Mars",
    food: "dust",
    surface:
      "radial-gradient(circle at 35% 30%, #f4a075 0%, #c84a25 50%, #6b1d10 100%)",
    happy: "Mars puffs a happy dust cloud!",
  },
];

const PET_FEEDER_FOODS = [
  {
    kind: "ice",
    glyph: "🧊",
    label: "Ice cubes",
    sparkle: "❄️",
  },
  {
    kind: "storm",
    glyph: "⛈️",
    label: "Storm cloud",
    sparkle: "⚡",
  },
  {
    kind: "dust",
    glyph: "🟫",
    label: "Dust puff",
    sparkle: "💨",
  },
];

function shufflePetFeederTray() {
  const tray = [];
  let id = 0;
  for (const food of PET_FEEDER_FOODS) {
    for (let i = 0; i < 3; i += 1) {
      tray.push({ uid: `f${id++}`, kind: food.kind });
    }
  }
  for (let i = tray.length - 1; i > 0; i -= 1) {
    const j = Math.floor(Math.random() * (i + 1));
    [tray[i], tray[j]] = [tray[j], tray[i]];
  }
  return tray;
}

function PlanetPetFeederLevel({ onExit }) {
  const [tray, setTray] = useState(() => shufflePetFeederTray());
  const [fed, setFed] = useState({ saturn: 0, jupiter: 0, mars: 0 });
  const [score, setScore] = useState(0);
  const [misses, setMisses] = useState(0);
  const [drag, setDrag] = useState(null);
  const [giggle, setGiggle] = useState(null);
  const [shake, setShake] = useState(null);
  const [bounce, setBounce] = useState(null);
  const planetRefs = useRef({});
  const stageRef = useRef(null);
  const giggleTimerRef = useRef(null);
  const shakeTimerRef = useRef(null);
  const bounceTimerRef = useRef(null);

  const won = score === 9;

  useEffect(
    () => () => {
      if (giggleTimerRef.current) clearTimeout(giggleTimerRef.current);
      if (shakeTimerRef.current) clearTimeout(shakeTimerRef.current);
      if (bounceTimerRef.current) clearTimeout(bounceTimerRef.current);
    },
    [],
  );

  function pointFromEvent(event) {
    if (event.touches && event.touches[0]) {
      return { x: event.touches[0].clientX, y: event.touches[0].clientY };
    }
    return { x: event.clientX, y: event.clientY };
  }

  function startDrag(chip, event) {
    event.preventDefault();
    const point = pointFromEvent(event);
    setDrag({ uid: chip.uid, kind: chip.kind, x: point.x, y: point.y });
    if (typeof playKidSound === "function") playKidSound("pop");
  }

  function moveDrag(event) {
    if (!drag) return;
    event.preventDefault();
    const point = pointFromEvent(event);
    setDrag((prev) => (prev ? { ...prev, x: point.x, y: point.y } : prev));
  }

  function endDrag(event) {
    if (!drag) return;
    event.preventDefault();
    const point = pointFromEvent(event);
    let landed = null;
    for (const planet of PET_FEEDER_PLANETS) {
      const node = planetRefs.current[planet.id];
      if (!node) continue;
      const rect = node.getBoundingClientRect();
      const cx = rect.left + rect.width / 2;
      const cy = rect.top + rect.height / 2;
      const dx = point.x - cx;
      const dy = point.y - cy;
      const radius = Math.min(rect.width, rect.height) / 2 + 14;
      if (dx * dx + dy * dy <= radius * radius) {
        landed = planet;
        break;
      }
    }
    const droppedKind = drag.kind;
    const droppedUid = drag.uid;
    setDrag(null);
    if (!landed) return;
    if (landed.food === droppedKind) {
      setScore((s) => s + 1);
      setFed((prev) => ({ ...prev, [landed.id]: prev[landed.id] + 1 }));
      setTray((prev) => prev.filter((c) => c.uid !== droppedUid));
      const food = PET_FEEDER_FOODS.find((f) => f.kind === droppedKind);
      setGiggle({
        planetId: landed.id,
        message: landed.happy,
        sparkle: food ? food.sparkle : "✨",
      });
      setBounce(landed.id);
      if (giggleTimerRef.current) clearTimeout(giggleTimerRef.current);
      if (bounceTimerRef.current) clearTimeout(bounceTimerRef.current);
      giggleTimerRef.current = setTimeout(() => setGiggle(null), 1400);
      bounceTimerRef.current = setTimeout(() => setBounce(null), 600);
      if (typeof playKidSound === "function") playKidSound("chime");
    } else {
      setMisses((m) => m + 1);
      setShake(landed.id);
      if (shakeTimerRef.current) clearTimeout(shakeTimerRef.current);
      shakeTimerRef.current = setTimeout(() => setShake(null), 450);
      if (typeof playKidSound === "function") playKidSound("buzz");
    }
  }

  function resetGame() {
    setTray(shufflePetFeederTray());
    setFed({ saturn: 0, jupiter: 0, mars: 0 });
    setScore(0);
    setMisses(0);
    setDrag(null);
    setGiggle(null);
    setShake(null);
    setBounce(null);
  }

  return (
    <div
      className="pet-feeder-stage"
      ref={stageRef}
      onPointerMove={moveDrag}
      onPointerUp={endDrag}
      onPointerCancel={endDrag}
      onTouchMove={moveDrag}
      onTouchEnd={endDrag}
      style={{
        position: "fixed",
        inset: 0,
        background:
          "radial-gradient(circle at 50% 25%, #1a1547 0%, #0a0820 70%, #03020c 100%)",
        color: "#fff",
        fontFamily: "system-ui, -apple-system, sans-serif",
        userSelect: "none",
        touchAction: "none",
        overflow: "hidden",
      }}
    >
      <button
        onClick={onExit}
        style={{
          position: "absolute",
          top: 18,
          left: 18,
          padding: "10px 18px",
          borderRadius: 999,
          border: "2px solid rgba(255,255,255,0.4)",
          background: "rgba(0,0,0,0.4)",
          color: "#fff",
          fontSize: 16,
          fontWeight: 600,
          cursor: "pointer",
          zIndex: 10,
        }}
      >
        ← Back to planets
      </button>

      <div
        style={{
          position: "absolute",
          top: 24,
          right: 24,
          display: "flex",
          gap: 12,
          alignItems: "center",
          zIndex: 10,
        }}
      >
        <div
          style={{
            padding: "8px 14px",
            background: "rgba(255,255,255,0.12)",
            borderRadius: 12,
            fontSize: 18,
            fontWeight: 700,
          }}
        >
          🍴 Fed: {score} / 9
        </div>
        {won && (
          <button
            onClick={resetGame}
            style={{
              padding: "10px 18px",
              borderRadius: 12,
              border: "none",
              background: "#ffd95a",
              color: "#241400",
              fontWeight: 700,
              fontSize: 16,
              cursor: "pointer",
            }}
          >
            Play again
          </button>
        )}
      </div>

      <div
        style={{
          position: "absolute",
          top: 90,
          left: 0,
          right: 0,
          textAlign: "center",
          fontSize: 26,
          fontWeight: 700,
          letterSpacing: 0.5,
        }}
      >
        Feed the planets!
      </div>
      <div
        style={{
          position: "absolute",
          top: 130,
          left: 0,
          right: 0,
          textAlign: "center",
          fontSize: 16,
          opacity: 0.85,
        }}
      >
        Saturn loves ice • Jupiter loves storm clouds • Mars loves dust
      </div>

      <div
        style={{
          position: "absolute",
          top: "30%",
          left: 0,
          right: 0,
          display: "flex",
          justifyContent: "space-around",
          alignItems: "center",
        }}
      >
        {PET_FEEDER_PLANETS.map((planet) => {
          const fedCount = fed[planet.id];
          const full = fedCount >= 3;
          return (
            <div
              key={planet.id}
              style={{
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                gap: 10,
                position: "relative",
              }}
            >
              <div
                ref={(node) => {
                  planetRefs.current[planet.id] = node;
                }}
                style={{
                  width: 160,
                  height: 160,
                  borderRadius: "50%",
                  background: planet.surface,
                  boxShadow: "0 0 60px rgba(255,255,255,0.18)",
                  position: "relative",
                  transform:
                    bounce === planet.id
                      ? "scale(1.18)"
                      : shake === planet.id
                        ? "translateX(0)"
                        : "scale(1)",
                  transition: "transform 0.25s ease",
                  animation:
                    shake === planet.id ? "petfeeder-shake 0.45s ease" : "none",
                }}
              >
                {planet.ring && (
                  <div
                    style={{
                      position: "absolute",
                      top: "50%",
                      left: "-30%",
                      width: "160%",
                      height: "20%",
                      background:
                        "linear-gradient(90deg, transparent, #d4b67a 30%, #b8923f 50%, #d4b67a 70%, transparent)",
                      transform: "translateY(-50%) rotate(-18deg)",
                      borderRadius: "50%",
                      opacity: 0.85,
                      pointerEvents: "none",
                    }}
                  />
                )}
                {planet.bands && (
                  <div
                    style={{
                      position: "absolute",
                      inset: 0,
                      borderRadius: "50%",
                      background:
                        "repeating-linear-gradient(180deg, transparent 0 14px, rgba(0,0,0,0.18) 14px 22px)",
                      pointerEvents: "none",
                    }}
                  />
                )}
                {full && (
                  <div
                    style={{
                      position: "absolute",
                      top: -8,
                      right: -8,
                      width: 36,
                      height: 36,
                      borderRadius: "50%",
                      background: "#ffe46b",
                      color: "#241400",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      fontSize: 22,
                      boxShadow: "0 4px 14px rgba(0,0,0,0.4)",
                    }}
                  >
                    😊
                  </div>
                )}
              </div>
              <div
                style={{
                  fontSize: 18,
                  fontWeight: 700,
                  letterSpacing: 0.5,
                }}
              >
                {planet.name}
              </div>
              <div
                style={{
                  display: "flex",
                  gap: 4,
                  fontSize: 18,
                }}
              >
                {[0, 1, 2].map((i) => (
                  <span key={i} style={{ opacity: i < fedCount ? 1 : 0.25 }}>
                    {PET_FEEDER_FOODS.find((f) => f.kind === planet.food).glyph}
                  </span>
                ))}
              </div>
              {giggle && giggle.planetId === planet.id && (
                <div
                  style={{
                    position: "absolute",
                    top: -56,
                    left: "50%",
                    transform: "translateX(-50%)",
                    background: "rgba(255,255,255,0.95)",
                    color: "#1c1147",
                    padding: "8px 14px",
                    borderRadius: 14,
                    fontSize: 14,
                    fontWeight: 600,
                    whiteSpace: "nowrap",
                    boxShadow: "0 6px 20px rgba(0,0,0,0.35)",
                    pointerEvents: "none",
                    animation: "petfeeder-pop 1.4s ease",
                  }}
                >
                  {giggle.sparkle} {giggle.message}
                </div>
              )}
            </div>
          );
        })}
      </div>

      <div
        style={{
          position: "absolute",
          bottom: 0,
          left: 0,
          right: 0,
          padding: "20px 16px 28px",
          background:
            "linear-gradient(180deg, transparent, rgba(0,0,0,0.45) 30%)",
          display: "flex",
          flexWrap: "wrap",
          justifyContent: "center",
          gap: 10,
          minHeight: 130,
        }}
      >
        {tray.length === 0 && !won && (
          <div style={{ fontSize: 18, alignSelf: "center" }}>
            Tray empty — drag chips above onto planets
          </div>
        )}
        {won && (
          <div
            style={{
              fontSize: 22,
              fontWeight: 700,
              alignSelf: "center",
              color: "#ffe46b",
            }}
          >
            🎉 All planets fed! ({misses} oopsies)
          </div>
        )}
        {tray.map((chip) => {
          const food = PET_FEEDER_FOODS.find((f) => f.kind === chip.kind);
          const isDragging = drag && drag.uid === chip.uid;
          return (
            <div
              key={chip.uid}
              onPointerDown={(event) => startDrag(chip, event)}
              onTouchStart={(event) => startDrag(chip, event)}
              style={{
                width: 80,
                height: 80,
                borderRadius: 16,
                background: "rgba(255,255,255,0.16)",
                border: "2px solid rgba(255,255,255,0.4)",
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                justifyContent: "center",
                fontSize: 32,
                cursor: "grab",
                opacity: isDragging ? 0 : 1,
                transition: "transform 0.12s ease",
                touchAction: "none",
              }}
            >
              <span>{food.glyph}</span>
              <span style={{ fontSize: 10, marginTop: 4, opacity: 0.85 }}>
                {food.label}
              </span>
            </div>
          );
        })}
      </div>

      {drag && (
        <div
          style={{
            position: "fixed",
            left: drag.x - 40,
            top: drag.y - 40,
            width: 80,
            height: 80,
            borderRadius: 16,
            background: "rgba(255,255,255,0.28)",
            border: "2px solid rgba(255,255,255,0.7)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            fontSize: 36,
            pointerEvents: "none",
            zIndex: 20,
            boxShadow: "0 8px 24px rgba(0,0,0,0.4)",
          }}
        >
          {PET_FEEDER_FOODS.find((f) => f.kind === drag.kind).glyph}
        </div>
      )}

      <style>{`
        @keyframes petfeeder-pop {
          0% { transform: translateX(-50%) translateY(8px) scale(0.6); opacity: 0; }
          25% { transform: translateX(-50%) translateY(-4px) scale(1.08); opacity: 1; }
          75% { transform: translateX(-50%) translateY(-4px) scale(1); opacity: 1; }
          100% { transform: translateX(-50%) translateY(-12px) scale(0.95); opacity: 0; }
        }
        @keyframes petfeeder-shake {
          0%, 100% { transform: translateX(0); }
          20% { transform: translateX(-12px); }
          40% { transform: translateX(12px); }
          60% { transform: translateX(-8px); }
          80% { transform: translateX(8px); }
        }
      `}</style>
    </div>
  );
}
