// 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%)",
    accent: "#d8c088",
    detail: "wide icy rings",
    shortDetail: "icy rings",
    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%)",
    accent: "#d8b080",
    detail: "stormy cloud bands",
    shortDetail: "cloud bands",
    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%)",
    accent: "#d46a3a",
    detail: "rusty dust world",
    shortDetail: "red dust",
    happy: "Mars puffs a happy dust cloud!",
  },
];

function getPetFeederPlanetModel(planetId) {
  if (!Array.isArray(window.PLANETS)) return null;
  return window.PLANETS.find((planet) => planet.id === planetId) || null;
}

function PetFeederPlanetArt({ planet, animated }) {
  const model = getPetFeederPlanetModel(planet.id);
  const isSaturn = planet.id === "saturn";
  const size = isSaturn
    ? {
        width: "clamp(150px, 36vw, 300px)",
        height: "clamp(112px, 26vw, 214px)",
      }
    : {
        width: "clamp(116px, 26vw, 214px)",
        height: "clamp(116px, 26vw, 214px)",
      };
  const shellStyle = {
    width: size.width,
    height: size.height,
    position: "relative",
    display: "grid",
    placeItems: "center",
    filter: `drop-shadow(0 0 34px ${planet.accent || "#ffffff"}55)`,
    transformOrigin: "center",
    animation: animated ? "planet-dance-bob 0.78s ease-in-out infinite" : "none",
    "--pet-planet-color": planet.accent || "#ffffff",
  };

  if (model && typeof Planet3D === "function") {
    return (
      <div
        className={`pet-feeder-planet-detail pet-feeder-planet-${planet.id}`}
        style={shellStyle}
        aria-label={`${planet.name}: ${planet.detail}`}
      >
        <div className="pet-feeder-planet-halo" aria-hidden="true" />
        <Planet3D
          planet={model}
          detail={true}
          allowOrbit={false}
          className="pet-feeder-planet-canvas"
          style={{
            width: "100%",
            height: "100%",
            pointerEvents: "none",
          }}
        />
        <span className="pet-feeder-planet-detail-label">{planet.shortDetail || planet.detail}</span>
      </div>
    );
  }

  return (
    <div
      className={`pet-feeder-planet-detail pet-feeder-planet-fallback pet-feeder-planet-${planet.id}`}
      style={{
        ...shellStyle,
        borderRadius: "50%",
        background: planet.surface,
      }}
      aria-label={`${planet.name}: ${planet.detail}`}
    >
      <div className="pet-feeder-planet-halo" aria-hidden="true" />
      {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",
          }}
        />
      )}
      {planet.id === "jupiter" && <div className="pet-feeder-jupiter-spot" />}
      {planet.id === "mars" && (
        <>
          <div className="pet-feeder-mars-cap cap-north" />
          <div className="pet-feeder-mars-cap cap-south" />
          <div className="pet-feeder-mars-canyon" />
        </>
      )}
      <span className="pet-feeder-planet-detail-label">{planet.shortDetail || planet.detail}</span>
    </div>
  );
}

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 makePetFeederTargets() {
  return { saturn: 2, jupiter: 1, mars: 3 };
}

