export type Theme = "light" | "dark" | "system";

const STORAGE_KEY = "nowhatever-theme";
const VALID_THEMES: Theme[] = ["light", "dark", "system"];

export function getStoredTheme(): Theme {
  if (typeof window === "undefined") return "system";
  const stored = localStorage.getItem(STORAGE_KEY);
  return stored && VALID_THEMES.includes(stored as Theme)
    ? (stored as Theme)
    : "system";
}

export function setStoredTheme(theme: Theme): void {
  if (typeof window === "undefined") return;
  localStorage.setItem(STORAGE_KEY, theme);
  applyTheme(theme);
}

function resolveTheme(theme: Theme): "light" | "dark" {
  if (theme !== "system") return theme;
  if (typeof window === "undefined") return "dark";
  return window.matchMedia("(prefers-color-scheme: light)").matches
    ? "light"
    : "dark";
}

export function applyTheme(theme: Theme): void {
  if (typeof window === "undefined") return;
  const resolved = resolveTheme(theme);
  document.documentElement.setAttribute("data-theme", resolved);
}

export function initTheme(): void {
  if (typeof window === "undefined") return;
  const theme = getStoredTheme();
  applyTheme(theme);

  if (theme === "system") {
    window
      .matchMedia("(prefers-color-scheme: light)")
      .addEventListener("change", () => applyTheme("system"));
  }
}
