// frontend-react/src/Store/UserSlice.jsx
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

/**
 * 用户角色 Store
 * 管理当前玩家角色信息
 */
const useUserStore = create(
  persist(
    (set, get) => ({
      // 当前用户角色
      currentUserRole: { name: '', description: '' },
      
      // ✅ 用户角色列表（支持多个角色）
      userRoles: [
        { id: 'default', name: '默认用户', description: '普通用户角色' }
      ],

      // 设置用户角色
      setCurrentUserRole: (role) => {
        set({ currentUserRole: role });
      },

      // 清除用户角色
      clearCurrentUserRole: () => {
        set({ currentUserRole: { name: '', description: '' } });
      },

      // 更新用户角色名称
      updateRoleName: (name) => {
        set((state) => ({
          currentUserRole: { ...state.currentUserRole, name }
        }));
      },

      // 更新用户角色描述
      updateRoleDescription: (description) => {
        set((state) => ({
          currentUserRole: { ...state.currentUserRole, description }
        }));
      },
      
      // ✅ 添加新用户角色
      addUserRole: (role) => {
        set((state) => ({
          userRoles: [...state.userRoles, { ...role, id: role.id || `role_${Date.now()}` }]
        }));
      },
      
      // ✅ 删除用户角色
      removeUserRole: (roleId) => {
        set((state) => ({
          userRoles: state.userRoles.filter(r => r.id !== roleId)
        }));
      },
      
      // ✅ 更新用户角色
      updateUserRole: (roleId, updates) => {
        set((state) => ({
          userRoles: state.userRoles.map(r => 
            r.id === roleId ? { ...r, ...updates } : r
          )
        }));
      },
      
      // ✅ 选择用户角色（从列表中选择一个作为当前角色）
      selectUserRole: (roleId) => {
        set((state) => {
          const selectedRole = state.userRoles.find(r => r.id === roleId);
          if (selectedRole) {
            return { currentUserRole: { ...selectedRole } };
          }
          return state;
        });
      }
    }),
    {
      name: 'user-role-storage', // localStorage key
      partialize: (state) => ({ 
        currentUserRole: state.currentUserRole 
      })
    }
  )
);

export default useUserStore;
