import { ref, watchEffect } from "vue";

function getStoredTheme(): string {
  return localStorage.getItem("theme") || "system";
}

const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)").matches;

const isDarkMode = ref<boolean>(determineInitialMode(getStoredTheme()));

function determineInitialMode(theme: string): boolean {
  if (theme === "dark") return true;
  if (theme === "light") return false;
  return prefersDarkScheme;
}

function setDarkModeClass(): void {
  const htmlElement = document.getElementById("app-html");
  if (htmlElement) {
    if (isDarkMode.value) {
      htmlElement.classList.add("dark");
    } else {
      htmlElement.classList.remove("dark");
    }
  }
}

function setTheme(theme: string): void {
  if (theme === "system") {
    localStorage.removeItem("theme");
    isDarkMode.value = determineInitialMode(getStoredTheme());
  } else {
    localStorage.setItem("theme", theme);
    isDarkMode.value = determineInitialMode(theme);
  }
  setDarkModeClass();
}

function toggleDarkMode(): void {
  if (getStoredTheme() === "dark") {
    setTheme("light");
  } else {
    setTheme("dark");
  }
}

setDarkModeClass();

// Observa o tema do sistema operacional
watchEffect(() => {
  const mediaQueryList = window.matchMedia("(prefers-color-scheme: dark)");
  function handleChange() {
    if (getStoredTheme() === "system") {
      isDarkMode.value = mediaQueryList.matches;
      setDarkModeClass();
    }
  }

  mediaQueryList.addEventListener("change", handleChange);
  return () => mediaQueryList.removeEventListener("change", handleChange);
});

export { isDarkMode, toggleDarkMode, setTheme };
