import { darkTheme, type GlobalTheme } from "naive-ui";
import { defineStore } from "pinia";

export const useSettingsStore = defineStore(
  "setting",
  () => {
    const isDark = ref(false);

    watch(isDark, (newVal) => {
      // 控制根元素 class
      if (newVal) {
        document.documentElement.classList.add('dark');
        document.documentElement.setAttribute('data-theme', 'dark');
      } else {
        document.documentElement.classList.remove('dark');
        document.documentElement.setAttribute('data-theme', 'light');
      }
    }, { immediate: true }); // 立即执行一次初始化

    const theme = computed<GlobalTheme | null>(() =>
      isDark.value ? darkTheme : null
    );

    function toggleTheme() {
      isDark.value = !isDark.value;
    }

    function changeTheme(val: boolean) {
      isDark.value = val;
    }

    return {
      isDark,
      theme,
      toggleTheme,
      changeTheme,
    };
  },
  {
    persist: {
      key: "setting",
      storage: window.localStorage,
    },
  }
);
