import { useEffect, useState } from "react";

export type ThemePreference = "light" | "dark";

const THEME_STORAGE_KEY = "theme";

function readThemePreference(): ThemePreference {
  if (typeof window === "undefined") {
    return "light";
  }

  return window.localStorage.getItem(THEME_STORAGE_KEY) === "dark"
    ? "dark"
    : "light";
}

export function useThemePreference() {
  const [theme, setTheme] = useState<ThemePreference>(readThemePreference);

  useEffect(() => {
    document.documentElement.dataset.theme = theme;
    document.documentElement.style.colorScheme = theme;
    window.localStorage.setItem(THEME_STORAGE_KEY, theme);
  }, [theme]);

  return {
    theme,
    setTheme,
    toggleTheme: () =>
      setTheme((currentTheme) =>
        currentTheme === "light" ? "dark" : "light",
      ),
  };
}
