// Doorway for the Death page.
//
// A pair of doors that begin to swing open when the reader has scrolled
// past ~60% of the section and stand fully parted by ~95%. Behind them
// a warm gold-white glow that intensifies as they open — the light on
// the other side, getting through.

(function () {
  const root = document.getElementById("doorway");
  if (!root) return;
  const view = document.querySelector('.view[data-view="death"]');
  if (!view) return;
  const doorL = root.querySelector(".dw-door-left");
  const doorR = root.querySelector(".dw-door-right");
  const light = root.querySelector(".dw-light");

  function progress() {
    const rect = view.getBoundingClientRect();
    const total = Math.max(1, rect.height - window.innerHeight);
    return Math.max(0, Math.min(1, -rect.top / total));
  }

  // Map full scroll 0..1 → door open 0..1, starting at 0.25 and finishing at 1.0.
  function doorOpen(p) {
    const start = 0.25;
    const end   = 1.0;
    if (p <= start) return 0;
    if (p >= end)   return 1;
    return (p - start) / (end - start);
  }

  let rafQueued = false;
  let lastP = -1;

  function apply() {
    const p = doorOpen(progress());
    if (Math.abs(p - lastP) < 0.005) return;
    lastP = p;
    const deg = (p * 88).toFixed(1);  // 0 → 88°
    doorL.style.transform = "rotateY(-" + deg + "deg)";
    doorR.style.transform = "rotateY("  + deg + "deg)";
    light.style.opacity = (0.15 + p * 0.85).toFixed(3);
    light.style.transform = "scale(" + (0.35 + p * 1.4).toFixed(3) + ")";
  }

  function onScroll() {
    if (rafQueued) return;
    rafQueued = true;
    requestAnimationFrame(() => { rafQueued = false; apply(); });
  }

  function start() {
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    // First-frame snap: disable transitions, jump to the correct state, then
    // fade in and restore transitions so subsequent scrolls animate smoothly.
    doorL.style.transition = "none";
    doorR.style.transition = "none";
    light.style.transition = "none";
    apply();
    requestAnimationFrame(() => {
      doorL.style.transition = "";
      doorR.style.transition = "";
      light.style.transition = "";
      root.classList.add("ready");
    });
  }
  function stop() {
    window.removeEventListener("scroll", onScroll);
    window.removeEventListener("resize", onScroll);
  }

  function isActive() { return view.classList.contains("active"); }
  if ("MutationObserver" in window) {
    new MutationObserver(() => { if (isActive()) start(); else stop(); })
      .observe(view, { attributes: true, attributeFilter: ["class"] });
    if (isActive()) start();
  } else {
    start();
  }
})();
