import { KEYS } from "../../data/mock/keys";
import { readJson, writeJson } from "../storage";
import {
  isAppCurrency,
  isAppLocale,
  type AppCurrency,
  type AppLocale,
} from "./types";

/** 與 lib/theme 同步；此處內聯避免循環 import */
export type ThemePreference = "light" | "dark" | "system";

export type UiPrefs = {
  locale: AppLocale;
  currency: AppCurrency;
  theme: ThemePreference;
};

const DEFAULT: UiPrefs = {
  locale: "zh-TW",
  currency: "TWD",
  theme: "system",
};

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

export function loadUiPrefs(): UiPrefs {
  const raw = readJson<Partial<UiPrefs> | null>(KEYS.uiPrefs, null);
  const locale = raw?.locale && isAppLocale(raw.locale) ? raw.locale : detectBrowserLocale();
  const currency =
    raw?.currency && isAppCurrency(raw.currency) ? raw.currency : DEFAULT.currency;
  const theme = raw?.theme && isThemePref(raw.theme) ? raw.theme : DEFAULT.theme;
  return { locale, currency, theme };
}

/** 合併寫入，避免只改語言時把 theme 洗掉 */
export function saveUiPrefs(prefs: Partial<UiPrefs>): void {
  const cur = loadUiPrefs();
  writeJson(KEYS.uiPrefs, {
    locale: prefs.locale ?? cur.locale,
    currency: prefs.currency ?? cur.currency,
    theme: prefs.theme ?? cur.theme,
  });
}

function detectBrowserLocale(): AppLocale {
  try {
    const lang = (navigator.language || "").toLowerCase();
    if (lang.startsWith("zh")) return "zh-TW";
    if (lang.startsWith("en")) return "en";
  } catch {
    /* ignore */
  }
  return DEFAULT.locale;
}
