function initMenubar() {
  const menubar = document.querySelector<HTMLDivElement>(".menubar")!;
  const hamburger = menubar.querySelector<HTMLButtonElement>(".hamburger")!;
  const backdrop = document.querySelector<HTMLDivElement>(".mobile-backdrop")!;
  const drawer = document.querySelector<HTMLDivElement>("#mobile-drawer")!;
  const triggers = document.querySelectorAll<HTMLButtonElement>(
    ".menu-trigger",
  );
  const panels = document.querySelectorAll<HTMLDivElement>(".menu-panel");

  // mobile check
  const mq = globalThis.matchMedia("(max-width: 768px)");

  function moveToDrawer() {
    if (drawer.children.length > 0) return; // already moved

    let fileGroup: HTMLDivElement | null = null;
    let settingsGroup: HTMLDivElement | null = null;
    for (
      const g of menubar.querySelectorAll<HTMLDivElement>(
        ":scope > .menu-group",
      )
    ) {
      if (g.querySelector("[data-menu=file]")) fileGroup = g;
      if (g.querySelector("[data-menu=output]")) settingsGroup = g;
    }
    const visParams = document.querySelector<HTMLDivElement>("#vis-params")!;
    const imgGroup = document.querySelector<HTMLDivElement>("#img-group")!;

    // section label helper
    const label = (text: string) => {
      const el = document.createElement("div");
      el.className = "drawer-section-label";
      el.textContent = text;
      return el;
    };

    if (visParams) {
      drawer.appendChild(label("visualizer params"));
      drawer.appendChild(visParams);
    }
    if (imgGroup) {
      drawer.appendChild(imgGroup);
    }
    if (fileGroup) {
      drawer.appendChild(label("file"));
      drawer.appendChild(fileGroup);
    }
    if (settingsGroup) {
      drawer.appendChild(label("settings"));
      drawer.appendChild(settingsGroup);
    }
  }

  function moveBack() {
    const visGroup = document.querySelector<HTMLDivElement>("#vis-group")!;
    const visSelect = visGroup.querySelector("#vis-select")!;

    while (drawer.firstChild) {
      const child = drawer.firstChild;
      if (child instanceof HTMLElement && child.id === "vis-params") {
        visGroup.appendChild(child);
      } else if (
        child instanceof HTMLElement && child.id === "img-group"
      ) {
        visSelect.after(child);
      } else if (
        child instanceof HTMLElement && child.classList.contains("menu-group")
      ) {
        menubar.insertBefore(child, visGroup);
      } else {
        child.remove();
      }
    }
  }

  function applyLayout() {
    if (mq.matches) {
      moveToDrawer();
    } else {
      moveBack();
    }
  }

  applyLayout();
  mq.addEventListener("change", applyLayout);

  function isOpen() {
    return !drawer.classList.contains("hidden");
  }

  function openDrawer() {
    drawer.classList.remove("hidden");
    backdrop.classList.remove("hidden");
    hamburger.textContent = "✕";
    document.body.classList.add("mobile-open");
  }

  function closeDrawer() {
    drawer.classList.add("hidden");
    backdrop.classList.add("hidden");
    hamburger.textContent = "☰";
    document.body.classList.remove("mobile-open");
    closeAll();
  }

  hamburger.addEventListener("click", (e) => {
    e.stopPropagation();
    if (isOpen()) {
      closeDrawer();
    } else {
      openDrawer();
    }
  });

  backdrop.addEventListener("click", () => {
    closeDrawer();
  });

  function panelFor(trigger: HTMLElement): HTMLDivElement | null {
    const menu = trigger.dataset.menu;
    if (!menu) return null;
    return document.querySelector(`#panel-${menu}`);
  }

  function closeAll() {
    panels.forEach((p) => p.classList.add("hidden"));
    triggers.forEach((t) => t.classList.remove("open"));
  }

  function open(trigger: HTMLButtonElement) {
    const panel = panelFor(trigger);
    if (!panel) return;
    panels.forEach((p) => p.classList.add("hidden"));
    triggers.forEach((t) => t.classList.remove("open"));
    panel.classList.remove("hidden");
    trigger.classList.add("open");
  }

  // click on trigger → open / toggle
  triggers.forEach((trigger) => {
    trigger.addEventListener("click", (e) => {
      e.stopPropagation();
      if (trigger.classList.contains("open")) {
        closeAll();
      } else {
        open(trigger);
      }
    });
  });

  // hover to switch (macOS style) — desktop only
  triggers.forEach((trigger) => {
    trigger.addEventListener("mouseenter", () => {
      if (mq.matches) return; // no hover switching on mobile
      const anyOpen = document.querySelector(".menu-trigger.open");
      if (anyOpen) {
        open(trigger);
      }
    });
  });

  // click outside → close
  document.addEventListener("click", (e) => {
    const target = e.target as HTMLElement;
    const clickedInside = target.closest(".menubar");
    const clickedDrawer = target.closest("#mobile-drawer");
    if (!clickedInside && !clickedDrawer) {
      if (mq.matches) {
        closeDrawer();
      } else {
        closeAll();
      }
    }
  });

  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape") {
      if (mq.matches) {
        closeDrawer();
      } else {
        closeAll();
      }
    }
  });

  // clicks on selects/inputs inside panels shouldn't close the panel
  panels.forEach((panel) => {
    panel.addEventListener("click", (e) => e.stopPropagation());
  });
}

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initMenubar);
} else {
  initMenubar();
}
