import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { APP_UI_STORAGE_NAME, appUiPersistStorage, migrateAppUiState } from '../middleware/persist';
import type { AppPersistedState, AppStore } from './appTypes';

/**
 * 应用级 UI Store：布局、抽屉、路由页签等跨组件共享状态。
 * 侧边栏折叠与路由页签持久化；其余为会话内状态。
 */
export const useAppStore = create<AppStore>()(
  devtools(
    persist(
      (set) => ({
        sidebarCollapsed: false,
        mobileDrawerOpen: false,
        menuOpenKeys: [],
        aiChatOpen: false,
        aiWorking: false,
        routeDockTabs: [],
        toggleSidebar: () => {
          set((state) => ({ sidebarCollapsed: !state.sidebarCollapsed }), false, 'app/toggleSidebar');
        },
        setSidebarCollapsed: (collapsed) => {
          set({ sidebarCollapsed: collapsed }, false, 'app/setSidebarCollapsed');
        },
        setMobileDrawerOpen: (open) => {
          set({ mobileDrawerOpen: open }, false, 'app/setMobileDrawerOpen');
        },
        setMenuOpenKeys: (keys) => {
          set(
            (state) => ({
              menuOpenKeys: typeof keys === 'function' ? keys(state.menuOpenKeys) : keys,
            }),
            false,
            'app/setMenuOpenKeys',
          );
        },
        setAiChatOpen: (open) => {
          set({ aiChatOpen: open }, false, 'app/setAiChatOpen');
        },
        setAiWorking: (working) => {
          set({ aiWorking: working }, false, 'app/setAiWorking');
        },
        setRouteDockTabs: (updater) => {
          set(
            (state) => ({
              routeDockTabs:
                typeof updater === 'function' ? updater(state.routeDockTabs) : updater,
            }),
            false,
            'app/setRouteDockTabs',
          );
        },
      }),
      {
        name: APP_UI_STORAGE_NAME,
        storage: appUiPersistStorage,
        partialize: (state): AppPersistedState => ({
          sidebarCollapsed: state.sidebarCollapsed,
          routeDockTabs: state.routeDockTabs,
        }),
        version: 2,
        migrate: migrateAppUiState,
      },
    ),
    { name: 'app-store', enabled: import.meta.env.DEV },
  ),
);
