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

/**
 * App 布局状态 Store
 * 管理应用整体布局和主题（持久化）
 */
const useAppLayoutStore = create(
  persist(
    (set) => ({
      // ==================== 状态 ====================
      
      // 布局模式：'chat' | 'workflow' | 'settings'
      layoutMode: 'chat',
      
      // 侧边栏模式：'left' | 'right' | 'both' | 'none'
      sidebarMode: 'both',
      
      // 侧边栏是否悬停
      isSidebarHovered: false,
      
      // 颜色主题：'light' | 'dark'
      colorTheme: 'dark',

      // 当前页面：'chat' | 'studio' | 'novel' | 'room'
      activePage: 'chat',

      // ==================== Actions ====================

      /**
       * 设置布局模式
       * @param {string} mode - 布局模式
       */
      setLayoutMode: (mode) => {
        set({ layoutMode: mode });
      },

      /**
       * 设置侧边栏模式
       * @param {string} mode - 侧边栏模式
       */
      setSidebarMode: (mode) => {
        set({ sidebarMode: mode });
      },

      /**
       * 切换侧边栏悬停状态
       * @param {boolean} hovered - 是否悬停
       */
      setSidebarHovered: (hovered) => {
        set({ isSidebarHovered: hovered });
      },

      /**
       * 设置当前页面
       * @param {string} page - 'chat' | 'studio' | 'novel' | 'room'
       */
      setActivePage: (page) => {
        set({ activePage: page });
      },

      /**
       * 设置颜色主题
       * @param {string} theme - 主题名
       */
      setColorTheme: (theme) => {
        set({ colorTheme: theme });
        
        // 同步到 DOM
        document.documentElement.setAttribute('data-color-theme', theme);
      },

      /**
       * 切换颜色主题
       */
      toggleColorTheme: () => {
        set((state) => {
          const newTheme = state.colorTheme === 'light' ? 'dark' : 'light';
          document.documentElement.setAttribute('data-color-theme', newTheme);
          return { colorTheme: newTheme };
        });
      },

      /**
       * 重置所有布局状态
       */
      reset: () => {
        set({
          layoutMode: 'chat',
          sidebarMode: 'both',
          isSidebarHovered: false,
          colorTheme: 'dark',
          activePage: 'chat',
        });
      }
    }),
    {
      name: 'app-layout-storage', // localStorage key
      partialize: (state) => ({ 
        layoutMode: state.layoutMode,
        sidebarMode: state.sidebarMode,
        colorTheme: state.colorTheme,
        activePage: state.activePage,
      })
    }
  )
);

export default useAppLayoutStore;
