// quiz-planet-sort.jsx
// Planet Sort level: tap-the-right-planet rounds. Loaded after quiz-helpers.jsx.

const PLANET_SORT_ROUNDS = [
  {
    prompt: "Tap the biggest planet.",
    fact: "Jupiter is the biggest planet in our solar system.",
    choices: ["mercury", "earth", "jupiter"],
    answer: "jupiter",
  },
  {
    prompt: "Tap the smallest planet.",
    fact: "Mercury is the smallest planet.",
    choices: ["venus", "mars", "mercury"],
    answer: "mercury",
  },
  {
    prompt: "Tap the biggest ice giant.",
    fact: "Uranus and Neptune are ice giants. Uranus is a little wider.",
    choices: ["earth", "uranus", "neptune"],
    answer: "uranus",
  },
  {
    prompt: "Tap the planet with the widest rings.",
    fact: "Saturn's bright rings are made of ice and rock.",
    choices: ["mars", "saturn", "venus"],
    answer: "saturn",
  },
  {
    prompt: "Tap the closest planet to the Sun.",
    fact: "Mercury orbits closest to the Sun.",
    choices: ["earth", "mercury", "neptune"],
    answer: "mercury",
  },
  {
    prompt: "Tap the farthest planet from the Sun.",
    fact: "Neptune is the farthest planet in our solar system.",
    choices: ["mars", "jupiter", "neptune"],
    answer: "neptune",
  },
];
function PlanetSortLevel({ onExit }) {
  const [roundIndex, setRoundIndex] = useState(0);
  const [message, setMessage] = useState({
    tone: "ready",
    text: "Tap the glowing planet.",
  });
  const [pickedId, setPickedId] = useState(null);
  const [missCount, setMissCount] = useState(0);
  const [finished, setFinished] = useState(false);
  const [choiceIndex, setChoiceIndex] = useState(0);
  const feedbackTimerRef = useRef(null);
  const round = PLANET_SORT_ROUNDS[roundIndex];
  const choices = resolveChoiceItems(round.choices, (id) =>
    PLANETS.find((planet) => planet.id === id),
  );
  const maxRadius = choices.length
    ? Math.max(...choices.map((planet) => planet.radius))
    : 1;
  const answerPlanet = choices.find((planet) => planet.id === round.answer);
  const selectedChoice = choiceSelectionState(
    choiceIndex,
    choices,
    (planet) => planet.name,
  );
  const planetChoiceState = (planet, index) =>
    [
      "planet-sort-card",
      selectedChoice.index === index ? "selected" : "",
      pickedId === planet.id
        ? planet.id === round.answer
          ? "correct"
          : "wrong"
        : missCount > 0 && planet.id === round.answer
          ? "hint"
          : !pickedId && planet.id === round.answer
            ? "hint"
            : "",
    ]
      .filter(Boolean)
      .join(" ");

  useEffect(() => {
    return () => clearChoiceFeedbackTimer(feedbackTimerRef);
  }, []);
  useEffect(() => {
    setChoiceIndex(0);
  }, [roundIndex]);
  useEffect(() => {
    setChoiceIndex((index) => clampChoiceIndex(index, choices.length));
  }, [choices.length]);

  const choose = (planet) => {
    if (!planet) return;
    if (finished) return;
    clearChoiceFeedbackTimer(feedbackTimerRef);
    setPickedId(planet.id);
    if (planet.id !== round.answer) {
      const nextMissCount = missCount + 1;
      setMissCount(nextMissCount);
      setMessage({
        tone: "try",
        text:
          nextMissCount >= 1 && answerPlanet
            ? `Good tap. Now try ${answerPlanet.name}.`
            : `${planet.name} is not this one. Try again.`,
      });
      playKidSound("pop");
      feedbackTimerRef.current = window.setTimeout(() => setPickedId(null), 900);
      return;
    }

    playKidSound("chime");
    setMissCount(0);
    const lastRound = roundIndex >= PLANET_SORT_ROUNDS.length - 1;
    setMessage({
      tone: "good",
      text: `${planet.name}! ${round.fact}`,
    });
    if (lastRound) {
      setFinished(true);
      window.SpaceExplorerFoundation?.celebrateGameFinish?.({
        gameId: "planet-sort",
        emoji: "🪐",
        title: "Space sorted!",
        message: "You matched the planets by their clues.",
      });
      return;
    }
    feedbackTimerRef.current = window.setTimeout(() => {
      setRoundIndex((i) => i + 1);
      setPickedId(null);
      setMissCount(0);
      setMessage({
        tone: "ready",
        text: "Nice! Try the next one.",
      });
    }, 950);
  };

  const reset = () => {
    clearChoiceFeedbackTimer(feedbackTimerRef);
    setRoundIndex(0);
    setFinished(false);
    setPickedId(null);
    setMissCount(0);
    setMessage({ tone: "ready", text: "Tap the glowing planet." });
  };

  useWindowKeyHandler(
    (event) => {
      handleChoiceNavigationKey(event, {
        choices,
        selectedChoice,
        disabled: finished,
        onMove: (delta) =>
          setChoiceIndex((index) => nextChoiceIndex(index, delta, choices.length)),
        onChoose: choose,
      });
    },
    !finished,
  );

  return (
    <section className="planet-sort-level" aria-label="Planet sorting game">
      <Starfield count={220} />
      <button className="planet-sort-back" onClick={onExit}>
        ← Back to planets
      </button>
      <div className="planet-sort-shell">
        <div className="planet-sort-copy">
          <span>Planet Sort</span>
          <h1>{finished ? "You sorted space!" : round.prompt}</h1>
          <p>
            {finished
              ? "Big planets have stronger gravity because they hold more stuff."
              : "Planets are different sizes. The helper glow shows one to try."}
          </p>
          <div
            className={`planet-sort-message ${message.tone}`}
            role="status"
            aria-live="polite"
          >
            {finished ? (
              <SafeAssetImage
                src={GENERATED_ASSETS.sparkleStar}
                alt=""
                context="PlanetSort:finishSparkle"
                fallbackText=""
              />
            ) : null}
            <strong>{message.text}</strong>
          </div>
          <div className="planet-sort-comparison" aria-label="Planet size comparison">
            <strong>Compare size</strong>
            {choices.map((planet) => (
              <span key={`compare-${planet.id}`}>
                <em>{planet.name}</em>
                <i>
                  <b style={{ width: `${(planet.radius / maxRadius) * 100}%` }} />
                </i>
              </span>
            ))}
          </div>
          <div className="planet-sort-progress" aria-label="Rounds">
            {PLANET_SORT_ROUNDS.map((item, index) => (
              <span
                key={`${item.answer}-${index}`}
                className={
                  finished ||
                  index < roundIndex ||
                  (index === roundIndex && pickedId === round.answer)
                    ? "on"
                    : ""
                }
              />
            ))}
          </div>
          {finished ? (
            <div className="planet-sort-actions">
              <button onClick={reset}>Play again</button>
              <button onClick={onExit}>Done</button>
            </div>
          ) : null}
        </div>
        <div className="planet-sort-choices">
          <span className="game-keyboard-status" aria-live="polite">
            {selectedChoice.statusText}
          </span>
          {choices.map((planet, index) => {
            const visualSize = 88 + (planet.radius / maxRadius) * 108;
            return (
              <button
                key={planet.id}
                className={planetChoiceState(planet, index)}
                onClick={() => choose(planet)}
                onFocus={() => setChoiceIndex(clampChoiceIndex(index, choices.length))}
                aria-current={selectedChoice.index === index ? "true" : undefined}
                aria-label={choiceButtonLabel(
                  planet,
                  index,
                  choices,
                  (item) => item.name,
                  "Choose",
                )}
                disabled={finished}
              >
                <span className="planet-sort-planet-wrap">
                  <Planet3D
                    planet={planet}
                    detail={false}
                    allowOrbit={false}
                    className="planet-sort-planet"
                    style={{
                      width: `${visualSize}px`,
                      height: `${visualSize}px`,
                    }}
                  />
                </span>
                <strong>{planet.name}</strong>
                <small>
                  {!pickedId && planet.id === round.answer
                    ? "Tap me"
                    : planet.type.split(" · ")[0]}
                </small>
              </button>
            );
          })}
        </div>
      </div>
    </section>
  );
}
