import { defineStore } from "pinia";

export type ThemeName =
  | "enterprise"
  | "default"
  | "anthropic"
  | "mono"
  | "midnight"
  | "rose"
  | "lagoon"
  | "sunset"
  | "forest"
  | "ocean"
  | "lavender";
export type ThemeMode = "system" | "light" | "dark";
export type FontChoice = "auto" | "sans" | "serif";
export type RadiusChoice = "auto" | "0" | "0.3" | "0.5" | "0.75" | "1";
export type DensityChoice = "compact" | "default" | "comfortable" | "large";
export type SidebarChoice = "embedded" | "floating" | "edge";
export type LayoutChoice = "default" | "compact" | "fullscreen";
export type ContentWidthChoice = "full" | "centered";

export interface ThemeOption {
  name: ThemeName;
  label: string;
  primary: string;
  accent: string;
  soft: string;
  gradient: [string, string];
  tokens: {
    light: ThemeTokens;
    dark: ThemeTokens;
  };
}

interface ThemeTokens {
  surface: string;
  surfaceSoft: string;
  surfaceStrong: string;
  card: string;
  text: string;
  muted: string;
  line: string;
  lineSoft: string;
  primary: string;
  primarySoft: string;
  accent: string;
  accentSoft: string;
  sidebarBg: string;
  navText: string;
  navActiveBg: string;
  topbarBg: string;
  searchBg: string;
  controlBg: string;
  secondaryBg: string;
  secondaryHoverBg: string;
  secondaryHoverBorder: string;
  tableHeaderBg: string;
  tableRowHoverBg: string;
}

type LightThemeTokens = Omit<ThemeTokens, "primary" | "primarySoft" | "accent" | "accentSoft">;
type DarkThemeSeed = Omit<
  ThemeTokens,
  | "text"
  | "muted"
  | "navText"
  | "topbarBg"
  | "searchBg"
  | "controlBg"
  | "secondaryBg"
  | "secondaryHoverBg"
  | "secondaryHoverBorder"
  | "tableHeaderBg"
  | "tableRowHoverBg"
>;

interface ThemeSeed {
  name: ThemeName;
  label: string;
  primary: string;
  accent: string;
  soft: string;
  gradient: [string, string];
  light: LightThemeTokens;
  dark: ThemeTokens;
}

type StoredSetting =
  | ThemeName
  | ThemeMode
  | FontChoice
  | RadiusChoice
  | DensityChoice
  | SidebarChoice
  | LayoutChoice
  | ContentWidthChoice;

const THEME_KEY = "financial-system-theme";
const THEME_MODE_KEY = "financial-system-theme-mode";
const FONT_KEY = "financial-system-font";
const RADIUS_KEY = "financial-system-radius";
const DENSITY_KEY = "financial-system-density";
const SIDEBAR_KEY = "financial-system-sidebar";
const LAYOUT_KEY = "financial-system-layout";
const CONTENT_WIDTH_KEY = "financial-system-content-width";
const APPEARANCE_VERSION_KEY = "financial-system-appearance-version";
const CURRENT_APPEARANCE_VERSION = "2026-06-enterprise-clean";

export const DEFAULT_THEME_SETTINGS = {
  theme: "enterprise" as ThemeName,
  mode: "light" as ThemeMode,
  font: "sans" as FontChoice,
  radius: "0.3" as RadiusChoice,
  density: "compact" as DensityChoice,
  sidebar: "embedded" as SidebarChoice,
  layout: "default" as LayoutChoice,
  contentWidth: "full" as ContentWidthChoice,
};

const legacyThemeMap: Record<string, ThemeName> = {
  navy: "enterprise",
  blue: "ocean",
  emerald: "forest",
  burgundy: "rose",
};

migrateLegacyAppearanceDefaults();

