(function () {
  const scriptEl = document.currentScript;
  const API_URL = scriptEl?.dataset?.apiUrl;

  window.toggleTheme = () => {
    const currentTheme = document.documentElement.getAttribute("data-theme");
    const newTheme = currentTheme === "dark" ? "light" : "dark";
    
    // Toggle the dark class for Tailwind
    if (newTheme === "dark") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
    
    // Dispatch event for astro-themes and other listeners
    document.dispatchEvent(new CustomEvent("set-theme", { detail: newTheme }));
  };

  window.handleLogout = async () => {
    try {
      await fetch(`${API_URL}/auth/logout`, {
        method: "POST",
        credentials: "include",
      });
    } catch (error) {
      console.error("Logout failed", error);
    } finally {
      window.location.href = "/";
    }
  };

  function initMobileMenu() {
    const menuBtn = document.getElementById("mobile-menu-btn");
    const mobileMenu = document.getElementById("mobile-menu");
    const menuIcon = document.getElementById("menu-icon");
    const closeIcon = document.getElementById("close-icon");

    if (!menuBtn || !mobileMenu || !menuIcon || !closeIcon) {
      return;
    }

    const newMenuBtn = menuBtn.cloneNode(true);
    menuBtn.parentNode.replaceChild(newMenuBtn, menuBtn);

    newMenuBtn.addEventListener("click", (e) => {
      e.stopPropagation();
      const isOpen = mobileMenu.classList.contains("open");

      if (isOpen) {
        mobileMenu.classList.remove("open");
        menuIcon.style.display = "block";
        closeIcon.style.display = "none";
      } else {
        mobileMenu.classList.add("open");
        menuIcon.style.display = "none";
        closeIcon.style.display = "block";
      }
    });

    const mobileLinks = mobileMenu.querySelectorAll("a");
    mobileLinks.forEach((link) => {
      link.addEventListener("click", () => {
        mobileMenu.classList.remove("open");
        menuIcon.style.display = "block";
        closeIcon.style.display = "none";
      });
    });

    const closeHandler = (e) => {
      if (!mobileMenu.contains(e.target) && !newMenuBtn.contains(e.target)) {
        if (mobileMenu.classList.contains("open")) {
          mobileMenu.classList.remove("open");
          menuIcon.style.display = "block";
          closeIcon.style.display = "none";
        }
      }
    };

    document.removeEventListener("click", closeHandler);
    document.addEventListener("click", closeHandler);
  }

  const ready = () => initMobileMenu();

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

  document.addEventListener("astro:page-load", initMobileMenu);
})();
