import { LS, readAccountMerged, writeAccount } from "./storage";

type Mode = "dark" | "light";
export type Scheme = "midnight" | "forest" | "slate" | "youtube" | "starship" | "matrix";

export const SCHEMES: { id: Scheme; name: string; swatch: string }[] = [
  { id: "midnight", name: "Midnight", swatch: "#6d8cff" },
  { id: "forest", name: "Forest", swatch: "#2dd4bf" },
  { id: "slate", name: "Slate", swatch: "#e8913c" },
  { id: "youtube", name: "YouTube", swatch: "#ff3b46" },
  { id: "starship", name: "Starship", swatch: "#38b6ff" },
  { id: "matrix", name: "Matrix", swatch: "#46b87c" },
];

export interface ThemePrefs {
  mode: Mode;
  scheme: Scheme;
  fontScale: number;
  /** Show the per-scheme background image (dark theme only); off = flat colour. */
  bgImage: boolean;
  /** How strongly the background image is faded out, 0–100% (higher = fainter). */
  bgFade: number;
  /** Show the floating glass/theme tuner (a secondary "geek toy"); off by default. */
  showTuner: boolean;
}

export const DEFAULT_THEME: ThemePrefs = {
  mode: "dark",
  scheme: "midnight",
  fontScale: 1.06,
  bgImage: true,
  bgFade: 60,
  showTuner: false,
};

export function applyTheme(t: ThemePrefs): void {
  const el = document.documentElement;
  el.dataset.theme = t.mode;
  el.dataset.scheme = t.scheme;
  el.style.setProperty("--font-scale", String(t.fontScale));
  if (typeof t.bgFade === "number") el.style.setProperty("--bg-fade", `${t.bgFade}%`);
}

export function loadLocalTheme(): ThemePrefs {
  return readAccountMerged(LS.theme, DEFAULT_THEME);
}

export function saveLocalTheme(t: ThemePrefs): void {
  writeAccount(LS.theme, t);
}