const themeSeeds: ThemeSeed[] = [
  {
    name: "enterprise",
    label: "企业清爽",
    primary: "#22313f",
    accent: "#2563eb",
    soft: "#e8f0ff",
    gradient: ["#22313f", "#2563eb"],
    light: createLightSeed({
      primary: "#22313f",
      accent: "#2563eb",
      soft: "#e8f0ff",
      surface: "#f5f7fa",
      surfaceSoft: "#eef2f7",
      surfaceStrong: "#d9e1ec",
      sidebarBg: "#ffffff",
      navActiveBg: "#e8f0ff",
    }),
    dark: createDarkSeed({
      primary: "#edf4ff",
      primarySoft: "#b8cff8",
      accent: "#7aa7ff",
      accentSoft: "rgba(122, 167, 255, 0.18)",
      surface: "#101418",
      surfaceSoft: "#171d23",
      surfaceStrong: "#26313c",
      card: "#151a20",
      sidebarBg: "#141a20",
      navActiveBg: "#233750",
      line: "#303b46",
      lineSoft: "#242d36",
    }),
  },
  {
    name: "default",
    label: "默认",
    primary: "#171717",
    accent: "#8c8c8c",
    soft: "#ececec",
    gradient: ["#151515", "#f4f4f1"],
    light: createLightSeed({
      primary: "#171717",
      accent: "#626262",
      soft: "#ececec",
      surface: "#f7f7f5",
      surfaceSoft: "#eeeeeb",
      surfaceStrong: "#dfdfdc",
      sidebarBg: "#eeeeeb",
      navActiveBg: "#e1e1dd",
    }),
    dark: createDarkSeed({
      primary: "#f4f1eb",
      primarySoft: "#ded8cf",
      accent: "#b9b6ad",
      accentSoft: "rgba(185, 182, 173, 0.18)",
      surface: "#141411",
      surfaceSoft: "#1d1c18",
      surfaceStrong: "#2b2925",
      card: "#191814",
      sidebarBg: "#1a1915",
      navActiveBg: "#28251f",
      line: "#34312a",
      lineSoft: "#282620",
    }),
  },
  {
    name: "anthropic",
    label: "Anthropic",
    primary: "#8f563e",
    accent: "#ed8b6d",
    soft: "#fde4d8",
    gradient: ["#fbe2d4", "#ea7b5d"],
    light: createLightSeed({
      primary: "#6f3e2a",
      accent: "#dd7154",
      soft: "#fde4d8",
      surface: "#fff8f4",
      surfaceSoft: "#f6e7df",
      surfaceStrong: "#edcdbf",
      sidebarBg: "#f6e7df",
      navActiveBg: "#f1d3c5",
    }),
    dark: createDarkSeed({
      primary: "#f4dfd3",
      primarySoft: "#e7b7a4",
      accent: "#f28a6a",
      accentSoft: "rgba(242, 138, 106, 0.18)",
      surface: "#16130f",
      surfaceSoft: "#211913",
      surfaceStrong: "#392417",
      card: "#1b1712",
      sidebarBg: "#201713",
      navActiveBg: "#5b3425",
      line: "#403029",
      lineSoft: "#2b211c",
    }),
  },
  {
    name: "mono",
    label: "超大字体简易",
    primary: "#202020",
    accent: "#a1a1a1",
    soft: "#eeeeee",
    gradient: ["#202020", "#eeeeee"],
    light: createLightSeed({
      primary: "#202020",
      accent: "#6d6d6d",
      soft: "#eeeeee",
      surface: "#fafafa",
      surfaceSoft: "#eeeeee",
      surfaceStrong: "#dcdcdc",
      sidebarBg: "#eeeeee",
      navActiveBg: "#e2e2e2",
    }),
    dark: createDarkSeed({
      primary: "#f5f5f5",
      primarySoft: "#dddddd",
      accent: "#c8c8c8",
      accentSoft: "rgba(200, 200, 200, 0.16)",
      surface: "#121212",
      surfaceSoft: "#1f1f1f",
      surfaceStrong: "#303030",
      card: "#181818",
      sidebarBg: "#1b1b1b",
      navActiveBg: "#2b2b2b",
      line: "#3a3a3a",
      lineSoft: "#2a2a2a",
    }),
  },
  {
    name: "midnight",
    label: "暗夜",
    primary: "#1d3150",
    accent: "#2d5da8",
    soft: "#e6efff",
    gradient: ["#466f5a", "#9b7390"],
    light: createLightSeed({
      primary: "#1d3150",
      accent: "#2d5da8",
      soft: "#e6efff",
      surface: "#f5f8fc",
      surfaceSoft: "#e8eef6",
      surfaceStrong: "#d3deed",
      sidebarBg: "#e6edf6",
      navActiveBg: "#d5e1f2",
    }),
    dark: createDarkSeed({
      primary: "#dce8ff",
      primarySoft: "#a8c5ef",
      accent: "#6ca1ee",
      accentSoft: "rgba(108, 161, 238, 0.18)",
      surface: "#10151e",
      surfaceSoft: "#162235",
      surfaceStrong: "#213451",
      card: "#131b28",
      sidebarBg: "#17263a",
      navActiveBg: "#1d3b64",
      line: "#2c3d55",
      lineSoft: "#213047",
    }),
  },
  {
    name: "rose",
    label: "玫瑰花园",
    primary: "#8f2044",
    accent: "#f13d72",
    soft: "#ffe2ea",
    gradient: ["#f22366", "#f77c99"],
    light: createLightSeed({
      primary: "#8f2044",
      accent: "#e53967",
      soft: "#ffe2ea",
      surface: "#fff7fa",
      surfaceSoft: "#fde9f0",
      surfaceStrong: "#f6ccd9",
      sidebarBg: "#fde9f0",
      navActiveBg: "#f8d4df",
    }),
    dark: createDarkSeed({
      primary: "#ffdce7",
      primarySoft: "#f7a5be",
      accent: "#ff6d97",
      accentSoft: "rgba(255, 109, 151, 0.18)",
      surface: "#171116",
      surfaceSoft: "#26141c",
      surfaceStrong: "#471d2d",
      card: "#1d1218",
      sidebarBg: "#25131b",
      navActiveBg: "#5a2136",
      line: "#442934",
      lineSoft: "#2f1d25",
    }),
  },
  {
    name: "lagoon",
    label: "湖光",
    primary: "#006b5e",
    accent: "#08b997",
    soft: "#dcfbf4",
    gradient: ["#0fc69b", "#058b88"],
    light: createLightSeed({
      primary: "#006b5e",
      accent: "#08a88c",
      soft: "#dcfbf4",
      surface: "#f4fbf9",
      surfaceSoft: "#e0f4ef",
      surfaceStrong: "#c4e7de",
      sidebarBg: "#e0f4ef",
      navActiveBg: "#caeadf",
    }),
    dark: createDarkSeed({
      primary: "#d8fff6",
      primarySoft: "#86e4d0",
      accent: "#20d0ad",
      accentSoft: "rgba(32, 208, 173, 0.18)",
      surface: "#0f1715",
      surfaceSoft: "#112923",
      surfaceStrong: "#14483d",
      card: "#101d1a",
      sidebarBg: "#132820",
      navActiveBg: "#195745",
      line: "#27433b",
      lineSoft: "#1c312b",
    }),
  },
  {
    name: "sunset",
    label: "日落霞光",
    primary: "#b93f32",
    accent: "#f2765a",
    soft: "#ffe4d9",
    gradient: ["#df443f", "#fb805e"],
    light: createLightSeed({
      primary: "#9f392e",
      accent: "#ea674c",
      soft: "#ffe4d9",
      surface: "#fff8f4",
      surfaceSoft: "#f7e8df",
      surfaceStrong: "#f0ccb9",
      sidebarBg: "#f7e8df",
      navActiveBg: "#f4d4c3",
    }),
    dark: createDarkSeed({
      primary: "#ffe1d5",
      primarySoft: "#f4a089",
      accent: "#ff8a68",
      accentSoft: "rgba(255, 138, 104, 0.18)",
      surface: "#171210",
      surfaceSoft: "#281914",
      surfaceStrong: "#52271d",
      card: "#1d1512",
      sidebarBg: "#271814",
      navActiveBg: "#653123",
      line: "#442d25",
      lineSoft: "#2f201b",
    }),
  },
  {
    name: "forest",
    label: "森林低语",
    primary: "#1d6253",
    accent: "#4f7c86",
    soft: "#e0f2ed",
    gradient: ["#1b8d7e", "#51788c"],
    light: createLightSeed({
      primary: "#1d6253",
      accent: "#3f7881",
      soft: "#e0f2ed",
      surface: "#f4faf7",
      surfaceSoft: "#e4f1ec",
      surfaceStrong: "#cfe2dc",
      sidebarBg: "#e4f1ec",
      navActiveBg: "#d4e9e2",
    }),
    dark: createDarkSeed({
      primary: "#dbfff2",
      primarySoft: "#9dd6c7",
      accent: "#78aeb9",
      accentSoft: "rgba(120, 174, 185, 0.18)",
      surface: "#111817",
      surfaceSoft: "#172623",
      surfaceStrong: "#243f3b",
      card: "#141d1c",
      sidebarBg: "#172521",
      navActiveBg: "#254d45",
      line: "#2d4440",
      lineSoft: "#22322f",
    }),
  },
  {
    name: "ocean",
    label: "海风",
    primary: "#2148d8",
    accent: "#4964f2",
    soft: "#e7ecff",
    gradient: ["#315fe8", "#6464f3"],
    light: createLightSeed({
      primary: "#2148d8",
      accent: "#4964f2",
      soft: "#e7ecff",
      surface: "#f6f8ff",
      surfaceSoft: "#e9eeff",
      surfaceStrong: "#d6ddfb",
      sidebarBg: "#e9eeff",
      navActiveBg: "#d9e0ff",
    }),
    dark: createDarkSeed({
      primary: "#e0e6ff",
      primarySoft: "#aebcff",
      accent: "#7c92ff",
      accentSoft: "rgba(124, 146, 255, 0.18)",
      surface: "#11131d",
      surfaceSoft: "#181d35",
      surfaceStrong: "#24336c",
      card: "#151827",
      sidebarBg: "#171d34",
      navActiveBg: "#25387c",
      line: "#2c365d",
      lineSoft: "#222944",
    }),
  },
  {
    name: "lavender",
    label: "薰衣草梦",
    primary: "#7f58c2",
    accent: "#8aaec4",
    soft: "#ece5ff",
    gradient: ["#8e63ca", "#9cc8d4"],
    light: createLightSeed({
      primary: "#7653b7",
      accent: "#7fa9bc",
      soft: "#ece5ff",
      surface: "#faf8ff",
      surfaceSoft: "#eee8fa",
      surfaceStrong: "#ddd5ee",
      sidebarBg: "#eee8fa",
      navActiveBg: "#e1d7f2",
    }),
    dark: createDarkSeed({
      primary: "#eee6ff",
      primarySoft: "#c4a8ef",
      accent: "#a8cfdd",
      accentSoft: "rgba(168, 207, 221, 0.18)",
      surface: "#15131b",
      surfaceSoft: "#201a2c",
      surfaceStrong: "#382a55",
      card: "#1a1622",
      sidebarBg: "#201a2a",
      navActiveBg: "#49366f",
      line: "#3c334c",
      lineSoft: "#2b2537",
    }),
  },
];

