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

export const UI_THEME_STORAGE_KEY = "powerup.ui.theme";

export function normalizeUiTheme(value: string | null | undefined): UiTheme {
  return value === "light" ? "light" : "dark";
}

export function readStoredUiTheme(): UiTheme {
  if (typeof window === "undefined") {
    return "dark";
  }
  return normalizeUiTheme(window.localStorage.getItem(UI_THEME_STORAGE_KEY));
}

export function applyUiTheme(theme: UiTheme): void {
  if (typeof document === "undefined") {
    return;
  }
  document.documentElement.setAttribute("data-theme", theme);
  document.documentElement.style.colorScheme = theme;
}

export function storeUiTheme(theme: UiTheme): void {
  if (typeof window !== "undefined") {
    window.localStorage.setItem(UI_THEME_STORAGE_KEY, theme);
  }
  applyUiTheme(theme);
}

export function initializeUiTheme(): UiTheme {
  const theme = readStoredUiTheme();
  applyUiTheme(theme);
  return theme;
}
