export const THEME_KEY = "theme";

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

const THEMES: readonly Theme[] = ["light", "dark", "system"];

function prefersDark(): boolean {
  return (
    typeof window !== "undefined" &&
    typeof window.matchMedia === "function" &&
    window.matchMedia("(prefers-color-scheme: dark)").matches
  );
}

export function resolveTheme(theme: Theme): "light" | "dark" {
  if (theme === "light" || theme === "dark") return theme;

  return prefersDark() ? "dark" : "light";
}

export function readTheme(): Theme {
  if (typeof localStorage === "undefined") return "system";

  const stored = localStorage.getItem(THEME_KEY);

  return THEMES.includes(stored as Theme) ? (stored as Theme) : "system";
}

/** Browser-chrome colors per resolved theme; must match `--background` in index.css. */
const THEME_COLORS = { light: "#ffffff", dark: "#0a0a0a" } as const;

export function applyTheme(theme: Theme): void {
  if (typeof document === "undefined") return;

  const resolved = resolveTheme(theme);

  document.documentElement.classList.toggle("dark", resolved === "dark");
  document
    .querySelector('meta[name="theme-color"]')
    ?.setAttribute("content", THEME_COLORS[resolved]);
}