export const themeOptions: ThemeOption[] = themeSeeds.map((seed) => ({
  name: seed.name,
  label: seed.label,
  primary: seed.primary,
  accent: seed.accent,
  soft: seed.soft,
  gradient: seed.gradient,
  tokens: {
    light: {
      ...seed.light,
      primary: seed.primary,
      primarySoft: mix(seed.primary, "#ffffff", 18),
      accent: seed.accent,
      accentSoft: seed.soft,
    },
    dark: seed.dark,
  },
}));

export const useThemeStore = defineStore("theme", {
  state: () => ({
    current: readThemeName(),
    mode: readSetting(THEME_MODE_KEY, DEFAULT_THEME_SETTINGS.mode, ["system", "light", "dark"] as const),
    font: readSetting(FONT_KEY, DEFAULT_THEME_SETTINGS.font, ["auto", "sans", "serif"] as const),
    radius: readSetting(RADIUS_KEY, DEFAULT_THEME_SETTINGS.radius, ["auto", "0", "0.3", "0.5", "0.75", "1"] as const),
    density: readSetting(DENSITY_KEY, DEFAULT_THEME_SETTINGS.density, ["compact", "default", "comfortable", "large"] as const),
    sidebar: readSetting(SIDEBAR_KEY, DEFAULT_THEME_SETTINGS.sidebar, ["embedded", "floating", "edge"] as const),
    layout: readSetting(LAYOUT_KEY, DEFAULT_THEME_SETTINGS.layout, ["default", "compact", "fullscreen"] as const),
    contentWidth: readSetting(CONTENT_WIDTH_KEY, DEFAULT_THEME_SETTINGS.contentWidth, ["full", "centered"] as const),
  }),
  getters: {
    activeTheme: (state) => themeOptions.find((item) => item.name === state.current) || themeOptions[0],
    resolvedMode: (state): "light" | "dark" => resolveThemeMode(state.mode),
  },
  actions: {
    applyTheme(themeName?: ThemeName): void {
      if (themeName) {
        this.current = themeName;
      }

      const theme = themeOptions.find((item) => item.name === this.current) || themeOptions[0];
      const mode = resolveThemeMode(this.mode);
      const tokens = theme.tokens[mode];
      const root = document.documentElement;
      const cssVariables: Record<string, string> = {
        "--surface": tokens.surface,
        "--surface-soft": tokens.surfaceSoft,
        "--surface-strong": tokens.surfaceStrong,
        "--card": tokens.card,
        "--text": tokens.text,
        "--muted": tokens.muted,
        "--line": tokens.line,
        "--line-soft": tokens.lineSoft,
        "--primary": tokens.primary,
        "--primary-soft": tokens.primarySoft,
        "--blue": tokens.accent,
        "--blue-soft": tokens.accentSoft,
        "--sidebar-bg": tokens.sidebarBg,
        "--nav-text": tokens.navText,
        "--nav-active-bg": tokens.navActiveBg,
        "--topbar-bg": tokens.topbarBg,
        "--search-bg": tokens.searchBg,
        "--control-bg": tokens.controlBg,
        "--secondary-bg": tokens.secondaryBg,
        "--secondary-hover-bg": tokens.secondaryHoverBg,
        "--secondary-hover-border": tokens.secondaryHoverBorder,
        "--table-header-bg": tokens.tableHeaderBg,
        "--table-row-hover-bg": tokens.tableRowHoverBg,
        "--modal-backdrop": hexToRgba(mode === "dark" ? "#000000" : theme.primary, mode === "dark" ? 0.56 : 0.32),
        "--primary-rgb": hexToRgbCsv(mode === "dark" ? theme.primary : tokens.primary),
        "--accent-rgb": hexToRgbCsv(tokens.accent),
        "--shadow": mode === "dark" ? "0 20px 44px rgba(0, 0, 0, 0.34)" : `0 16px 32px ${hexToRgba(theme.primary, 0.08)}`,
        ...fontVariables(this.font),
        ...radiusVariables(this.radius),
        ...densityVariables(this.density),
        ...layoutVariables(this.layout, this.sidebar, this.contentWidth),
      };

      Object.entries(cssVariables).forEach(([name, value]) => {
        root.style.setProperty(name, value);
      });

      root.dataset.themeMode = mode;
      root.dataset.themePreset = theme.name;
      root.dataset.font = this.font;
      root.dataset.radius = this.radius;
      root.dataset.density = this.density;
      root.dataset.sidebar = this.sidebar;
      root.dataset.layout = this.layout;
      root.dataset.contentWidth = this.contentWidth;

      persistSetting(THEME_KEY, theme.name);
      persistSetting(THEME_MODE_KEY, this.mode);
      persistSetting(FONT_KEY, this.font);
      persistSetting(RADIUS_KEY, this.radius);
      persistSetting(DENSITY_KEY, this.density);
      persistSetting(SIDEBAR_KEY, this.sidebar);
      persistSetting(LAYOUT_KEY, this.layout);
      persistSetting(CONTENT_WIDTH_KEY, this.contentWidth);
      watchSystemTheme(() => this.applyTheme());
    },
    setTheme(themeName: ThemeName): void {
      this.current = themeName;
      this.applyTheme();
    },
    setMode(mode: ThemeMode): void {
      this.mode = mode;
      this.applyTheme();
    },
    setFont(font: FontChoice): void {
      this.font = font;
      this.applyTheme();
    },
    setRadius(radius: RadiusChoice): void {
      this.radius = radius;
      this.applyTheme();
    },
    setDensity(density: DensityChoice): void {
      this.density = density;
      this.applyTheme();
    },
    setSidebar(sidebar: SidebarChoice): void {
      this.sidebar = sidebar;
      this.applyTheme();
    },
    setLayout(layout: LayoutChoice): void {
      this.layout = layout;
      this.applyTheme();
    },
    setContentWidth(contentWidth: ContentWidthChoice): void {
      this.contentWidth = contentWidth;
      this.applyTheme();
    },
    resetTheme(): void {
      this.current = DEFAULT_THEME_SETTINGS.theme;
      this.mode = DEFAULT_THEME_SETTINGS.mode;
      this.applyTheme();
    },
    resetColor(): void {
      this.current = DEFAULT_THEME_SETTINGS.theme;
      this.applyTheme();
    },
    resetFont(): void {
      this.font = DEFAULT_THEME_SETTINGS.font;
      this.applyTheme();
    },
    resetRadius(): void {
      this.radius = DEFAULT_THEME_SETTINGS.radius;
      this.applyTheme();
    },
    resetDensity(): void {
      this.density = DEFAULT_THEME_SETTINGS.density;
      this.applyTheme();
    },
    resetSidebar(): void {
      this.sidebar = DEFAULT_THEME_SETTINGS.sidebar;
      this.applyTheme();
    },
    resetLayout(): void {
      this.layout = DEFAULT_THEME_SETTINGS.layout;
      this.applyTheme();
    },
    resetContentWidth(): void {
      this.contentWidth = DEFAULT_THEME_SETTINGS.contentWidth;
      this.applyTheme();
    },
    resetAppearance(): void {
      this.current = DEFAULT_THEME_SETTINGS.theme;
      this.mode = DEFAULT_THEME_SETTINGS.mode;
      this.font = DEFAULT_THEME_SETTINGS.font;
      this.radius = DEFAULT_THEME_SETTINGS.radius;
      this.density = DEFAULT_THEME_SETTINGS.density;
      this.sidebar = DEFAULT_THEME_SETTINGS.sidebar;
      this.layout = DEFAULT_THEME_SETTINGS.layout;
      this.contentWidth = DEFAULT_THEME_SETTINGS.contentWidth;
      this.applyTheme();
    },
  },
});

