const LIFECYCLE_FRAMES = [
  {
    when: "4.6 billion years ago",
    text: "Our Sun was born inside a giant cloud of dust and gas.",
    showOrbits: false,
    audio: "lifecycle1.mp3",
  },
  {
    when: "4 billion years ago",
    text: "It started shining! Earth wasn't here yet.",
    showOrbits: false,
    audio: "lifecycle2.mp3",
  },
  {
    when: "Right now",
    text: "This is the Sun you see in the sky today.",
    showOrbits: true,
    audio: "lifecycle3.mp3",
  },
  {
    when: "In about 5 billion years",
    text: "When it grows old, the Sun will start to puff up...",
    showOrbits: "fading",
    audio: "lifecycle4.mp3",
  },
  {
    when: "In about 6 billion years",
    text: "...big enough to swallow Mercury and Venus!",
    showOrbits: false,
    audio: "lifecycle5.mp3",
  },
  {
    when: "Far in the future",
    text: "Then it shrinks into a tiny diamond-bright star and rests.",
    showOrbits: false,
    audio: "lifecycle6.mp3",
  },
];

function playLifecycleClip(frameIndex) {
  const frame = LIFECYCLE_FRAMES[frameIndex];
  if (!frame || !frame.audio) return;
  if (window.__narration) window.__narration.play(frame.audio);
}

function SunLifecycleFlipbook({ onClose }) {
  // The rich NASA-telescope flipbook lives in /sun-story/. Load it in an iframe
  // overlay so we don't double-render Three.js inside this page's React tree.
  // Pause the planet narration while the flipbook is open — the iframe owns audio.
  useEffect(() => {
    if (window.__narration) window.__narration.stop();
  }, []);

  useEscapeHandler(onClose);

  useEffect(() => {
    const onMessage = (e) => {
      if (e.origin !== window.location.origin) return;
      if (e.data && e.data.type === "flipbook-close") onClose();
    };
    window.addEventListener("message", onMessage);
    return () => window.removeEventListener("message", onMessage);
  }, [onClose]);

  return (
    <div className="lifecycle-iframe-overlay">
      <iframe
        className="lifecycle-iframe"
        src="sun-story/index.html"
        title="Sun's Life"
        allow="autoplay"
      />
      <button
        className="lifecycle-back"
        onClick={(e) => {
          e.stopPropagation();
          onClose();
        }}
      >
        × Close
      </button>
    </div>
  );
}

const EARTH_GRAVITY_MS2 = 9.81;

function planetGravityRatio(planet) {
  const raw = parseFloat(String(planet.gravity || "").replace(/,/g, ""));
  if (!Number.isFinite(raw) || raw <= 0) return null;
  return raw / EARTH_GRAVITY_MS2;
}

// AGENT_TARGET: get-planet-gravity — public getter returning gravity multiplier vs Earth
function getPlanetGravity(planet) {
  return planetGravityRatio(planet);
}

function gravityFeelingCopy(ratio) {
  if (ratio === null) return "Gravity data is missing for this world.";
  if (ratio < 0.2) return "Tiny hops turn into big floaty bounces here.";
  if (ratio < 0.75) return "You would feel light and springy here.";
  if (ratio < 1.25) return "This feels pretty close to home.";
  if (ratio < 3) return "Your legs would work much harder here.";
  return "This pull is extreme, so visiting would need a very special suit.";
}

function sunlightTravelTime(distance) {
  const au = parseFloat(String(distance || "").replace(/,/g, ""));
  if (!Number.isFinite(au) || au <= 0) return "right here";
  const minutes = au * 8.3167;
  if (minutes < 1) return `${Math.round(minutes * 60)} sec`;
  if (minutes < 90) return `${minutes.toFixed(minutes < 10 ? 1 : 0)} min`;
  const hours = minutes / 60;
  return `${hours.toFixed(hours < 10 ? 1 : 0)} hr`;
}

function planetYearInEarthDays(year) {
  const text = String(year || "").toLowerCase();
  const value = parseFloat(text.replace(/,/g, ""));
  if (!Number.isFinite(value) || value <= 0) return null;
  if (text.includes("year")) return value * 365.25;
  if (text.includes("day")) return value;
  return null;
}

const WORLD_NAME_CLIPS = {
  sun: "name_sun.mp3",
  mercury: "name_mercury.mp3",
  venus: "name_venus.mp3",
  earth: "name_earth.mp3",
  mars: "name_mars.mp3",
  jupiter: "name_jupiter.mp3",
  saturn: "name_saturn.mp3",
  uranus: "name_uranus.mp3",
  neptune: "name_neptune.mp3",
};

// AGENT_TARGET: say-name-slow — Web Speech API pronunciation for early readers, slow & clear
function speakNameSlow(displayName) {
  try {
    if (
      !window.speechSynthesis ||
      typeof window.SpeechSynthesisUtterance !== "function"
    )
      return;
    window.speechSynthesis.cancel();
    const utt = new window.SpeechSynthesisUtterance(
      String(displayName || "").trim(),
    );
    utt.rate = 0.65;
    utt.pitch = 1.1;
    utt.volume = 1;
    window.speechSynthesis.speak(utt);
  } catch (_) {}
}

function speakWorldName(world) {
  if (!window.__narration) return;
  const id =
    typeof world === "string"
      ? PLANETS.find((planet) => planet.id === world || planet.name === world)?.id
      : world?.id;
  const clip = WORLD_NAME_CLIPS[id];
  if (clip) window.__narration.play(clip);
}

function planetFromHash() {
  const rawId = (window.location.hash || "")
    .replace(/^#\/?planet=/, "")
    .replace(/^#\/?/, "");
  let id = rawId;
  try {
    id = decodeURIComponent(rawId);
  } catch {}
  if (!id) return null;
  return allKnownPlanets().find((planet) => planet.id === id) || null;
}

function allKnownPlanets() {
  const exoplanets =
    typeof EXOPLANET_SYSTEMS !== "undefined"
      ? Object.values(EXOPLANET_SYSTEMS).flatMap((system) => system.planets || [])
      : [];
  return [...PLANETS, ...exoplanets];
}

function systemIdForPlanetId(planetId) {
  if (!planetId || typeof EXOPLANET_SYSTEMS === "undefined") return null;
  const entry = Object.entries(EXOPLANET_SYSTEMS).find(([, system]) =>
    (system.planets || []).some((planet) => planet.id === planetId),
  );
  return entry ? entry[0] : null;
}

function setPlanetHash(planet) {
  const nextHash = planet
    ? `#planet=${encodeURIComponent(planet.id)}`
    : window.location.pathname + window.location.search;
  if (planet) {
    if (window.location.hash !== nextHash) window.history.replaceState(null, "", nextHash);
  } else if (window.location.hash) {
    window.history.replaceState(null, "", nextHash);
  }
}

function fallbackCopyText(text) {
  let textarea = null;
  try {
    textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.setAttribute("readonly", "");
    textarea.style.position = "fixed";
    textarea.style.left = "-9999px";
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand("copy");
  } catch {
  } finally {
    if (textarea) textarea.remove();
  }
}

function copyPlanetLink(planet) {
  const url = `${window.location.origin}${window.location.pathname}${window.location.search}#planet=${planet.id}`;
  try {
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(url).catch(() => fallbackCopyText(url));
    } else {
      fallbackCopyText(url);
    }
  } catch {}
  setPlanetHash(planet);
  playKidSound("boop");
}
