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

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

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

  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, .dropdown").forEach(function (el) { el.remove(); });
    a.textContent = clone.textContent.trim();
    li.appendChild(a);
    list.appendChild(li);
  });
  nav.appendChild(list);

  // Stack the TOC on top of any server-rendered widget(s) already in the rail.
  var rail = document.querySelector("aside.sidebar");
  rail.insertBefore(nav, rail.firstChild);
});
