document.addEventListener("DOMContentLoaded", () => {
  const BREAKPOINT = 1000;
  const frame = document.getElementById("contentFrame");
  const links = Array.from(document.querySelectorAll("main a[href]"));
  const headings = Array.from(document.querySelectorAll("main h2, main h3, main h4, main h5, main h6"));

  const isWide = () => window.innerWidth >= BREAKPOINT;

  function setActiveByRel(rel) {
    // Compare as strings; rels are exactly what's in the HTML.
    for (const a of links) {
      a.classList.toggle("active", a.getAttribute("href") === rel);
    }
  }

  // -------- Collapsible sections (h2-h6) --------
  for (const h of headings) {
    const li = h.closest("li");
    if (!li) continue;
    const ul = li.querySelector(":scope > ul");
    if (!ul) continue;

    const key = "collapse:" + (h.id || h.textContent.trim());
    const isCollapsed = localStorage.getItem(key) === "0";

    if (isCollapsed) {
      ul.classList.add("collapsed");
      h.classList.add("collapsed"); // make arrow start as ▸
    }

    h.addEventListener("click", (ev) => {
      ev.preventDefault();
      const collapsed = ul.classList.toggle("collapsed");
      h.classList.toggle("collapsed", collapsed);
      localStorage.setItem(key, collapsed ? "0" : "1");
    });
  }

  // -------- Navigation + active (NO target, no iframe load handler) --------
  function openInFrame(rel) {
    frame.setAttribute("src", rel);
    sessionStorage.setItem("activeHref", rel);
    setActiveByRel(rel);
  }

  for (const a of links) {
    a.addEventListener("click", (ev) => {
      const rel = a.getAttribute("href");

      if (isWide()) {
        // Wide: keep the index, load in iframe
        ev.preventDefault();
        openInFrame(rel);
      } else {
        // Narrow: normal navigation (no iframe)
        sessionStorage.setItem("activeHref", rel);
        // let browser navigate
      }
    });
  }

  // -------- Preload (wide only) --------
  let didPreload = false;
  function preloadIfWide() {
    if (!isWide()) return;
    if (didPreload) return;

    const saved = sessionStorage.getItem("activeHref");
    const first = links[0]?.getAttribute("href");
    const rel = saved || first;
    if (!rel) return;

    openInFrame(rel);
    didPreload = true;
  }

  // Restore highlight (narrow or wide)
  const saved = sessionStorage.getItem("activeHref");
  if (saved) setActiveByRel(saved);

  preloadIfWide();
  window.addEventListener("resize", preloadIfWide);
});