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

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

function speakWorldName(name) {
  if (window.__narration && !window.__narration.isEnabled()) return;
  try {
    if (!window.speechSynthesis || !window.SpeechSynthesisUtterance) return;
    window.__narration?.stop();
    window.speechSynthesis.cancel();
    const utterance = new SpeechSynthesisUtterance(name);
    utterance.rate = 0.72;
    utterance.pitch = 1.08;
    window.speechSynthesis.speak(utterance);
  } catch {}
}

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