import { create } from 'zustand';
import { persist } from 'zustand/middleware';

const useSideBarRightStore = create(
  persist(
    (set, get) => ({
      selectedTabs: ['dice', 'rag'],

      allTabs: [
        { id: 'dice', label: '骰子', title: '掷骰子和随机数生成工具', component: null },
        { id: 'macros', label: '宏', title: '主要为快捷输入', component: null },
        { id: 'table', label: '表格', title: '动态数据表格展示与编辑，可直接影响后端', component: null },
        { id: 'rag', label: 'RAG', title: '查看具体召回了哪些条目', component: null },
        { id: 'worldbook_active', label: '世界书', title: '查看当前对话中激活的世界书条目', component: null }, // ✅ 添加世界书激活标签
        { id: 'tasks', label: '任务', title: '查看和管理并行任务（生图、表格维护等）', component: null } // ✅ 添加任务队列标签
      ],

      handleTabClick: (tabId) => set((state) => {
        if (state.selectedTabs.includes(tabId)) {
          // 如果已选中，则取消选中
          return { selectedTabs: state.selectedTabs.filter(id => id !== tabId) };
        } else if (state.selectedTabs.length < 2) {
          // 如果未选中且少于2个，则添加
          return { selectedTabs: [...state.selectedTabs, tabId] };
        } else {
          // 如果已有2个，则替换最早选中的
          return { selectedTabs: [...state.selectedTabs.slice(1), tabId] };
        }
      }),

      // 设置特定标签的组件
      setTabComponent: (tabId, component) => set((state) => ({
        allTabs: state.allTabs.map(tab =>
          tab.id === tabId ? { ...tab, component } : tab
        )
      })),
      
      // ✅ 验证并清理无效的选中标签
      validateSelectedTabs: () => {
        const state = get();
        const validIds = state.allTabs.map(tab => tab.id);
        const validSelectedTabs = state.selectedTabs.filter(id => validIds.includes(id));
        
        if (validSelectedTabs.length !== state.selectedTabs.length) {
          set({ selectedTabs: validSelectedTabs });
        }
      }
    }),
    {
      name: 'sidebar-right-storage', // localStorage key
      partialize: (state) => ({ selectedTabs: state.selectedTabs }), // 只保存 selectedTabs
      // ✅ 迁移逻辑：清除已删除的标签
      migrate: (persistedState, version) => {
        if (persistedState.selectedTabs) {
          // 移除已删除的 'debug' 标签
          const cleanedTabs = persistedState.selectedTabs.filter(id => id !== 'debug');
          
          // 如果清理后为空或只有一个，恢复到默认值
          if (cleanedTabs.length === 0) {
            persistedState.selectedTabs = ['dice', 'rag'];
          } else if (cleanedTabs.length === 1 && cleanedTabs[0] === 'dice') {
            // 如果只剩dice，添加rag作为第二个
            persistedState.selectedTabs = ['dice', 'rag'];
          } else {
            persistedState.selectedTabs = cleanedTabs;
          }
        }
        return persistedState;
      },
      // ✅ 加载后验证
      onRehydrateStorage: () => (state) => {
        if (state) {
          state.validateSelectedTabs();
        }
      }
    }
  )
);

export default useSideBarRightStore;
