(function () {
  const body = document.body;
  const sidebar = document.querySelector("[data-app-shell-sidebar]");
  const toggle = document.querySelector("[data-app-shell-toggle]");
  const backdrop = document.querySelector("[data-app-shell-backdrop]");
  const navItems = Array.from(document.querySelectorAll("[data-app-shell-nav-item]"));

  if (!sidebar || !toggle) return;

  const storageKey = "app-shell-sidebar-expanded";
  const desktopQuery = globalThis.matchMedia("(min-width: 64rem)");

  function isDesktop() {
    return desktopQuery.matches;
  }

  function syncToggleState() {
    const isExpanded = body.classList.contains("is-app-shell-expanded");
    const isOpen = body.classList.contains("is-app-shell-open");
    const expanded = isDesktop() ? isExpanded : isOpen;
    toggle.setAttribute("aria-expanded", expanded ? "true" : "false");
  }

  function applyDesktopState(expanded) {
    body.classList.toggle("is-app-shell-expanded", expanded);
    body.classList.remove("is-app-shell-open");
    syncToggleState();
  }

  function setMobileOpen(nextState) {
    body.classList.toggle("is-app-shell-open", nextState);
    syncToggleState();
  }

  function restoreDesktopPreference() {
    const saved = globalThis.localStorage?.getItem(storageKey);
    applyDesktopState(saved === "true");
  }

  function handleToggle() {
    if (isDesktop()) {
      const nextState = !body.classList.contains("is-app-shell-expanded");
      globalThis.localStorage?.setItem(storageKey, nextState ? "true" : "false");
      applyDesktopState(nextState);
      return;
    }
    setMobileOpen(!body.classList.contains("is-app-shell-open"));
  }

  function handleViewportChange() {
    if (isDesktop()) {
      restoreDesktopPreference();
      return;
    }
    body.classList.remove("is-app-shell-expanded");
    syncToggleState();
  }

  toggle.addEventListener("click", handleToggle);
  backdrop?.addEventListener("click", () => setMobileOpen(false));
  navItems.forEach((item) => {
    item.addEventListener("click", () => {
      if (!isDesktop()) {
        setMobileOpen(false);
      }
    });
  });

  document.addEventListener("keydown", (event) => {
    if (event.key === "Escape" && body.classList.contains("is-app-shell-open")) {
      setMobileOpen(false);
    }
  });

  desktopQuery.addEventListener("change", handleViewportChange);
  restoreDesktopPreference();
})();