function createLightSeed(seed: {
  primary: string;
  accent: string;
  soft: string;
  surface: string;
  surfaceSoft: string;
  surfaceStrong: string;
  sidebarBg: string;
  navActiveBg: string;
}): LightThemeTokens {
  return {
    surface: seed.surface,
    surfaceSoft: seed.surfaceSoft,
    surfaceStrong: seed.surfaceStrong,
    card: "#ffffff",
    text: "#191c1e",
    muted: "#5f6670",
    line: mix(seed.surfaceStrong, "#88919c", 26),
    lineSoft: mix(seed.surfaceSoft, "#ffffff", 54),
    sidebarBg: seed.sidebarBg,
    navText: "#303842",
    navActiveBg: seed.navActiveBg,
    topbarBg: hexToRgba(seed.surface, 0.94),
    searchBg: mix(seed.surfaceSoft, "#ffffff", 28),
    controlBg: "#ffffff",
    secondaryBg: seed.surfaceSoft,
    secondaryHoverBg: seed.surfaceStrong,
    secondaryHoverBorder: mix(seed.surfaceStrong, "#87919c", 34),
    tableHeaderBg: mix(seed.surfaceSoft, "#ffffff", 34),
    tableRowHoverBg: mix(seed.surface, "#ffffff", 38),
  };
}

