(function () {
  var content = document.querySelector("main");
  if (!content) return;

  var headings = content.querySelectorAll("h1, h2, h3");
  if (headings.length < 2) return;

  var nav = document.createElement("nav");
  nav.className = "toc";

  var header = document.createElement("div");
  header.className = "panel-header";
  header.textContent = "Contents";
  nav.appendChild(header);

  var list = document.createElement("ul");
  headings.forEach(function (h) {
    if (!h.id) return;
    var li = document.createElement("li");
    li.className = "toc-" + h.tagName.toLowerCase();
    var a = document.createElement("a");
    a.href = "#" + h.id;
    var clone = h.cloneNode(true);
    clone.querySelectorAll(".btn, .muted, .heading-anchor").forEach(function (el) { el.remove(); });
    a.textContent = clone.textContent.trim();
    li.appendChild(a);
    list.appendChild(li);
  });
  nav.appendChild(list);

  var toggle = document.createElement("button");
  toggle.type = "button";
  toggle.className = "panel-toggle";
  toggle.textContent = "Contents";
  toggle.setAttribute("aria-expanded", "false");
  toggle.addEventListener("click", function () {
    var open = nav.classList.toggle("is-open");
    toggle.setAttribute("aria-expanded", open ? "true" : "false");
  });

  var main = document.querySelector("main");
  if (main) {
    main.parentNode.insertBefore(toggle, main);
    main.parentNode.insertBefore(nav, main);
  } else {
    document.body.appendChild(toggle);
    document.body.appendChild(nav);
  }

  var pageHeader = document.querySelector("header");
  function updateTop() {
    if (!pageHeader || getComputedStyle(nav).position !== "fixed") return;
    var rect = pageHeader.getBoundingClientRect();
    nav.style.top = Math.max(8, rect.bottom + 8) + "px";
  }
  window.addEventListener("scroll", updateTop, { passive: true });
  window.addEventListener("resize", updateTop);
  updateTop();
})();
