// galileo-eyepiece.jsx
// AGENT_TARGET: galileo-eyepiece — scrub through what humans knew about the solar system across eras

const GALILEO_ERAS = [
  {
    year: 1600,
    label: "1600",
    note: "Naked-eye astronomy only. No telescope. Humans knew 6 planets (Mercury through Saturn), but had no idea about orbits, distances, or outer worlds.",
    knownIds: ["sun", "mercury", "venus", "earth", "mars", "jupiter", "saturn"],
    moonNote: "Only Earth's Moon was known.",
  },
  {
    year: 1700,
    label: "1700",
    note: "Galileo's telescope (1609) revealed Jupiter's four large moons and the phases of Venus. Saturn's Titan was found in 1655. Still just 6 planets.",
    knownIds: ["sun", "mercury", "venus", "earth", "mars", "jupiter", "saturn"],
    moonNote:
      "Known moons: Earth's Moon, Jupiter's 4 Galilean moons, Saturn's Titan.",
  },
  {
    year: 1850,
    label: "1850",
    note: "Uranus discovered by Herschel in 1781. Neptune predicted by math and found in 1846. The solar system suddenly had two invisible giants.",
    knownIds: [
      "sun",
      "mercury",
      "venus",
      "earth",
      "mars",
      "jupiter",
      "saturn",
      "uranus",
      "neptune",
    ],
    moonNote:
      "Dozens of moons now known. Neptune's Triton found within weeks of Neptune.",
  },
  {
    year: 2026,
    label: "2026",
    note: "All 8 planets confirmed. Over 290 known moons. Spacecraft have visited every planet. We photograph black holes and detect gravitational waves.",
    knownIds: [
      "sun",
      "mercury",
      "venus",
      "earth",
      "mars",
      "jupiter",
      "saturn",
      "uranus",
      "neptune",
    ],
    moonNote: "290+ moons confirmed. Saturn alone has 146.",
  },
];

const PLANET_META = {
  sun: { label: "Sun", color: "#FFD700", fact: "Center of the solar system" },
  mercury: {
    label: "Mercury",
    color: "#b8b8a8",
    fact: "Innermost planet — swings in the sky near the Sun",
  },
  venus: {
    label: "Venus",
    color: "#e8c87c",
    fact: "Brightest 'star' — visible at dusk and dawn",
  },
  earth: { label: "Earth", color: "#4488ff", fact: "Our home — always known" },
  mars: {
    label: "Mars",
    color: "#c84820",
    fact: "The red wanderer — tracked since ancient times",
  },
  jupiter: {
    label: "Jupiter",
    color: "#c8a870",
    fact: "Brightest true planet — known for millennia",
  },
  saturn: {
    label: "Saturn",
    color: "#e0c878",
    fact: "Its rings weren't understood until ~1655",
  },
  uranus: {
    label: "Uranus",
    color: "#88e0e0",
    fact: "Discovered 1781 by Herschel with a telescope",
  },
  neptune: {
    label: "Neptune",
    color: "#4060e0",
    fact: "Predicted by math in 1846 before being seen",
  },
};

const ERA_YEARS = GALILEO_ERAS.map((e) => e.year);

function GalileoEyepiece({ onClose }) {
  const [eraIndex, setEraIndex] = React.useState(3);
  const overlayRef = React.useRef(null);
  const era = GALILEO_ERAS[eraIndex];
  const knownSet = new Set(era.knownIds);
  const discoveryPercent =
    (knownSet.size / Object.keys(PLANET_META).length) * 100;

  const handleSlider = (e) => {
    setEraIndex(Number(e.target.value));
  };
  const stepEra = (direction) => {
    setEraIndex((index) =>
      Math.max(0, Math.min(GALILEO_ERAS.length - 1, index + direction)),
    );
  };
  React.useEffect(() => {
    if (overlayRef.current) overlayRef.current.focus();
  }, [onClose]);
  const handleOverlayKeyDown = (event) => {
    if (event.key === "Escape") {
      event.preventDefault();
      event.stopPropagation();
      onClose();
      return;
    }
    if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
      event.preventDefault();
      event.stopPropagation();
      stepEra(event.key === "ArrowLeft" ? -1 : 1);
    }
  };

  return (
    <div
      ref={overlayRef}
      className="galileo-overlay"
      role="dialog"
      aria-label="Galileo's Eyepiece"
      tabIndex="-1"
      onKeyDownCapture={handleOverlayKeyDown}
    >
      <button
        className="galileo-close"
        onClick={onClose}
        aria-label="Close Galileo's Eyepiece"
      >
        ✕
      </button>

      <div className="galileo-header">
        <span style={{ fontSize: 28 }}>🔭</span>
        <div className="galileo-title">Galileo's Eyepiece</div>
      </div>
      <div style={{ fontSize: 13, color: "#8898b0", marginBottom: 4 }}>
        What did humans know?
      </div>

      <div className="galileo-year-label">{era.label}</div>

      <div className="galileo-era-stepper" aria-label="Change discovery year">
        <button
          type="button"
          onClick={() => stepEra(-1)}
          disabled={eraIndex === 0}
        >
          Earlier
        </button>
        <button
          type="button"
          onClick={() => stepEra(1)}
          disabled={eraIndex === GALILEO_ERAS.length - 1}
        >
          Later
        </button>
      </div>

      <div className="galileo-slider-wrap">
        <input
          type="range"
          className="galileo-slider"
          min={0}
          max={GALILEO_ERAS.length - 1}
          step={1}
          value={eraIndex}
          onChange={handleSlider}
          aria-label="Scrub through history of astronomical discovery"
        />
        <div className="galileo-era-labels">
          {GALILEO_ERAS.map((e) => (
            <span key={e.year}>{e.year}</span>
          ))}
        </div>
      </div>

      <div className="galileo-discovery-meter" aria-label="Known solar system meter">
        <strong>{knownSet.size} known</strong>
        <i>
          <b style={{ width: `${discoveryPercent}%` }} />
        </i>
        <span>More discoveries appear later.</span>
      </div>

      <div className="galileo-note">{era.note}</div>

      <div className="galileo-system">
        {Object.entries(PLANET_META).map(([id, meta]) => {
          const known = knownSet.has(id);
          return (
            <div
              key={id}
              className={`galileo-planet-row ${known ? "known" : "unknown"}`}
            >
              <div
                className="galileo-planet-dot"
                style={{ background: meta.color }}
              />
              <div className="galileo-planet-name">{meta.label}</div>
              <div className="galileo-planet-detail">
                {known ? meta.fact : "— not yet discovered —"}
              </div>
            </div>
          );
        })}
      </div>

      <div
        style={{
          marginTop: 16,
          fontSize: 13,
          color: "#6878a0",
          textAlign: "center",
          maxWidth: 360,
        }}
      >
        🌕 {era.moonNote}
      </div>
    </div>
  );
}