function createDarkSeed(seed: DarkThemeSeed): ThemeTokens {
  return {
    ...seed,
    text: "#f4f0e8",
    muted: "#b8b2a8",
    navText: "#d6cec4",
    topbarBg: hexToRgba(seed.surface, 0.88),
    searchBg: seed.surfaceSoft,
    controlBg: seed.surfaceSoft,
    secondaryBg: seed.surfaceStrong,
    secondaryHoverBg: seed.navActiveBg,
    secondaryHoverBorder: seed.line,
    tableHeaderBg: seed.surfaceSoft,
    tableRowHoverBg: seed.surfaceStrong,
  };
}

function fontVariables(font: FontChoice): Record<string, string> {
  const fontMap: Record<FontChoice, string> = {
    auto: 'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
    sans: 'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
    serif: 'Georgia, "Times New Roman", "Songti SC", "SimSun", serif',
  };

  return {
    "--app-font-family": fontMap[font],
  };
}

function radiusVariables(radius: RadiusChoice): Record<string, string> {
  const radiusMap: Record<RadiusChoice, [string, string, string]> = {
    auto: ["7px", "8px", "12px"],
    "0": ["0px", "0px", "0px"],
    "0.3": ["5px", "7px", "10px"],
    "0.5": ["8px", "11px", "14px"],
    "0.75": ["12px", "16px", "20px"],
    "1": ["18px", "24px", "28px"],
  };
  const [sm, md, lg] = radiusMap[radius];
  return {
    "--radius-sm": sm,
    "--radius-md": md,
    "--radius-lg": lg,
  };
}

