(() => {
  "use strict";

  const MOBILE_QUERY = matchMedia("(max-width: 767px)");
  let backdrop = null;
  let drawer = null;
  let trigger = null;
  let header = null;
  let mutationObserver = null;
  let setupTimer = null;

  function isArchitectDrawer(candidate) {
    if (!candidate) return false;
    const text = candidate.textContent || "";
    return (
      candidate.tagName === "ASIDE" &&
      text.includes("Enterprise RAG") &&
      text.includes("Cloud Compare") &&
      text.includes("Governance")
    );
  }

  function locateElements() {
    const asides = [...document.querySelectorAll("aside")];
    drawer = asides.find(isArchitectDrawer) || null;
    if (!drawer) return false;

    const nav = drawer.querySelector("nav");
    header = document.querySelector("header");
    trigger =
      header?.querySelector("button.md\\:hidden") ||
      header?.querySelector("button");

    if (!nav || !header || !trigger) return false;

    drawer.classList.add("ai-architect-drawer");
    header.classList.add("ai-architect-header");
    trigger.classList.add("ai-menu-trigger");
    trigger.setAttribute("aria-label", "Open AI Architect navigation");
    trigger.setAttribute("aria-controls", "ai-architect-navigation");
    drawer.id = "ai-architect-navigation";

    const main = drawer.parentElement?.querySelector("main");
    if (main) main.classList.add("ai-architect-main");

    if (!drawer.querySelector(".ai-drawer-heading")) {
      const heading = document.createElement("div");
      heading.className = "ai-drawer-heading";
      heading.innerHTML = `
        <div class="ai-drawer-heading__copy">
          <strong>Architecture Modules</strong>
          <span>14 interactive workspaces</span>
        </div>
        <button class="ai-drawer-close" type="button" aria-label="Close navigation"></button>
      `;
      drawer.insertBefore(heading, nav);
      heading.querySelector(".ai-drawer-close").addEventListener("click", closeDrawer);
    }

    if (!backdrop) {
      backdrop = document.createElement("button");
      backdrop.type = "button";
      backdrop.className = "ai-nav-backdrop";
      backdrop.setAttribute("aria-label", "Close navigation");
      document.body.appendChild(backdrop);
      backdrop.addEventListener("click", closeDrawer);
    }

    nav.querySelectorAll("a").forEach(link => {
      if (link.dataset.aiNavBound === "true") return;
      link.dataset.aiNavBound = "true";
      link.addEventListener("click", () => {
        requestAnimationFrame(syncState);
      });
    });

    if (!mutationObserver) {
      mutationObserver = new MutationObserver(syncState);
      mutationObserver.observe(drawer, {
        attributes: true,
        attributeFilter: ["class", "style"]
      });
    }

    syncState();
    return true;
  }

  function drawerIsOpen() {
    if (!drawer || !MOBILE_QUERY.matches) return false;
    const style = getComputedStyle(drawer);
    return (
      !drawer.classList.contains("hidden") &&
      style.display !== "none" &&
      style.visibility !== "hidden"
    );
  }

  function syncState() {
    if (!drawer || !trigger || !backdrop) return;

    const open = drawerIsOpen();
    trigger.setAttribute("aria-expanded", String(open));
    trigger.setAttribute(
      "aria-label",
      open ? "Close AI Architect navigation" : "Open AI Architect navigation"
    );
    backdrop.classList.toggle("is-visible", open);
    document.documentElement.classList.toggle("ai-architect-nav-open", open);
    document.body.classList.toggle("ai-architect-nav-open", open);

    if (!open) {
      backdrop.setAttribute("tabindex", "-1");
    } else {
      backdrop.removeAttribute("tabindex");
    }
  }

  function closeDrawer() {
    if (!drawerIsOpen()) return;
    trigger?.click();
    requestAnimationFrame(syncState);
    trigger?.focus({ preventScroll: true });
  }

  function setup() {
    clearTimeout(setupTimer);
    if (locateElements()) return;
    setupTimer = setTimeout(setup, 120);
  }

  addEventListener("keydown", event => {
    if (event.key === "Escape" && drawerIsOpen()) {
      event.preventDefault();
      closeDrawer();
    }
  });

  addEventListener("resize", () => {
    if (!MOBILE_QUERY.matches) {
      backdrop?.classList.remove("is-visible");
      document.documentElement.classList.remove("ai-architect-nav-open");
      document.body.classList.remove("ai-architect-nav-open");
    }
    requestAnimationFrame(syncState);
  }, { passive: true });

  addEventListener("orientationchange", () => {
    setTimeout(syncState, 120);
  }, { passive: true });

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", setup, { once: true });
  } else {
    setup();
  }
})();
