// frontend-react/src/Store/Mid/ChatBoxSlice.jsx
import { create } from 'zustand';
import { subscribeWithSelector, persist } from 'zustand/middleware';
import useApiConfigStore from '../SideBarLeft/ApiConfigSlice';
import usePresetStore from '../SideBarLeft/PresetSlice';
import useCharacterStore from '../SideBarLeft/CharacterSlice'; // 引入角色卡 Store
import useWorldBookStore from '../SideBarLeft/WorldBookSlice'; // 引入世界书 Store

const useChatBoxStore = create(
  subscribeWithSelector(
    persist(
      (set, get) => ({
        // WebSocket连接实例
        wsConnection: null,
        // 聊天历史消息列表
        messages: [],

        // 用户名称
        userName: '',

        // 角色名称
        characterName: '',

        // 当前选中的角色
        currentRole: null,

        // 当前选中的聊天
        currentChat: null,

        // 是否正在加载
        isLoading: false,

        // 是否正在生成
        isGenerating: false,

        // 错误信息
        error: null,

        // 选项状态
        options: {
          dynamicTable: false,   // 动态表格
          streamOutput: false,   // 流式输出
          imageWorkflow: false,  // 生图工作流
          renderMode: 'markdown', // 渲染模式: 'none' | 'html' | 'markdown'
          autoDiceRoll: false,   // 自动掷骰子替换（默认关闭）
        },

        // 设置消息列表
        setMessages: (messages) => set({ messages }),

        // 设置用户名称
        setUserName: (userName) => set({ userName }),

        // 设置角色名称
        setCharacterName: (characterName) => set({ characterName }),

        // 设置当前角色
        setCurrentRole: (role) => set({ currentRole: role }),

        // 设置当前聊天
        setCurrentChat: (chat) => set({ currentChat: chat }),

        // 切换选项状态
        toggleOption: (optionName) => set((state) => ({
          options: {
            ...state.options,
            [optionName]: !state.options[optionName]
          }
        })),

        // 设置选项状态
        setOption: (optionName, value) => set((state) => ({
          options: {
            ...state.options,
            [optionName]: value
          }
        })),

        // 重置所有选项
        resetOptions: () => set({
          options: {
            dynamicTable: false,
            streamOutput: false,
            imageWorkflow: false,
            renderMode: 'markdown',
            autoDiceRoll: false
          }
        }),

        // 切换渲染模式 (none -> html -> markdown -> none)
        cycleRenderMode: () => set((state) => {
          const modes = ['none', 'html', 'markdown'];
          const currentIndex = modes.indexOf(state.options.renderMode);
          const nextIndex = (currentIndex + 1) % modes.length;
          return {
            options: {
              ...state.options,
              renderMode: modes[nextIndex]
            }
          };
        }),

        // 设置渲染模式
        setRenderMode: (mode) => set((state) => ({
          options: {
            ...state.options,
            renderMode: mode
          }
        })),

        // 同时设置角色和聊天
        setChatBoxRoleAndChat: (role, chat) => {
          // console.log('[ChatBoxStore] setChatBoxRoleAndChat called with:', { role, chat });
          set({
            currentRole: role,
            currentChat: typeof chat === 'object' && chat !== null ? chat.chat_name : chat
          });
        },

        // 设置生成状态
        setIsGenerating: (status) => set({ isGenerating: status }),

        // 计算下一个楼层号
        getNextFloor: (messages) => {
          if (messages.length === 0) return 1;
          const maxFloor = Math.max(...messages.map(msg => msg.floor));
          return maxFloor + 1;
        },

        // 发送消息
        sendMessage: async (content, targetFloor = null) => {
          const { messages, userName, characterName, currentRole, currentChat, options, wsConnection } = get();

          // ✅ 如果启用了自动掷骰子，处理内容
          let processedContent = content;
          if (options.autoDiceRoll) {
            const result = get().processDiceRoll(content);
            processedContent = result.content;
            
            if (result.hasDiceCommand) {
              console.log('[DiceRoll] 自动替换掷骰指令:', { original: content, processed: processedContent });
            }
          }

          // ✅ 如果没有 currentChat，先创建聊天文件
          let actualChat = currentChat;
          if (!currentChat && currentRole) {
            // console.log(`[ChatBoxStore] 检测到未选择聊天，自动创建...`);
            try {
              const chatName = '默认聊天';
              const response = await fetch(`/api/chat/${encodeURIComponent(currentRole)}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                  chat_name: chatName,
                  metadata: {
                    user_name: userName || 'User',
                    character_name: characterName || currentRole
                  }
                })
              });
              
              if (response.ok || response.status === 400) {
                actualChat = chatName;
                // 更新 currentChat
                set({ currentChat: chatName });
                // console.log(`[ChatBoxStore] ✅ 已创建/使用聊天: ${chatName}`);
              } else {
                throw new Error(`创建聊天失败: ${response.status}`);
              }
            } catch (error) {
              // console.error('[ChatBoxStore] ❌ 创建聊天失败:', error);
              set({ error: '创建聊天失败: ' + error.message });
              return;
            }
          }

          // 获取 API 配置
          const apiConfigStore = useApiConfigStore.getState();

          // 获取预设配置
          const presetStore = usePresetStore.getState();

          // ✅ 获取角色卡数据
          const characterStore = useCharacterStore.getState();
          const selectedCharacter = characterStore.selectedCharacter;

          // ✅ 获取世界书数据
          const worldBookStore = useWorldBookStore.getState();
          const globalWorldBooks = worldBookStore.globalWorldBooks;

          // 关闭之前的WebSocket连接
          if (wsConnection) {
            wsConnection.close();
          }

          // ✅ 判断是重roll还是新消息
          const isReroll = targetFloor !== null;
          
          let userFloor, assistantFloor, nextFloor;
          
          if (isReroll) {
            // 重roll模式：不创建新用户消息楼层，直接使用目标楼层的上一条用户消息
            // console.log('[ChatBoxStore] 🔄 重roll模式，目标楼层:', targetFloor);
            
            // 找到目标 AI 消息
            const targetMessage = messages.find(m => m.floor === targetFloor);
            if (!targetMessage || targetMessage.is_user) {
              // console.error('[ChatBoxStore] ❌ 无效的目标楼层');
              return;
            }
            
            // 助手楼层就是目标楼层
            assistantFloor = targetFloor;
            nextFloor = targetFloor;  // ✅ 设置 nextFloor 用于后续发送
            
            // ✅ 不添加新的用户消息，只准备更新 AI 消息
            set({
              isGenerating: true,
              wsConnection: null,  // 重置连接
            });
          } else {
            // 正常模式：创建新的用户消息和 AI 消息
            nextFloor = get().getNextFloor(messages);
            userFloor = nextFloor;
            assistantFloor = nextFloor + 1;
            
            set({
              isGenerating: true,
              wsConnection: null,  // 重置连接
              messages: [...messages, {
                id: `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,  // ✅ 使用唯一ID
                floor: userFloor,
                mes: processedContent,  // 使用处理后的内容
                is_user: true,
                name: userName || 'User',
                sendDate: new Date().toISOString()
              }]
            });
          }

          try {
            // 统一使用WebSocket处理流式和非流式输出
            // WebSocket 直接连接到后端，使用浏览器的 host
            const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsHost = window.location.host.replace('23338', '23337'); // 前端 23338 -> 后端 23337
            const wsUrl = `${wsProtocol}//${wsHost}/api/chat/${encodeURIComponent(currentRole)}/${encodeURIComponent(actualChat)}/ws`;
            const ws = new WebSocket(wsUrl);
            console.log('[WebSocket] 正在建立连接...', { url: wsUrl });

            // 添加连接超时处理
            const connectionTimeout = setTimeout(() => {
              if (ws.readyState === WebSocket.CONNECTING) {
                console.error('[WebSocket] 连接超时');
                ws.close();
                set({
                  error: 'WebSocket connection timeout',
                  isGenerating: false,
                  wsConnection: null
                });
              }
            }, 5000); // 5秒超时

            // 保存WebSocket连接到store
            set({ wsConnection: ws });

            // ✅ 根据模式处理 AI 消息
            let newMessageId;
            
            if (isReroll) {
              // 重roll模式：找到目标消息并准备添加新的 swipe
              const targetMessage = messages.find(m => m.floor === assistantFloor);
              if (!targetMessage) {
                // console.error('[ChatBoxStore] ❌ 找不到目标消息');
                return;
              }
              
              newMessageId = targetMessage.id;  // 使用现有的 ID
              // console.log('[ChatBoxStore] 🔄 重roll模式，更新消息:', newMessageId);
              
              // ✅ 不添加新消息，只是标记为正在生成
              set({ isGenerating: true });
            } else {
              // 正常模式：添加一个空的助手消息，稍后会更新
              newMessageId = `ai_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;  // ✅ 使用唯一ID
              set((state) => ({
                messages: [...state.messages, {
                  id: newMessageId,
                  floor: assistantFloor,
                  mes: '',
                  is_user: false,
                  name: characterName || 'Assistant',
                  sendDate: new Date().toISOString()
                }],
                isGenerating: true
              }));
            }

            let assistantMessage = '';
            let isStreamComplete = false;

            ws.onopen = () => {
              clearTimeout(connectionTimeout); // 清除超时定时器
              console.log('\n' + '='.repeat(80));
              console.log('[WebSocket] 📡 连接已建立');
              console.log('  - URL:', wsUrl);
              console.log('  - Ready State:', ws.readyState);
              console.log('='.repeat(80) + '\n');
            };

            ws.onclose = (event) => {
              console.log('\n' + '='.repeat(80));
              console.log('[WebSocket] 🔌 连接已关闭');
              console.log('  - Code:', event.code);
              console.log('  - Reason:', event.reason);
              console.log('  - Was Clean:', event.wasClean);
              console.log('='.repeat(80) + '\n');
            };

            // 处理WebSocket消息
            let chunkCount = 0;
            ws.onmessage = (event) => {
              const data = JSON.parse(event.data);
              
              if (data.type === 'chunk') {
                chunkCount++;
                // 每10个chunk记录一次
                if (chunkCount % 10 === 0) {
                  console.log(`[WebSocket] 📊 已接收 ${chunkCount} 个 chunks`);
                }
                
                // 处理流式数据块
                assistantMessage += data.content;
                
                if (isReroll) {
                  // ✅ 重roll模式：不更新 mes，只在内部累积 assistantMessage
                  // mes 保持不变，直到 complete 事件才更新
                } else {
                  // 正常模式：更新新创建的消息
                  set((state) => ({
                    messages: state.messages.map((msg) =>
                      msg.id === newMessageId ? { ...msg, mes: assistantMessage } : msg
                    )
                  }));
                }
              } else if (data.type === 'worldbook_active') {
                console.log('[WebSocket] 📚 收到世界书激活信息:', data.entries.length, '个条目');
                // ✅ 更新世界书激活显示
                import('../../Store/SideBarRight/WorldBookActiveSlice').then(module => {
                  module.default.getState().setActiveEntries(data.entries);
                });
              } else if (data.type === 'tasks_created') {
                console.log('[WebSocket] 📋 收到任务ID信息:', data.tasks);
                // ✅ 创建了新任务
                import('../../Store/SideBarRight/TasksSlice').then(module => {
                  const tasksStore = module.default;
                  const newTasks = [];
                  
                  if (data.tasks.imageWorkflow) {
                    newTasks.push({
                      taskId: data.tasks.imageWorkflow,
                      taskType: 'image_workflow',
                      chatId: `${currentRole}/${actualChat}`
                    });
                  }
                  
                  if (data.tasks.dynamicTable) {
                    newTasks.push({
                      taskId: data.tasks.dynamicTable,
                      taskType: 'dynamic_table',
                      chatId: `${currentRole}/${actualChat}`
                    });
                  }
                  
                  if (newTasks.length > 0) {
                    tasksStore.getState().addTasks(newTasks);
                  }
                });
              } else if (data.type === 'task_status_update') {
                console.log('[WebSocket] 🔄 收到任务状态更新:', data.tasks);
                // ✅ 任务状态更新
                import('../../Store/SideBarRight/TasksSlice').then(module => {
                  module.default.getState().setTasks(data.tasks);
                });
              } else if (data.type === 'task_cancelled') {
                console.log('[WebSocket] ❌ 任务取消确认:', data.taskId);
                // ✅ 任务取消确认
                import('../../Store/SideBarRight/TasksSlice').then(module => {
                  module.default.getState().updateTaskStatus(data.taskId, 'cancelled');
                });
              } else if (data.type === 'interrupted') {
                console.log('\n[WebSocket] 🛑 收到中断信号');
                console.log('  - 已生成内容长度:', data.content?.length || 0);
                // ✅ 处理中断：保存已生成的部分内容
                isStreamComplete = true;
                ws.close();
                set({ wsConnection: null, isGenerating: false });
              } else if (data.type === 'complete') {
                console.log('\n[WebSocket] ✅ 收到完成信号');
                console.log('  - 总 Chunks:', chunkCount);
                console.log('  - 消息长度:', assistantMessage.length);
                
                // ✅ 处理重roll模式：将新生成的内容添加到 swipes 数组
                if (isReroll) {
                  // console.log('[ChatBoxStore] 🔄 重roll完成，添加新的 swipe 版本');
                  
                  set((state) => ({
                    messages: state.messages.map((msg) => {
                      if (msg.id === newMessageId) {
                        // 获取现有的 swipes 数组
                        const existingSwipes = msg.swipes || [];
                        const currentMes = msg.mes;  // 当前显示的内容（旧版本）
                        
                        // 构建新的 swipes 数组：包含所有旧版本 + 新版本
                        let updatedSwipes = [...existingSwipes];
                        
                        // 如果当前 mes 不在 swipes 中，先添加它
                        if (!updatedSwipes.includes(currentMes)) {
                          updatedSwipes.push(currentMes);
                        }
                        
                        // 添加新生成的内容
                        updatedSwipes.push(assistantMessage);
                        
                        // console.log('[ChatBoxStore] 📊 Swipes 更新:', {
                        //   oldCount: existingSwipes.length,
                        //   newCount: updatedSwipes.length,
                        //   newSwipeIndex: updatedSwipes.length - 1,
                        //   currentMesLength: currentMes.length,
                        //   assistantMessageLength: assistantMessage.length
                        // });
                        
                        return {
                          ...msg,
                          mes: assistantMessage,  // 显示新生成的内容
                          swipes: updatedSwipes,  // 更新 swipes 数组
                          swipe_id: updatedSwipes.length - 1  // 自动切换到新版本
                        };
                      }
                      return msg;
                    })
                  }));
                }
                
                // 完成响应
                isStreamComplete = true;
                ws.close();
                set({ wsConnection: null, isGenerating: false });
              } else if (data.type === 'error') {
                console.error('[WebSocket] ❌ 收到错误:', data.message);
                // 错误处理
                set({
                  error: data.message,
                  isGenerating: false,
                  wsConnection: null
                });
                ws.close();
              }
            };

            // 处理连接错误
            ws.onerror = (error) => {
              console.error('[WebSocket] 连接错误', { error, readyState: ws.readyState });
              set({
                error: 'WebSocket connection failed',
                isGenerating: false,
                wsConnection: null
              });
            };

            // 处理连接关闭（非流式模式下会自动关闭）
            ws.onclose = () => {
              set({ wsConnection: null });
              if (!isStreamComplete && !options.streamOutput) {
                // 非流式模式下，一次性完成后自动关闭
                set({ isGenerating: false });
              }
            };

            // 发送请求到WebSocket（确保连接已建立）
            const sendAfterConnect = () => {
              console.log('[WebSocket] 📤 sendAfterConnect 被调用, readyState:', ws.readyState);
              
              if (ws.readyState === WebSocket.OPEN) {
                console.log('[WebSocket] ✅ 连接已打开，准备发送消息');
                // ✅ 获取 API 配置
                const apiConfigData = {
                  api_url: apiConfigStore.currentProfile?.apis?.mainLLM?.apiUrl || '',
                  api_key: apiConfigStore.currentProfile?.apis?.mainLLM?.apiKey ? '***' : '',
                  model: apiConfigStore.currentProfile?.apis?.mainLLM?.model || ''
                };
                
                // console.log('\n' + '-'.repeat(80));
                // console.log('[WebSocket] 📤 发送消息:');
                // console.log('  - Floor:', isReroll ? assistantFloor : nextFloor);
                // console.log('  - Mode:', isReroll ? '🔄 Reroll (添加swipe)' : '➕ New Message');
                // console.log('  - Role:', currentRole);
                // console.log('  - Chat:', actualChat);
                // console.log('  - Stream:', options.streamOutput);
                // console.log('  - Message Length:', processedContent.length);
                // console.log('  - API Config:', apiConfigData);
                // console.log('  - Current Profile:', apiConfigStore.currentProfile);
                // console.log('-'.repeat(80) + '\n');
                
                // ✅ 实际发送消息
                const messageData = JSON.stringify({
                  floor: isReroll ? assistantFloor : nextFloor,  // ✅ 重roll模式使用目标楼层
                  mes: processedContent,  // 使用处理后的内容
                  is_user: true,
                  currentRole: currentRole,
                  currentChat: actualChat,  // 使用 actualChat
                  options: options,
                  apiConfig: {
                    // 从 currentProfile 中获取 mainLLM 配置（不包含 apiKey）
                    api_url: apiConfigStore.currentProfile?.apis?.mainLLM?.apiUrl || '',
                    model: apiConfigStore.currentProfile?.apis?.mainLLM?.model || ''
                  },
                  // ✅ 传递 profileId，让后端从配置文件读取 API Key
                  currentProfile: {
                    id: apiConfigStore.currentProfile?.id || null
                  },
                  presetConfig: {
                    selectedPreset: presetStore.selectedPreset,
                    parameters: presetStore.parameters,
                    promptComponents: presetStore.promptComponents
                  },
                  // ✅ 角色卡数据
                  characterData: selectedCharacter ? {
                    id: selectedCharacter.id,
                    name: selectedCharacter.name,
                    description: selectedCharacter.description,
                    personality: selectedCharacter.personality,
                    scenario: selectedCharacter.scenario,
                    first_mes: selectedCharacter.first_mes,
                    mes_example: selectedCharacter.mes_example,
                    worldInfoId: selectedCharacter.worldInfoId || null,  // 绑定的世界书ID
                    tags: selectedCharacter.tags || [],
                    categories: selectedCharacter.categories || []
                  } : null,
                  // ✅ 世界书数据
                  worldBookData: {
                    globalBooks: globalWorldBooks.map(wb => ({
                      id: wb.id,
                      name: wb.name,
                      description: wb.description
                    })),
                    characterBookId: selectedCharacter?.worldInfoId || null  // 角色绑定的世界书ID
                  },
                  // ✅ 动态表格数据（如果启用）
                  dynamicTableData: options.dynamicTable ? {
                    headers: selectedCharacter?.tableHeaders || [],
                    currentValues: selectedCharacter?.tableDefaults || {}
                  } : null,
                  // ✅ 时间戳（用于冲突解决）
                  timestamp: Date.now(),
                  stream: options.streamOutput,
                  // ✅ 调试标志：请求后端返回完整的prompt拼接内容
                  debugPrompt: true
                });
                
                // console.log('[WebSocket] 📤 正在发送消息，数据长度:', messageData.length);
                ws.send(messageData);
                // console.log('[WebSocket] ✅ 消息已发送');
              } else if (ws.readyState === WebSocket.CONNECTING) {
                // 如果正在连接，继续等待
                // console.log('[WebSocket] 等待连接...', { readyState: ws.readyState });
                setTimeout(sendAfterConnect, 100);
              } else {
                // 连接失败或已关闭
                // console.error('[WebSocket] 连接失败', { readyState: ws.readyState });
                set({
                  error: 'WebSocket connection failed',
                  isGenerating: false,
                  wsConnection: null
                });
              }
            };
            // 等待连接建立后发送
            sendAfterConnect();
          } catch (error) {
            set({
              error: error.message,
              isGenerating: false
            });
          }
        },

        // 终止生成
        stopGeneration: () => set((state) => {
          if (state.wsConnection && state.wsConnection.readyState === WebSocket.OPEN) {
            // console.log('[ChatBoxStore] 🛑 发送终止信号...');
            
            // ✅ 先发送取消任务信号给后端
            state.wsConnection.send(JSON.stringify({
              type: 'cancel_task',
              taskId: 'current_llm_generation'  // 标记为当前LLM生成任务
            }));
            
            // 等待一小段时间让后端处理
            setTimeout(() => {
              if (state.wsConnection) {
                state.wsConnection.close();
                // console.log('[ChatBoxStore] 🔌 WebSocket 已关闭');
              }
            }, 100);
          }
          
          return {
            isGenerating: false,
            wsConnection: null
          };
        }),

        // 加载聊天历史
        fetchChatHistory: async (roleName, chatName) => {
          const currentState = get();
          
          // 如果已经在加载中，跳过
          if (currentState.isLoading) {
            // console.log(`[ChatBoxStore] 跳过重复加载: ${roleName}/${chatName}`);
            return;
          }
          
          set({ isLoading: true, error: null });
          try {
            // 确俚chatName是字符串
            const actualChatName = typeof chatName === 'object' && chatName !== null ? chatName.chat_name : chatName;
            const response = await fetch(`/api/chat/${encodeURIComponent(roleName)}/${encodeURIComponent(actualChatName)}`);
            if (!response.ok) {
              throw new Error('Failed to fetch chat history');
            }
            const data = await response.json();
        
            let messages = data.messages || [];
                    
            // 如果消息为空，尝试获取角色的 first_mes 并显示为第一条消息（仅前端显示）
            if (messages.length === 0) {
              try {
                const characterResponse = await fetch(`/api/characters/${encodeURIComponent(roleName)}`);
                if (characterResponse.ok) {
                  const characterData = await characterResponse.json();
                  if (characterData.first_mes && characterData.first_mes.trim()) {
                    // 创建临时的开场白消息（不保存到后端）
                    messages = [{
                      id: Date.now(), // ✅ 添加唯一 ID
                      floor: 1,
                      mes: characterData.first_mes,
                      is_user: false,
                      name: characterData.name || roleName,
                      sendDate: new Date().toISOString()
                    }];
                    // console.log(`[ChatBoxStore] 显示角色 ${roleName} 的开场白（临时消息）`);
                  }
                }
              } catch (error) {
                // console.warn('[ChatBoxStore] 获取角色信息失败:', error);
              }
            }
        
            // 只更新消息相关状态，不更新 currentRole/currentChat（避免触发监听器）
            set({
              messages: messages,
              userName: data.metadata?.user_name || 'User',
              characterName: data.metadata?.character_name || roleName || 'Assistant',
              isLoading: false
            });
            
            // console.log(`[ChatBoxStore] 已加载聊天: ${roleName}/${actualChatName}, 消息数: ${messages.length}`);
          } catch (error) {
            set({
              error: error.message,
              isLoading: false
            });
            // console.error('[ChatBoxStore] 加载聊天失败:', error);
          }
        },

        // 清空聊天历史
        clearChatHistory: () => set({
          messages: [],
          userName: '',
          characterName: '',
          error: null
        }),

        // 更新特定消息的内容
        updateMessage: async (floor, content) => {
          const { currentRole, currentChat } = get();
          try {
            const response = await fetch(`/api/chat/${encodeURIComponent(currentRole)}/${encodeURIComponent(currentChat)}/messages/${floor}`, {
              method: 'PUT',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ mes: content })
            });

            if (!response.ok) {
              throw new Error('Failed to update message');
            }

            set((state) => ({
              messages: state.messages.map((msg) =>
                msg.floor === floor ? { ...msg, mes: content } : msg
              )
            }));
          } catch (error) {
            set({ error: error.message });
          }
        },

        // 删除特定消息
        deleteMessage: async (floor) => {
          const { currentRole, currentChat } = get();
          try {
            const response = await fetch(`/api/chat/${encodeURIComponent(currentRole)}/${encodeURIComponent(currentChat)}/messages/${floor}`, {
              method: 'DELETE'
            });

            if (!response.ok) {
              throw new Error('Failed to delete message');
            }

            set((state) => ({
              messages: state.messages.filter((msg) => msg.floor !== floor)
            }));
          } catch (error) {
            set({ error: error.message });
          }
        },

        // 创建新聊天
        createChat: async (roleName, chatName, metadata = {}) => {
          try {
            const response = await fetch(`/api/chat/${encodeURIComponent(roleName)}`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                chat_name: chatName,
                metadata: {
                  user_name: 'User',
                  character_name: roleName,
                  ...metadata
                }
              })
            });

            if (!response.ok) {
              throw new Error('Failed to create chat');
            }

            return await response.json();
          } catch (error) {
            set({ error: error.message });
            throw error;
          }
        },

        // 更新聊天元数据
        updateChatMetadata: async (roleName, chatName, metadata) => {
          try {
            const response = await fetch(`/api/chat/${encodeURIComponent(roleName)}/${encodeURIComponent(chatName)}`, {
              method: 'PUT',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ metadata })
            });

            if (!response.ok) {
              throw new Error('Failed to update chat metadata');
            }

            return await response.json();
          } catch (error) {
            set({ error: error.message });
            throw error;
          }
        },

        // 删除聊天
        deleteChat: async (roleName, chatName) => {
          try {
            const response = await fetch(`/api/chat/${encodeURIComponent(roleName)}/${encodeURIComponent(chatName)}`, {
              method: 'DELETE'
            });

            if (!response.ok) {
              throw new Error('Failed to delete chat');
            }

            return await response.json();
          } catch (error) {
            set({ error: error.message });
            throw error;
          }
        }
      }),
      {
        name: 'chat-box-storage', // localStorage 中的键名
        partialize: (state) => ({
          // 只持久化选项状态，不持久化聊天历史等
          options: state.options
        }),
        merge: (persistedState, currentState) => {
          // 合并持久化状态和当前状态
          const merged = {
            ...currentState,
            ...persistedState,
          };
          
          // 确保 options 中的所有字段都存在，使用默认值填充缺失的字段
          if (persistedState?.options) {
            merged.options = {
              dynamicTable: persistedState.options.dynamicTable ?? false,
              streamOutput: persistedState.options.streamOutput ?? false,
              imageWorkflow: persistedState.options.imageWorkflow ?? false,
              // 兼容旧版本：如果存在 htmlRender/markdownRender，转换为 renderMode
              renderMode: (() => {
                // 优先使用新的 renderMode
                if (persistedState.options.renderMode) {
                  return persistedState.options.renderMode;
                }
                // 兼容旧版本的 htmlRender/markdownRender
                if (persistedState.options.markdownRender) return 'markdown';
                if (persistedState.options.htmlRender) return 'html';
                return 'none';
              })(),
              autoDiceRoll: persistedState.options.autoDiceRoll ?? false,
            };
          }
          
          return merged;
        }
      }
    )
  )
);

// 监听角色和聊天变化，自动加载聊天历史
useChatBoxStore.subscribe(
  (state) => ({ role: state.currentRole, chat: state.currentChat }),
  ({ role, chat }, prev) => {
    console.log(`[ChatBoxStore 监听器] 状态变化检测:`, {
      当前: { role, chat },
      之前: prev,
      角色变化: role !== prev.role,
      聊天变化: chat !== prev.chat
    });
    
    // 只有当角色或聊天发生变化时才处理
    if (role !== prev.role || chat !== prev.chat) {
      // 确保角色存在
      if (role) {
        // 如果聊天也存在，加载聊天历史
        if (chat) {
          // 确俚chat是字符串，如果是对象则提取chat_name
          const actualChat = typeof chat === 'object' && chat !== null ? chat.chat_name : chat;
          
          // 检查是否已经在加载中，避免重复加载
          const currentState = useChatBoxStore.getState();
          console.log(`[ChatBoxStore 监听器] isLoading 状态:`, currentState.isLoading);
          
          if (!currentState.isLoading) {
            console.log(`[ChatBoxStore 监听器] ✅ 开始加载聊天: ${role}/${actualChat}`);
            useChatBoxStore.getState().fetchChatHistory(role, actualChat);
          } else {
            console.log(`[ChatBoxStore 监听器] ⏭️ 跳过加载，正在加载中: ${role}/${actualChat}`);
          }
        } else {
          // 聊天为 null，只设置角色，不加载聊天（等待用户发送第一条消息）
          console.log(`[ChatBoxStore 监听器] ℹ️ 只设置角色，未选择聊天: ${role}`);
          useChatBoxStore.setState({
            currentRole: role,
            currentChat: null,
            messages: [],  // 清空消息
            characterName: role  // 使用角色名作为显示名称
          });
        }
      } else {
        // 角色也为 null，完全清空
        console.log(`[ChatBoxStore 监听器] 🗑️ 清空所有状态`);
        useChatBoxStore.getState().clearChatHistory();
      }
    } else {
      console.log(`[ChatBoxStore 监听器] ⏸️ 无变化，不触发加载`);
    }
  },
  { equalityFn: (a, b) => a.role === b.role && a.chat === b.chat }
);

export default useChatBoxStore;