function densityVariables(density: DensityChoice): Record<string, string> {
  const densityMap: Record<DensityChoice, Record<string, string>> = {
    compact: {
      "--topbar-height": "60px",
      "--nav-height": "38px",
      "--control-height": "38px",
      "--base-font-size": "14px",
      "--page-padding": "20px",
      "--content-gap": "14px",
      "--panel-padding": "16px",
      "--table-cell-y": "10px",
      "--table-cell-x": "14px",
    },
    default: {
      "--topbar-height": "66px",
      "--nav-height": "44px",
      "--control-height": "42px",
      "--base-font-size": "15px",
      "--page-padding": "26px",
      "--content-gap": "18px",
      "--panel-padding": "20px",
      "--table-cell-y": "14px",
      "--table-cell-x": "18px",
    },
    comfortable: {
      "--topbar-height": "72px",
      "--nav-height": "50px",
      "--control-height": "46px",
      "--base-font-size": "16px",
      "--page-padding": "32px",
      "--content-gap": "24px",
      "--panel-padding": "24px",
      "--table-cell-y": "18px",
      "--table-cell-x": "22px",
    },
    large: {
      "--topbar-height": "82px",
      "--nav-height": "58px",
      "--control-height": "52px",
      "--base-font-size": "17px",
      "--page-padding": "38px",
      "--content-gap": "30px",
      "--panel-padding": "30px",
      "--table-cell-y": "24px",
      "--table-cell-x": "28px",
    },
  };
  return densityMap[density];
}

