/* =====================================================================
   ReadingChrome — sticky top bar + reading progress + section nav
   rail + theme toggle + Download PDF. Exports:
     window.ProgressBar, window.TopBar, window.SectionNav
   ===================================================================== */
(function () {
  const { useState, useEffect, useRef } = React;

  /* ---- reading progress (top hairline) ---- */
  function ProgressBar() {
    const [pct, setPct] = useState(0);
    useEffect(() => {
      let raf = 0;
      const onScroll = () => {
        cancelAnimationFrame(raf);
        raf = requestAnimationFrame(() => {
          const doc = document.documentElement;
          const h = doc.scrollHeight - doc.clientHeight;
          setPct(h > 0 ? Math.min(1, doc.scrollTop / h) : 0);
        });
      };
      onScroll();
      window.addEventListener("scroll", onScroll, { passive: true });
      window.addEventListener("resize", onScroll);
      return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); cancelAnimationFrame(raf); };
    }, []);
    return (
      <div className="wp-progress" aria-hidden="true">
        <div className="wp-progress-fill" style={{ transform: `scaleX(${pct})` }}></div>
      </div>
    );
  }

  /* ---- theme toggle ---- */
  function useTheme() {
    const [theme, setTheme] = useState(() => localStorage.getItem("whooperates.theme") || "dark");
    useEffect(() => {
      document.documentElement.setAttribute("data-theme", theme);
      localStorage.setItem("whooperates.theme", theme);
    }, [theme]);
    return [theme, setTheme];
  }

  function TopBar({ onDownload }) {
    const [theme, setTheme] = useTheme();
    useEffect(() => { if (window.lucide) window.lucide.createIcons(); }, [theme]);
    return (
      <header className="wp-topbar ui">
        <a className="wp-topbar-brand" href="../index.html" aria-label="Nectar — back to homepage">
          <img src={(window.__resources && window.__resources.logoMark) || "assets/logo-mark.svg"} alt="" width="22" height="22" className="wp-topbar-mark" />
          <span className="wp-topbar-name">Nectar</span>
          <span className="wp-topbar-sep" aria-hidden="true">/</span>
          <span className="wp-topbar-doc">Who Runs the Compute Where Physical AI Works?</span>
        </a>
        <div className="wp-topbar-actions">
          <button type="button" className="wp-iconbtn" onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
                  aria-label={theme === "dark" ? "Switch to light theme" : "Switch to dark theme"}
                  title={theme === "dark" ? "Light" : "Dark"}>
            <i data-lucide={theme === "dark" ? "sun" : "moon"} aria-hidden="true"></i>
          </button>
          <button type="button" className="wp-btn-ghost" onClick={onDownload}>
            <i data-lucide="download" aria-hidden="true"></i>
            <span className="wp-btn-ghost-label">Download PDF</span>
          </button>
        </div>
      </header>
    );
  }

  /* ---- section nav rail (scroll-spy) ---- */
  function SectionNav({ sections }) {
    const [active, setActive] = useState(sections[0] && sections[0].id);
    const ticking = useRef(false);

    useEffect(() => {
      const ids = sections.map((s) => s.id);
      const onScroll = () => {
        if (ticking.current) return;
        ticking.current = true;
        requestAnimationFrame(() => {
          const mid = window.innerHeight * 0.34;
          let cur = ids[0];
          for (const id of ids) {
            const el = document.getElementById(id);
            if (el && el.getBoundingClientRect().top <= mid) cur = id;
          }
          setActive(cur);
          ticking.current = false;
        });
      };
      onScroll();
      window.addEventListener("scroll", onScroll, { passive: true });
      return () => window.removeEventListener("scroll", onScroll);
    }, [sections]);

    return (
      <nav className="wp-sectionnav ui" aria-label="Sections">
        <span className="wp-sectionnav-title">Contents</span>
        <ol className="wp-sectionnav-list">
          {sections.map((s) => (
            <li key={s.id}>
              <a href={"#" + s.id}
                 className={"wp-sectionnav-link" + (active === s.id ? " is-active" : "")}
                 aria-current={active === s.id ? "true" : undefined}>
                <span className="wp-sectionnav-num mono">{s.num}</span>
                <span className="wp-sectionnav-label">{s.title}</span>
              </a>
            </li>
          ))}
        </ol>
      </nav>
    );
  }

  window.ProgressBar = ProgressBar;
  window.TopBar = TopBar;
  window.SectionNav = SectionNav;
})();
