import { defineStore } from "pinia";
import { ref } from "vue";
import { buildCustomThemeVars } from "./buildCustomThemeVars.js";

const DEFAULT_THEME = "blue"; // 默认主题
const CUSTOM_THEME = "custom";
const CUSTOM_THEME_COLOR_KEY = "customThemeColor";
const THEME_CLASS_MAP = {
  blue: "",
  purple: "purple",
  red: "red",
  black: "dark",
  dark: "dark",
  custom: "",
};

const normalizeThemeValue = (theme) => {
  return THEME_CLASS_MAP[theme] !== undefined ? theme : DEFAULT_THEME;
};

const clearCustomThemeVars = (html) => {
  Object.keys(buildCustomThemeVars("#1764FF")).forEach((key) => {
    html.style.removeProperty(key);
  });
};

export const useThemeStore = defineStore("theme", () => {
  // 当前主题值，默认为 localStorage 中的值或 DEFAULT_THEME
  const themeValue = ref(
    normalizeThemeValue(localStorage.getItem("theme") || DEFAULT_THEME),
  );
  // 定制主题颜色，默认为 localStorage 中的值或 "#1764FF"
  const customThemeColor = ref(
    localStorage.getItem(CUSTOM_THEME_COLOR_KEY) || "#1764FF",
  );
  // 应用主题
  const applyTheme = (theme) => {
    const normalizedTheme = normalizeThemeValue(theme);
    const html = document.documentElement;
    const themeClass = THEME_CLASS_MAP[normalizedTheme] || "";
    // 预设主题通过 class 切换
    html.className = themeClass;
    clearCustomThemeVars(html);
    // 定制主题通过 CSS 变量实现
    if (normalizedTheme === CUSTOM_THEME) {
      const customVars = buildCustomThemeVars(customThemeColor.value);
      Object.entries(customVars).forEach(([key, value]) => {
        html.style.setProperty(key, value);
      });
    }
  };
  // 设置自定义主题颜色
  const setCustomThemeColor = (color) => {
    customThemeColor.value = color;
    localStorage.setItem(CUSTOM_THEME_COLOR_KEY, color);

    if (themeValue.value === CUSTOM_THEME) {
      applyTheme(CUSTOM_THEME);
    }
  };

  const previewCustomThemeColor = (color) => {
    customThemeColor.value = color;

    if (themeValue.value === CUSTOM_THEME) {
      applyTheme(CUSTOM_THEME);
    }
  };

  const setTheme = (theme) => {
    const normalizedTheme = normalizeThemeValue(theme);
    themeValue.value = normalizedTheme;
    localStorage.setItem("theme", normalizedTheme);
    applyTheme(normalizedTheme);
  };

  // 初始化时应用默认主题
  applyTheme(themeValue.value);

  return {
    themeValue,
    customThemeColor,
    setTheme,
    setCustomThemeColor,
    previewCustomThemeColor,
    applyTheme,
    buildCustomThemeVars,
  };
});
