// AGENT_TARGET: scavenger-checklist — corner checklist of playful solar system exploration prompts

const SCAVENGER_PROMPTS = [
  {
    id: "rings",
    text: "Find the planet with rings",
    planet: "saturn",
    emoji: "🪐",
  },
  { id: "red", text: "Find the red planet", planet: "mars", emoji: "🔴" },
  {
    id: "biggest",
    text: "Find the biggest planet",
    planet: "jupiter",
    emoji: "🌟",
  },
  {
    id: "nearest",
    text: "Find the nearest planet to Sun",
    planet: "mercury",
    emoji: "☀️",
  },
  {
    id: "blue",
    text: "Find our blue home planet",
    planet: "earth",
    emoji: "🌍",
  },
  { id: "hot", text: "Find the hottest planet", planet: "venus", emoji: "🔥" },
  {
    id: "windy",
    text: "Find the planet with storm winds",
    planet: "neptune",
    emoji: "🌀",
  },
];

// AGENT_TARGET: scavenger-checklist — persist completed prompts across sessions
function useScavengerProgress() {
  const [checked, setChecked] = React.useState(() => {
    try {
      const raw = localStorage.getItem("planets_scavenger_checked");
      return raw ? JSON.parse(raw) : [];
    } catch (_) {
      return [];
    }
  });

  const check = React.useCallback((promptId) => {
    setChecked((prev) => {
      if (prev.includes(promptId)) return prev;
      const next = [...prev, promptId];
      try {
        localStorage.setItem("planets_scavenger_checked", JSON.stringify(next));
      } catch (_) {}
      return next;
    });
  }, []);

  const reset = React.useCallback(() => {
    setChecked([]);
    try {
      localStorage.removeItem("planets_scavenger_checked");
    } catch (_) {}
  }, []);

  return [checked, check, reset];
}

function ScavengerChecklist({ onCelebrate }) {
  // AGENT_TARGET: scavenger-checklist — ScavengerChecklist component with window bridge for focusPlanet
  const [checked, check, reset] = useScavengerProgress();
  const [collapsed, setCollapsed] = React.useState(false);
  const prevLen = React.useRef(checked.length);
  const allDone = checked.length >= SCAVENGER_PROMPTS.length;

  // Register window bridge so focusPlanet in app.jsx can notify this component
  React.useEffect(() => {
    window.__scavengerNotify = (planetId) => {
      const match = SCAVENGER_PROMPTS.find(
        (p) => p.planet === planetId && !checked.includes(p.id),
      );
      if (match) {
        check(match.id);
        const willFinish = checked.length + 1 >= SCAVENGER_PROMPTS.length;
        return { matched: match, allDone: willFinish };
      }
      return null;
    };
    return () => {
      delete window.__scavengerNotify;
    };
  }, [checked, check]);

  // Fire celebration when the last prompt is checked
  React.useEffect(() => {
    if (
      checked.length > prevLen.current &&
      checked.length >= SCAVENGER_PROMPTS.length
    ) {
      if (typeof onCelebrate === "function") onCelebrate();
    }
    prevLen.current = checked.length;
  }, [checked.length, onCelebrate]);

  const nextPrompt = SCAVENGER_PROMPTS.find((p) => !checked.includes(p.id));

  return (
    <div
      className={`scavenger-checklist${collapsed ? " collapsed" : ""}${allDone ? " done" : ""}`}
      aria-label="Solar system scavenger hunt"
    >
      <button
        className="scavenger-toggle"
        onClick={() => setCollapsed((v) => !v)}
        aria-expanded={String(!collapsed)}
      >
        <span>{allDone ? "🎉" : "🔍"}</span>
        <span>
          Hunt {checked.length}/{SCAVENGER_PROMPTS.length}
        </span>
        <span className="scavenger-chevron">{collapsed ? "▲" : "▼"}</span>
      </button>

      {!collapsed && (
        <>
          <ul className="scavenger-list">
            {SCAVENGER_PROMPTS.map((prompt) => {
              const done = checked.includes(prompt.id);
              const isNext = nextPrompt && nextPrompt.id === prompt.id;
              return (
                <li
                  key={prompt.id}
                  className={`scavenger-item${done ? " done" : ""}${isNext ? " next" : ""}`}
                >
                  <span className="scavenger-emoji" aria-hidden="true">
                    {done ? "✅" : prompt.emoji}
                  </span>
                  <span className="scavenger-text">{prompt.text}</span>
                </li>
              );
            })}
          </ul>

          {allDone ? (
            <div className="scavenger-complete">
              <strong>Explorer badge earned!</strong>
              <button className="scavenger-reset" onClick={reset}>
                Play again
              </button>
            </div>
          ) : (
            <button
              className="scavenger-reset-small"
              onClick={reset}
              title="Reset progress"
            >
              ↺ reset
            </button>
          )}
        </>
      )}
    </div>
  );
}
