(function () {
  const roots = Array.from(document.querySelectorAll("[data-user-menu-root]"));
  if (!roots.length) return;

  function closeMenu(root) {
    const button = root.querySelector("[data-user-menu-button]");
    const panel = root.querySelector("[data-user-menu-panel]");
    panel?.classList.add("ui-hidden");
    button?.setAttribute("aria-expanded", "false");
  }

  function toggleMenu(root) {
    const button = root.querySelector("[data-user-menu-button]");
    const panel = root.querySelector("[data-user-menu-panel]");
    const willOpen = panel?.classList.contains("ui-hidden");

    roots.forEach((currentRoot) => {
      if (currentRoot !== root) {
        closeMenu(currentRoot);
      }
    });

    if (!button || !panel) return;
    panel.classList.toggle("ui-hidden", !willOpen);
    button.setAttribute("aria-expanded", willOpen ? "true" : "false");
  }

  roots.forEach((root) => {
    const button = root.querySelector("[data-user-menu-button]");
    button?.addEventListener("click", () => toggleMenu(root));
  });

  document.addEventListener("click", (event) => {
    roots.forEach((root) => {
      if (!root.contains(event.target)) {
        closeMenu(root);
      }
    });
  });
})();
