---
import DarkModeScriptInline from "./DarkModeScriptInline.astro";
---

<DarkModeScriptInline />

<script>
  type ColorScheme = "auto" | "dark" | "light" | undefined;

  const colorSchemeSetup = () => {
    let colorScheme: ColorScheme = localStorage.colorScheme;
    if (!colorScheme || colorScheme === "auto") {
      colorScheme = matchMedia("(prefers-color-scheme:dark)").matches ? "dark" : "light";
    }
    const toggleColorScheme = (e: MouseEvent) => {
      e.preventDefault();
      if (colorScheme === "dark") {
        colorScheme = "light";
        document.body.classList.remove("dark");
      } else {
        colorScheme = "dark";
        document.body.classList.add("dark");
      }
      localStorage.colorScheme = colorScheme;
    };
    document.querySelectorAll<HTMLElementTagNameMap["button"]>("button[data-dark-mode]").forEach((button) => {
      button.addEventListener("click", toggleColorScheme);
      button.classList.remove("hidden");
      button.style.removeProperty("display");
      button.setAttribute("aria-hidden", "false");
    });
  };

  colorSchemeSetup();
</script>
