import { createStore } from "./createStore";

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

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

interface ThemeState {
  theme: Theme;
}

// Preference is held in memory only (no localStorage), defaulting to the OS setting.
export const themeStore = createStore<ThemeState>({ theme: detectInitialTheme() });

function applyTheme(theme: Theme): void {
  const root = document.documentElement;
  root.classList.toggle("dark", theme === "dark");
}

export function initTheme(): void {
  applyTheme(themeStore.getState().theme);
}

export function toggleTheme(): void {
  const next: Theme = themeStore.getState().theme === "dark" ? "light" : "dark";
  themeStore.setState({ theme: next });
  applyTheme(next);
}
