/**
 * ADR Page — timeline placement
 *
 * On ADR pages the build hook embeds a hidden `.adr-timeline` element in the
 * page content.
 *
 *   Desktop (>= 76.25em) — move the timeline into the left sidebar, replacing
 *                           the integrated Table of Contents.
 *   Mobile  (<  76.25em) — leave the navigation drawer alone; instead show
 *                           the timeline at the end of the article body.
 *
 * Compatible with Material for MkDocs instant-loading (SPA navigation).
 */

var _adrDesktopQuery = window.matchMedia("(min-width: 76.25em)");

document$.subscribe(function () {
  var timeline = document.querySelector(".md-content .adr-timeline");

  if (!timeline) {
    // Not an ADR page — clean up any leftover state from a previous page.
    document.body.classList.remove("adr-page");
    return;
  }

  document.body.classList.add("adr-page");

  if (_adrDesktopQuery.matches) {
    _placeInSidebar(timeline);
  } else {
    _placeInContent(timeline);
  }
});

/* ── Desktop: replace the sidebar TOC with the timeline ──────────────── */

function _placeInSidebar(timeline) {
  var sidebarInner = document.querySelector(
    ".md-sidebar--primary .md-sidebar__inner"
  );
  if (!sidebarInner) return;

  var nav = document.createElement("nav");
  nav.className = "md-nav md-nav--primary adr-sidebar-timeline";
  nav.setAttribute("data-md-level", "0");

  var title = document.createElement("label");
  title.className = "md-nav__title adr-timeline-title";
  title.textContent = "Status History";

  var clone = timeline.cloneNode(true);
  clone.style.display = "";

  nav.appendChild(title);
  nav.appendChild(clone);

  sidebarInner.innerHTML = "";
  sidebarInner.appendChild(nav);

  // Remove the hidden source element from the content area.
  timeline.parentNode.removeChild(timeline);
}

/* ── Mobile: append the timeline at the end of the article ───────────── */

function _placeInContent(timeline) {
  var article = document.querySelector(".md-content__inner");
  if (!article) return;

  // Build a wrapper with a heading so it reads as a distinct section.
  var wrapper = document.createElement("div");
  wrapper.className = "adr-timeline-mobile";

  var heading = document.createElement("h2");
  heading.textContent = "Status History";
  heading.id = "status-history";
  wrapper.appendChild(heading);

  // Move (not clone) the timeline into the wrapper and make it visible.
  timeline.style.display = "";
  wrapper.appendChild(timeline);

  article.appendChild(wrapper);
}
