---

---

<button
  class="theme-toggle-btn relative rounded-full p-2 text-foreground transition-colors hover:bg-foreground/10 focus:outline-none"
  aria-label="Toggle theme"
>
  <!-- Sun icon -->
  <svg
    class="sun-icon hidden h-5 w-5"
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
  >
    <circle cx="12" cy="12" r="4"></circle>
    <path d="M12 2v2"></path>
    <path d="M12 20v2"></path>
    <path d="m4.93 4.93 1.41 1.41"></path>
    <path d="m17.66 17.66 1.41 1.41"></path>
    <path d="M2 12h2"></path>
    <path d="M20 12h2"></path>
    <path d="m6.34 17.66-1.41 1.41"></path>
    <path d="m19.07 4.93-1.41 1.41"></path>
  </svg>
  <!-- Moon icon -->
  <svg
    class="moon-icon hidden h-5 w-5"
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
  >
    <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"></path>
  </svg>
</button>

<script>
  document.addEventListener("astro:page-load", () => {
    const updateIcons = () => {
      const theme =
        document.documentElement.getAttribute("data-theme") || "light";
      const btns = document.querySelectorAll(".theme-toggle-btn");

      btns.forEach((btn) => {
        const sunIcon = btn.querySelector(".sun-icon");
        const moonIcon = btn.querySelector(".moon-icon");

        if (theme === "dark") {
          sunIcon?.classList.remove("hidden");
          moonIcon?.classList.add("hidden");
        } else {
          sunIcon?.classList.add("hidden");
          moonIcon?.classList.remove("hidden");
        }
      });
    };

    // Initialize
    updateIcons();

    // Re-run on clicks
    const btns = document.querySelectorAll(".theme-toggle-btn");
    btns.forEach((btn) => {
      // Clone to remove old event listeners and avoid multiple triggers
      const newBtn = btn.cloneNode(true);
      if (btn.parentNode) {
        btn.parentNode.replaceChild(newBtn, btn);
      }

      newBtn.addEventListener("click", () => {
        const currentTheme =
          document.documentElement.getAttribute("data-theme");
        const newTheme = currentTheme === "dark" ? "light" : "dark";

        document.documentElement.setAttribute("data-theme", newTheme);
        localStorage.setItem("theme", newTheme);
        updateIcons();
      });
    });
  });
</script>