function layoutVariables(
  layout: LayoutChoice,
  sidebar: SidebarChoice,
  contentWidth: ContentWidthChoice,
): Record<string, string> {
  const sidebarWidth = layout === "compact" ? "252px" : "280px";
  const sidebarOffset = layout === "fullscreen" ? "0px" : sidebar === "floating" ? `calc(${sidebarWidth} + 24px)` : sidebarWidth;

  return {
    "--layout-sidebar-width": sidebarWidth,
    "--layout-sidebar-offset": sidebarOffset,
    "--content-max-width": contentWidth === "centered" ? "1180px" : "none",
  };
}

function readThemeName(): ThemeName {
  const stored = readRawSetting(THEME_KEY);
  const migrated = stored ? legacyThemeMap[stored] || stored : DEFAULT_THEME_SETTINGS.theme;
  return themeOptions.some((item) => item.name === migrated) ? (migrated as ThemeName) : DEFAULT_THEME_SETTINGS.theme;
}

function readSetting<T extends readonly StoredSetting[]>(key: string, fallback: T[number], values: T): T[number] {
  const stored = readRawSetting(key) as T[number] | null;
  return values.includes(stored as T[number]) ? stored! : fallback;
}

function readRawSetting(key: string): string | null {
  try {
    return typeof localStorage === "undefined" ? null : localStorage.getItem(key);
  } catch {
    return null;
  }
}

