/* Cinematic flow — scroll-driven reveals, mission progress rail,
   crosshair cursor, and section markers.
*/

const { useEffect: useE_f, useState: useS_f, useRef: useR_f } = React;

/* ============================================================
   useReveal — adds .revealed to any [data-reveal] element when
   it enters the viewport. Optional [data-reveal-delay] in ms.
   ============================================================ */
function useReveal() {
  useE_f(() => {
    const io = new IntersectionObserver((entries) => {
      for (const e of entries) {
        if (e.isIntersecting) {
          const el = e.target;
          const delay = parseInt(el.dataset.revealDelay || "0", 10);
          if (delay) setTimeout(() => el.classList.add("revealed"), delay);
          else el.classList.add("revealed");
          io.unobserve(el);
        }
      }
    }, { threshold: 0.12, rootMargin: "-5% 0px -8% 0px" });
    const scan = () => {
      document.querySelectorAll("[data-reveal]:not(.revealed):not(.observed)")
        .forEach(el => { el.classList.add("observed"); io.observe(el); });
    };
    scan();
    const id = setInterval(scan, 700);
    return () => { clearInterval(id); io.disconnect(); };
  }, []);
}

/* ============================================================
   MissionRail — vertical right-side scroll progress with
   chapter markers. Highlights the active section.
   ============================================================ */
const RAIL_SECTIONS = [
  { sel: ".hero",            n: "00", label: "COVER"        },
  { sel: ".intel-section",   n: "01", label: "INTEL"        },
  { sel: "#poster-section",  n: "02", label: "WANTED"       },
  { sel: ".section.darker:nth-of-type(4)",    n: "03", label: "BOUNTY BOARD" },
  { sel: ".bounties-tv-section", n: "04", label: "BOUNTIES" },
  { sel: ".ranks-section",   n: "05", label: "RANK LADDER"  },
  { sel: ".section.midnight",n: "06", label: "HEISTS"       },
  { sel: ".section.darker:last-of-type", n: "07", label: "DOSSIER" },
  { sel: ".cta-section",     n: "08", label: "JOIN CREW"    },
];

function MissionRail() {
  const [progress, setProgress] = useS_f(0);
  const [active, setActive]     = useS_f(0);
  const [open, setOpen]         = useS_f(false);

  useE_f(() => {
    const onScroll = () => {
      const max = document.documentElement.scrollHeight - window.innerHeight;
      const p = max > 0 ? Math.min(1, Math.max(0, window.scrollY / max)) : 0;
      setProgress(p);

      // determine active by which marker top is closest to 30% viewport
      const refY = window.innerHeight * 0.35;
      let bestI = 0, bestDist = Infinity;
      RAIL_SECTIONS.forEach((s, i) => {
        const el = document.querySelector(s.sel);
        if (!el) return;
        const r = el.getBoundingClientRect();
        if (r.top - refY < 0) {
          const dist = Math.abs(r.top - refY);
          if (dist < bestDist) { bestDist = dist; bestI = i; }
        }
      });
      setActive(bestI);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const jump = (sel) => {
    const el = document.querySelector(sel);
    if (!el) return;
    window.scrollTo({ top: el.offsetTop - 28, behavior: "smooth" });
  };

  return (
    <div className={`mission-rail ${open ? "open" : ""}`}>
      <div className="mr-head">
        <div className="mr-num">
          <span className="cur">{String(active).padStart(2,"0")}</span>
          <span className="den">/ {String(RAIL_SECTIONS.length - 1).padStart(2,"0")}</span>
        </div>
        <div className="mr-lbl">MISSION PROGRESS</div>
        <div className="mr-pct">{Math.round(progress * 100)}%</div>
      </div>

      <div className="mr-track">
        <div className="mr-fill" style={{ height: `${progress * 100}%` }}>
          <div className="mr-fill-glow" />
        </div>
        {RAIL_SECTIONS.map((s, i) => (
          <button
            key={i}
            className={`mr-mark ${i === active ? "on" : ""} ${i < active ? "passed" : ""}`}
            style={{ top: `${(i / (RAIL_SECTIONS.length - 1)) * 100}%` }}
            onClick={() => jump(s.sel)}
            onMouseEnter={() => setOpen(true)}
            onMouseLeave={() => setOpen(false)}
            aria-label={s.label}
          >
            <span className="dot" />
            <span className="mr-mark-label">
              <span className="n">{s.n}</span>
              <span className="l">{s.label}</span>
            </span>
          </button>
        ))}
      </div>

      <div className="mr-foot">
        <div className="mr-vc">GCA · LIVE</div>
        <div className="mr-now">
          <span className="dot" /> LIVE
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   SectionDivider — animated chrome bar between major sections.
   Render between two sections to get a scanning highlight + tag.
   ============================================================ */
function SectionDivider({ tag, n }) {
  return (
    <div className="sec-div" data-reveal>
      <div className="sd-bar left" />
      <div className="sd-chip">
        <span className="sd-n">{n}</span>
        <span className="sd-tag">{tag}</span>
        <span className="sd-scan" />
      </div>
      <div className="sd-bar right" />
    </div>
  );
}

/* ============================================================
   FlowHost — single mount point for everything in this file.
   ============================================================ */
function FlowHost() {
  useReveal();
  return <MissionRail />;
}

window.useReveal = useReveal;
window.MissionRail = MissionRail;
window.SectionDivider = SectionDivider;
window.FlowHost = FlowHost;
