import { loadUiPrefs, saveUiPrefs, type ThemePreference } from "./i18n/prefs";

export type { ThemePreference };
export type ResolvedTheme = "light" | "dark";

export function isThemePreference(v: unknown): v is ThemePreference {
  return v === "light" || v === "dark" || v === "system";
}

export function loadThemePreference(): ThemePreference {
  return loadUiPrefs().theme;
}

/** 只更新 uiPrefs 裡的 theme，保留 locale／currency */
export function saveThemePreference(theme: ThemePreference): void {
  saveUiPrefs({ theme });
}

export function getSystemPrefersDark(): boolean {
  try {
    return window.matchMedia("(prefers-color-scheme: dark)").matches;
  } catch {
    return false;
  }
}

export function resolveTheme(pref: ThemePreference): ResolvedTheme {
  if (pref === "dark") return "dark";
  if (pref === "light") return "light";
  return getSystemPrefersDark() ? "dark" : "light";
}

/** 寫入 <html data-theme> 與 color-scheme */
export function applyResolvedTheme(resolved: ResolvedTheme): void {
  const root = document.documentElement;
  root.setAttribute("data-theme", resolved);
  root.style.colorScheme = resolved;
}