function persistSetting(key: string, value: string): void {
  try {
    if (typeof localStorage !== "undefined") {
      localStorage.setItem(key, value);
    }
  } catch {
    // Local storage can be disabled in embedded browser contexts.
  }
}

function migrateLegacyAppearanceDefaults(): void {
  try {
    if (typeof localStorage === "undefined") {
      return;
    }
    if (localStorage.getItem(APPEARANCE_VERSION_KEY) === CURRENT_APPEARANCE_VERSION) {
      return;
    }

    const lookedLikeOldDefault = isLegacyDefaultAppearance(
      localStorage.getItem(THEME_KEY),
      localStorage.getItem(THEME_MODE_KEY),
      localStorage.getItem(FONT_KEY),
      localStorage.getItem(RADIUS_KEY),
      localStorage.getItem(SIDEBAR_KEY),
    );

    if (lookedLikeOldDefault) {
      localStorage.setItem(THEME_KEY, DEFAULT_THEME_SETTINGS.theme);
      localStorage.setItem(THEME_MODE_KEY, DEFAULT_THEME_SETTINGS.mode);
      localStorage.setItem(FONT_KEY, DEFAULT_THEME_SETTINGS.font);
      localStorage.setItem(RADIUS_KEY, DEFAULT_THEME_SETTINGS.radius);
      localStorage.setItem(DENSITY_KEY, DEFAULT_THEME_SETTINGS.density);
      localStorage.setItem(SIDEBAR_KEY, DEFAULT_THEME_SETTINGS.sidebar);
      localStorage.setItem(LAYOUT_KEY, DEFAULT_THEME_SETTINGS.layout);
      localStorage.setItem(CONTENT_WIDTH_KEY, DEFAULT_THEME_SETTINGS.contentWidth);
    }
    localStorage.setItem(APPEARANCE_VERSION_KEY, CURRENT_APPEARANCE_VERSION);
  } catch {
    // Appearance migration is best-effort only.
  }
}

export function isLegacyDefaultAppearance(
  theme: string | null,
  mode: string | null,
  font: string | null,
  radius: string | null,
  sidebar: string | null,
): boolean {
  return (!theme || theme === "anthropic" || theme === "navy")
    && (!mode || mode === "dark")
    && (!font || font === "serif")
    && (!radius || radius === "1")
    && (!sidebar || sidebar === "floating");
}

function resolveThemeMode(mode: ThemeMode): "light" | "dark" {
  if (mode !== "system") {
    return mode;
  }
  return typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}

let systemThemeWatching = false;

function watchSystemTheme(apply: () => void): void {
  if (systemThemeWatching || typeof window === "undefined" || !window.matchMedia) {
    return;
  }

  const query = window.matchMedia("(prefers-color-scheme: dark)");
  query.addEventListener?.("change", apply);
  systemThemeWatching = true;
}

function mix(hex: string, targetHex: string, percent: number): string {
  const source = hexToRgb(hex);
  const target = hexToRgb(targetHex);
  const ratio = percent / 100;
  return rgbToHex({
    r: Math.round(source.r + (target.r - source.r) * ratio),
    g: Math.round(source.g + (target.g - source.g) * ratio),
    b: Math.round(source.b + (target.b - source.b) * ratio),
  });
}

function hexToRgba(hex: string, alpha: number): string {
  const { r, g, b } = hexToRgb(hex);
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

function hexToRgbCsv(hex: string): string {
  const { r, g, b } = hexToRgb(hex);
  return `${r}, ${g}, ${b}`;
}

function hexToRgb(hex: string): { r: number; g: number; b: number } {
  const normalized = hex.replace("#", "");
  return {
    r: parseInt(normalized.slice(0, 2), 16),
    g: parseInt(normalized.slice(2, 4), 16),
    b: parseInt(normalized.slice(4, 6), 16),
  };
}

function rgbToHex({ r, g, b }: { r: number; g: number; b: number }): string {
  return `#${[r, g, b]
    .map((value) => value.toString(16).padStart(2, "0"))
    .join("")}`;
}