function PlanetPetFeederLevel({ onExit }) {
  const [tray, setTray] = useState(() => shufflePetFeederTray());
  const [fed, setFed] = useState({ saturn: 0, jupiter: 0, mars: 0 });
  const [targets, setTargets] = useState(() => makePetFeederTargets());
  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 feastTotal = PET_FEEDER_PLANETS.reduce(
    (sum, planet) => sum + (targets[planet.id] || 0),
    0,
  );
  const won = PET_FEEDER_PLANETS.every(
    (planet) => fed[planet.id] >= (targets[planet.id] || 0),
  );

  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 feedPlanetWithChip(landed, droppedKind, droppedUid) {
    if (!landed) return false;
    if (landed.food === droppedKind) {
      const target = targets[landed.id] || 0;
      const currentFed = fed[landed.id] || 0;
      const alreadyFull = currentFed >= target;
      const food = PET_FEEDER_FOODS.find((f) => f.kind === droppedKind);
      if (alreadyFull) {
        setGiggle({
          planetId: landed.id,
          message: `${landed.name} is full and happy!`,
          sparkle: "😊",
        });
        setBounce(landed.id);
        if (giggleTimerRef.current) clearTimeout(giggleTimerRef.current);
        if (bounceTimerRef.current) clearTimeout(bounceTimerRef.current);
        giggleTimerRef.current = setTimeout(() => setGiggle(null), 1200);
        bounceTimerRef.current = setTimeout(() => setBounce(null), 600);
        if (typeof playKidSound === "function") playKidSound("boop");
        return true;
      }
      const nextFed = currentFed + 1;
      const nextScore = Math.min(feastTotal, score + 1);
      setScore(nextScore);
      setFed((prev) => ({ ...prev, [landed.id]: nextFed }));
      setTray((prev) => prev.filter((c) => c.uid !== droppedUid));
      setGiggle({
        planetId: landed.id,
        message:
          nextFed >= target ? `${landed.name} is full and happy!` : 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");
      return true;
    }

    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");
    return false;
  }

  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) {
      landed = PET_FEEDER_PLANETS.find(
        (planet) =>
          planet.food === droppedKind &&
          (fed[planet.id] || 0) < (targets[planet.id] || 0),
      );
    }
    feedPlanetWithChip(landed, droppedKind, droppedUid);
  }

  function resetGame() {
    setTray(shufflePetFeederTray());
    setFed({ saturn: 0, jupiter: 0, mars: 0 });
    setTargets(makePetFeederTargets());
    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}
      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,
          minWidth: 44,
          minHeight: 44,
          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} / {feastTotal}
        </div>
        <div
          style={{
            padding: "8px 12px",
            background: "rgba(82, 180, 255, 0.16)",
            border: "1px solid rgba(150, 220, 255, 0.3)",
            borderRadius: 12,
            fontSize: 13,
            fontWeight: 700,
            maxWidth: 190,
            lineHeight: 1.25,
          }}
        >
          Drag path: pick up, move, let go on the matching planet.
        </div>
        {won && (
          <button
            onClick={resetGame}
            style={{
              padding: "10px 18px",
              minWidth: 44,
              minHeight: 44,
              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,
        }}
      >
        Match each treat to the planet that wants it.
      </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 target = targets[planet.id] || 0;
          const full = fedCount >= target;
          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: planet.id === "saturn" ? "clamp(150px, 36vw, 300px)" : "clamp(116px, 26vw, 214px)",
                  height: planet.id === "saturn" ? "clamp(112px, 26vw, 214px)" : "clamp(116px, 26vw, 214px)",
                  position: "relative",
                  display: "grid",
                  placeItems: "center",
                  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",
                }}
              >
                <PetFeederPlanetArt planet={planet} animated={won} />
                {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,
                }}
              >
                {Array.from({ length: target }).map((_, i) => (
                  <span key={i} style={{ opacity: i < fedCount ? 1 : 0.25 }}>
                    {PET_FEEDER_FOODS.find((f) => f.kind === planet.food).glyph}
                  </span>
                ))}
              </div>
              <div
                style={{
                  fontSize: 13,
                  fontWeight: 800,
                  color: full ? "#ffe46b" : "rgba(255,255,255,0.74)",
                }}
              >
                Wants {target}
              </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",
            }}
          >
            🎉 Planet feast complete! ({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}
              role="button"
              tabIndex={0}
              aria-label={`Feed ${food.label}`}
              onPointerDown={(event) => startDrag(chip, event)}
              onKeyDown={(event) => {
                if (event.key !== "Enter" && event.key !== " ") return;
                event.preventDefault();
                const landed = PET_FEEDER_PLANETS.find(
                  (planet) =>
                    planet.food === chip.kind &&
                    (fed[planet.id] || 0) < (targets[planet.id] || 0),
                );
                feedPlanetWithChip(landed, chip.kind, chip.uid);
              }}
              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>{`
        .pet-feeder-planet-detail {
          isolation: isolate;
        }

        .pet-feeder-planet-detail canvas {
          width: 100% !important;
          height: 100% !important;
        }

        .pet-feeder-planet-halo {
          position: absolute;
          inset: 7%;
          z-index: -1;
          border-radius: 999px;
          background:
            radial-gradient(circle at 42% 38%, var(--pet-planet-color), transparent 62%),
            radial-gradient(circle, rgba(255, 255, 255, 0.18), transparent 66%);
          opacity: 0.32;
          filter: blur(12px);
        }

        .pet-feeder-planet-detail-label {
          position: absolute;
          left: 50%;
          bottom: 4px;
          transform: translateX(-50%);
          max-width: calc(100% - 20px);
          min-width: min-content;
          padding: 4px 9px;
          border: 1px solid color-mix(in srgb, var(--pet-planet-color) 58%, transparent);
          border-radius: 999px;
          background: rgba(5, 4, 18, 0.72);
          color: #fff7d8;
          font-size: 11px;
          font-weight: 800;
          letter-spacing: 0.02em;
          line-height: 1;
          text-align: center;
          white-space: nowrap;
          box-shadow: 0 8px 22px rgba(0, 0, 0, 0.32);
          pointer-events: none;
        }

        .pet-feeder-planet-fallback {
          overflow: visible;
          box-shadow:
            inset -22px -26px 42px rgba(0, 0, 0, 0.34),
            inset 18px 16px 28px rgba(255, 255, 255, 0.16);
        }

        .pet-feeder-planet-fallback::after {
          content: "";
          position: absolute;
          inset: 6%;
          border-radius: 50%;
          background:
            radial-gradient(circle at 32% 26%, rgba(255, 255, 255, 0.34), transparent 18%),
            radial-gradient(circle at 70% 78%, rgba(0, 0, 0, 0.22), transparent 42%);
          pointer-events: none;
          mix-blend-mode: screen;
        }

        .pet-feeder-jupiter-spot {
          position: absolute;
          right: 22%;
          top: 55%;
          width: 30%;
          height: 16%;
          border-radius: 50%;
          background: radial-gradient(circle at 38% 35%, #ffd4a6, #b84429 58%, #6c2418 100%);
          box-shadow: inset -5px -4px 10px rgba(0, 0, 0, 0.28);
          transform: rotate(-8deg);
        }

        .pet-feeder-mars-cap {
          position: absolute;
          left: 50%;
          width: 34%;
          height: 13%;
          border-radius: 50%;
          background: rgba(255, 235, 205, 0.88);
          filter: blur(0.4px);
        }

        .pet-feeder-mars-cap.cap-north {
          top: 7%;
          transform: translateX(-50%) rotate(7deg);
        }

        .pet-feeder-mars-cap.cap-south {
          bottom: 8%;
          transform: translateX(-50%) rotate(-6deg);
          opacity: 0.5;
        }

        .pet-feeder-mars-canyon {
          position: absolute;
          left: 18%;
          top: 46%;
          width: 56%;
          height: 10%;
          border-radius: 50%;
          border-top: 5px solid rgba(92, 28, 18, 0.56);
          transform: rotate(-16deg);
        }

        @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>
  );
}
