import { defineStore } from "pinia";
import { ref } from "vue";
import {
  buildThemeVars,
  normalizeThemeValue,
  DEFAULT_THEME,
} from "./buildThemeVars.js";

const APPLIED_KEYS = Object.keys(buildThemeVars(DEFAULT_THEME));

const applyToRoot = (theme) => {
  const root = document.documentElement;
  // 先清掉旧变量，避免切主题后留下脏数据
  APPLIED_KEYS.forEach((k) => root.style.removeProperty(k));
  Object.entries(buildThemeVars(theme)).forEach(([k, v]) =>
    root.style.setProperty(k, v),
  );
};

export const useThemeStore = defineStore("theme", () => {
  const themeValue = ref(
    normalizeThemeValue(localStorage.getItem("theme") || DEFAULT_THEME),
  );

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

  // 初始化：setup 内即生效，不依赖外部调用
  applyToRoot(themeValue.value);

  return { themeValue, setTheme };
});