import { computed, ref } from 'vue';

import { createPinia, defineStore } from 'pinia';

// 创建 pinia 实例
export const pinia = createPinia();

// 用户模块 store
export const useUserStore = defineStore('user', () => {
  // 状态定义
  const token = ref<string>(localStorage.getItem('y-code-access-token') || '');
  const userProfile = ref<null>(null);

  // getter 计算属性
  const isLoggedIn = computed(() => !!token.value);

  // 同步 action
  const setToken = (newToken: string) => {
    token.value = newToken;
    localStorage.setItem('y-code-access-token', newToken);
  };

  // 清理方法
  const logout = () => {
    token.value = '';
    userProfile.value = null;
    localStorage.removeItem('y-code-access-token');
  };

  return {
    token,
    userProfile,
    isLoggedIn,
    setToken,
    logout
  };
});

// 应用配置 store
export const useAppStore = defineStore('app', () => {
  const theme = ref<'dark' | 'light'>('light');
  const sidebarCollapsed = ref(false);

  // 持久化配置
  const persist = {
    paths: ['theme', 'sidebarCollapsed'],
    storage: localStorage
  };

  const toggleTheme = () => {
    theme.value = theme.value === 'light' ? 'dark' : 'light';
  };

  return {
    theme,
    sidebarCollapsed,
    toggleTheme,
    persist
  };
});
