/**
 * Canvas Store — 画布核心状态与历史
 *
 * 职责：nodes/edges/groups、选区、缩放平移、持久化脏标、生成历史，
 * 以及增量历史（undo/redo 写入）与内存监控。
 *
 * 已拆分为多个 slice 模块：
 * - types.ts: 类型定义
 * - nodesSlice.ts: 节点状态管理
 * - edgesSlice.ts: 边状态管理
 * - selectionSlice.ts: 选择状态管理
 * - groupsSlice.ts: 组状态管理
 * - historySlice.ts: 历史记录管理
 * - persistenceSlice.ts: 持久化状态管理
 */
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { persist, createJSONStorage } from 'zustand/middleware';

import { CanvasState } from './types';
import { createNodesActions } from './nodesSlice';
import { createEdgesActions } from './edgesSlice';
import { createSelectionActions } from './selectionSlice';
import { createGroupsActions } from './groupsSlice';
import { createHistoryActions } from './historySlice';
import { createPersistenceActions } from './persistenceSlice';

export const useCanvasStore = create<CanvasState>()(
    persist(
        immer((set, get) => ({
            // Initial state
            nodes: [],
            edges: [],
            groups: [],
            incrementalHistory: null,
            historyMerger: null,
            memoryStats: null,
            memoryMonitoringEnabled: false,
            scale: 1,
            pan: { x: 0, y: 0 },
            selectedNodeIds: [],
            selectedGroupId: null,
            lastOperationType: null,
            isDirty: false,
            isSaving: false,
            lastSavedAt: null,
            generationHistory: [],

            // Combine all slice actions
            ...createNodesActions(set, get),
            ...createEdgesActions(set, get),
            ...createSelectionActions(set),
            ...createGroupsActions(set, get),
            ...createHistoryActions(set, get),
            ...createPersistenceActions(set),
        })),
        {
            name: 'pixel-canvas-storage',
            storage: createJSONStorage(() => localStorage),
            partialize: (state) => ({
                nodes: state.nodes,
                edges: state.edges,
                groups: state.groups,
                scale: state.scale,
                pan: state.pan,
                generationHistory: state.generationHistory.slice(0, 15),
                lastSavedAt: state.lastSavedAt,
            }),
            merge: (persistedState: any, currentState) => {
                const {
                    incrementalHistory,
                    historyMerger,
                    memoryStats,
                    saveHistoryTimeout,
                    ...rest
                } = persistedState || {};

                return {
                    ...currentState,
                    ...rest,
                    incrementalHistory: null,
                    historyMerger: null,
                    saveHistoryTimeout: null,
                    memoryStats: null,
                };
            },
        }
    )
);

// Re-export types
export * from './types';
