<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Palette</title>
    <script>
        // 在页面加载前初始化主题
        (function() {
            const savedConfig = JSON.parse(localStorage.getItem('aiPaletteConfig') || '{}');
            if (savedConfig.theme) {
                document.documentElement.classList.toggle('dark', savedConfig.theme === 'dark');
            } else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
                document.documentElement.classList.add('dark');
            }
        })();
    </script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {}
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer components {
            .gradient-bg {
                @apply dark:bg-gradient-to-br dark:from-slate-900 dark:to-slate-800 bg-gradient-to-br from-slate-50 to-slate-100;
            }
            .floating-image {
                @apply fixed left-8 top-8 w-[320px] rounded-lg shadow-lg transition-transform duration-300
                       hover:shadow-xl z-50;
                filter: drop-shadow(0 4px 12px rgba(0, 120, 255, 0.2));
            }
            .floating-image:hover {
                @apply -translate-y-1 rotate-1;
                filter: drop-shadow(0 8px 16px rgba(0, 120, 255, 0.3));
            }
            .github-corner:hover .octo-arm {
                animation: octocat-wave 560ms ease-in-out;
            }
            @keyframes octocat-wave {
                0%, 100% { transform: rotate(0) }
                20%, 60% { transform: rotate(-25deg) }
                40%, 80% { transform: rotate(10deg) }
            }
            .input-base {
                @apply w-full rounded-lg border shadow-sm backdrop-blur-sm px-4 py-3
                       dark:border-gray-700/50 dark:bg-gray-800/50 dark:text-gray-100
                       border-gray-200 bg-white/90 text-gray-900
                       dark:hover:border-blue-400/40 dark:hover:bg-gray-800/70
                       hover:border-blue-400/40 hover:bg-white
                       dark:focus:border-blue-400 dark:focus:bg-gray-800/90 dark:focus:ring-2 dark:focus:ring-blue-500/20
                       focus:border-blue-400 focus:bg-white focus:ring-2 focus:ring-blue-500/20 focus:outline-none
                       transition-all duration-200;
            }
            .btn-primary {
                @apply w-full bg-gradient-to-r from-blue-500 to-blue-600
                       text-white py-3 px-4 rounded-lg font-medium
                       hover:opacity-90 active:opacity-80
                       transform active:scale-[0.99]
                       transition-all duration-200
                       shadow-sm hover:shadow-blue-500/10 focus:shadow-md focus:outline-none;
            }
            .label-text {
                @apply block text-sm font-medium mb-1.5
                       dark:text-gray-300 text-gray-700;
            }
            .response-box {
                @apply w-full rounded-lg p-4 min-h-[100px] whitespace-pre-wrap backdrop-blur-sm shadow-sm
                       dark:bg-gray-800/50 dark:border dark:border-gray-700/50 dark:text-gray-100
                       bg-white/90 border border-gray-200 text-gray-900;
            }
            select {
                @apply input-base appearance-none bg-no-repeat cursor-pointer pr-10;
                background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%239ca3af' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
                background-position: right 0.75rem center;
                background-size: 1.5em 1.5em;
            }
            input[type="checkbox"] {
                @apply w-5 h-5 rounded-md cursor-pointer transition-colors duration-200
                       focus:ring-0 focus:ring-offset-0
                       dark:border-gray-700 dark:bg-gray-800 dark:text-blue-500
                       border-gray-300 bg-white text-blue-500;
            }
            ::placeholder {
                @apply dark:text-gray-500 text-gray-400;
            }
            option {
                @apply dark:bg-gray-800 dark:text-gray-100 bg-white text-gray-900;
            }
            .reasoning-content {
                @apply overflow-hidden transition-all duration-300 ease-in-out;
            }
            .reasoning-arrow {
                @apply transform transition-transform duration-300 ease-in-out;
            }
            .breathing-button {
                @apply animate-pulse;
                animation: breathing 2s ease-in-out infinite;
            }
            
            @keyframes breathing {
                0% {
                    box-shadow: 0 0 0 0 rgba(147, 51, 234, 0.7);
                }
                70% {
                    box-shadow: 0 0 0 10px rgba(147, 51, 234, 0);
                }
                100% {
                    box-shadow: 0 0 0 0 rgba(147, 51, 234, 0);
                }
            }

            .thinking-label {
                @apply px-2 py-0.5;
                animation: thinkingBreathing 2s ease-in-out infinite;
            }
            
            @keyframes thinkingBreathing {
                0% {
                    color: rgb(244, 114, 182);
                    text-shadow: 0 0 5px rgba(244, 114, 182, 0.5);
                }
                50% {
                    color: rgb(236, 72, 153);
                    text-shadow: 0 0 10px rgba(236, 72, 153, 0.7);
                }
                100% {
                    color: rgb(244, 114, 182);
                    text-shadow: 0 0 5px rgba(244, 114, 182, 0.5);
                }
            }

            .thinking-label.thinking-done {
                @apply text-slate-400;
                animation: none;
                text-shadow: none;
            }

            .thinking-text {
                @apply text-slate-400;
            }
        }
    </style>
</head>
<body class="dark:bg-slate-900 dark:text-slate-200 bg-slate-50 text-slate-900">
    <!-- 欢迎模态框 -->
    <div id="welcomeModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 opacity-0 pointer-events-none transition-opacity duration-300">
        <div class="relative bg-white dark:bg-slate-800 rounded-xl max-w-lg w-full mx-4 p-6 shadow-xl transform transition-transform duration-300 scale-95">
            <div class="absolute top-4 right-4">
                <button onclick="closeWelcomeModal()" class="dark:text-slate-400 text-slate-500 dark:hover:text-slate-300 hover:text-slate-700">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none">
                        <path d="M18 6l-12 12"></path>
                        <path d="M6 6l12 12"></path>
                    </svg>
                </button>
            </div>
            <div class="space-y-4">
                <h2 class="text-2xl font-bold dark:text-white text-slate-900">欢迎使用 AI Palette! 🎨</h2>
                <div class="space-y-2">
                    <p class="dark:text-slate-300 text-slate-600">AI Palette 是一个统一的 AI 接口平台，支持多种平台：</p>
                    <ul class="list-disc pl-5 dark:text-slate-300 text-slate-600 space-y-1">
                        <li><span class="font-medium text-blue-500"><a href="https://cloud.siliconflow.cn/i/gQhQNfpv" target="_blank" class="text-blue-500 hover:text-blue-600">硅基流动</a></span> - 推荐！提供丰富的模型选择，响应速度快</li>
                        <li><span class="font-medium">Ollama</span> - 本地部署，无需 API Key</li>
                        <li><span class="font-medium">其他</span> - DeepSeek、OpenAI、智谱、千问等。</li>
                    </ul>
                </div>
                <div class="bg-slate-50 dark:bg-slate-700/50 rounded-lg p-4 space-y-2">
                    <p class="dark:text-slate-300 text-slate-600 font-medium">快速开始：</p>
                    <p class="dark:text-slate-400 text-slate-600">1. 选择平台（推荐使用硅基流动，免费用Qwen2.5）</p>
                    <p class="dark:text-slate-400 text-slate-600">2. 输入 API Key（<a href="https://cloud.siliconflow.cn/i/gQhQNfpv" target="_blank" class="text-blue-500 hover:text-blue-600">点击获取</a>）</p>
                    <p class="dark:text-slate-400 text-slate-600">3. 开始对话！</p>
                </div>
                <div class="bg-slate-50 dark:bg-slate-700/50 rounded-lg p-4">
                    <div class="flex items-center justify-between">
                        <div class="dark:text-slate-300 text-slate-600">
                            <p class="font-medium">有任何想法？</p>
                            <p class="text-sm mt-1">扫描二维码关注我们，获取帮助和更新！</p>
                        </div>
                        <img src="/static/image/qrcode.jpg" alt="Connect" class="w-24 h-24 rounded-lg dark:border-slate-600 border-slate-200 border">
                    </div>
                </div>
                <div class="flex justify-end pt-2">
                    <button onclick="closeWelcomeModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:focus:ring-offset-slate-800 focus:ring-offset-white">
                        开始使用
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 主容器 -->
    <div class="flex h-screen">
        <!-- 左侧设置面板 -->
        <div class="w-80 border-r dark:border-slate-700 border-slate-200 dark:bg-slate-800 bg-white p-6 flex flex-col">
            <div class="mb-6">
                <div class="flex items-center justify-between mb-2">
                    <h1 class="text-2xl font-bold dark:text-white text-slate-800">AI Palette 🎨</h1>
                    <div class="flex">
                        <div class="rounded-md border dark:border-slate-200/20 border-slate-200">
                            <div class="flex text-[10px] font-medium leading-4">
                                <button onclick="toggleTheme('dark')" class="theme-toggle dark-toggle flex w-auto gap-1 rounded-l-md px-2 py-1 focus:outline-none dark:text-slate-300 text-slate-500 dark:hover:bg-slate-700/50 hover:bg-slate-100">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="inline-flex h-3.5 w-3.5">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path>
                                    </svg>
                                </button>
                                <button onclick="toggleTheme('light')" class="theme-toggle light-toggle flex gap-1 rounded-r-md px-2 py-1 focus:outline-none dark:text-slate-300 text-slate-500 dark:hover:bg-slate-700/50 hover:bg-slate-100">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" class="inline-flex h-3.5 w-3.5" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <p class="dark:text-slate-400 text-slate-600 text-sm">统一 AI 接口，一个调用满足所有需求</p>
            </div>

            <!-- 模型设置 -->
            <div class="space-y-4 flex-1">
                <div>
                    <label class="block text-sm font-medium dark:text-slate-300 text-slate-600 mb-1">模型提供商</label>
                    <select id="modelType" onchange="handleModelTypeChange()" class="input-base">
                        <option value="siliconflow">硅基流动</option>
                        <option value="deepseek">DeepSeek</option>
                        <option value="ollama">Ollama</option>
                        <option value="openai">OpenAI</option>
                        <option value="zhipu">智谱AI</option>
                        <option value="dashscope">通义千问</option>
                        <option value="minimax">MiniMax</option>
                        <option value="ernie">百度文心</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium dark:text-slate-300 text-slate-600 mb-1">API Key</label>
                    <div class="relative">
                        <input type="password" id="apiKey" class="input-base" 
                            placeholder="输入你的 API Key"
                            onblur="handleApiKeyChange()">
                        <button onclick="toggleApiKeyVisibility()" class="absolute right-2 top-1/2 -translate-y-1/2 dark:text-slate-400 text-slate-500 dark:hover:text-slate-300 hover:text-slate-700">
                            <svg id="eyeIcon" xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none">
                                <path d="M12 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"></path>
                                <path d="M22 12c-2.667 4.667 -6 7 -10 7s-7.333 -2.333 -10 -7c2.667 -4.667 6 -7 10 -7s7.333 2.333 10 7"></path>
                            </svg>
                        </button>
                    </div>
                    <a id="apiKeyHelp" href="#" target="_blank" class="text-sm text-blue-500 hover:text-blue-600 mt-1 inline-block">
                        跳转官网获取 API Key
                    </a>
                </div>

                <div>
                    <label class="block text-sm font-medium dark:text-slate-300 text-slate-600 mb-1">模型名称</label>
                    <div class="relative">
                        <input 
                            type="text" 
                            id="model" 
                            class="input-base pr-20" 
                            placeholder="选择或输入模型名称"
                            oninput="filterModels(this.value)"
                            onclick="showModelDropdown()"
                            autocomplete="off"
                        >
                        <button 
                            onclick="refreshModels()"
                            type="button"
                            class="absolute right-2 top-1/2 -translate-y-1/2 dark:text-slate-400 text-slate-500 dark:hover:text-slate-300 hover:text-slate-700"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none">
                                <path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4"></path>
                                <path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4"></path>
                            </svg>
                        </button>
                        <!-- 模型列表下拉框 -->
                        <div id="modelDropdown" class="hidden absolute left-0 right-0 z-50 mt-1 max-h-60 overflow-auto rounded-lg dark:bg-slate-700 bg-white dark:border-slate-600 border-slate-200 border shadow-lg">
                            <div id="modelList" class="py-1">
                                <!-- 模型选项将通过 JavaScript 动态添加 -->
                            </div>
                        </div>
                    </div>
                </div>

                <div class="flex items-center space-x-3">
                    <input type="checkbox" id="enableStreaming" class="rounded dark:border-slate-600 border-slate-300">
                    <label class="text-sm font-medium dark:text-slate-300 text-slate-600">启用流式输出</label>
                </div>
            </div>

            <!-- 底部链接 -->
            <div class="mt-auto space-y-4">
                <!-- 清除对话历史 -->
                <div>
                    <button onclick="clearAllMessages()" class="w-full flex items-center justify-center space-x-2 px-4 py-3 rounded-lg bg-red-500/10 dark:text-red-400 text-red-600 hover:bg-red-500/20 dark:hover:bg-red-500/20 transition-colors duration-200 border dark:border-red-900/50 border-red-200">
                        <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                        <span class="text-base">清空对话历史</span>
                    </button>
                </div>

                <!-- GitHub 链接 -->
                <div class="text-center">
                    <a href="https://github.com/itshen/ai_palette" class="inline-flex items-center gap-2 text-sm font-medium dark:text-slate-200 text-slate-600 hover:text-blue-500 transition-colors duration-200" target="_blank">
                        <svg class="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
                            <path fill-rule="evenodd" clip-rule="evenodd" d="M12 2C6.477 2 2 6.477 2 12c0 4.42 2.87 8.17 6.84 9.5.5.08.66-.23.66-.5v-1.69c-2.77.6-3.36-1.34-3.36-1.34-.46-1.16-1.11-1.47-1.11-1.47-.91-.62.07-.6.07-.6 1 .07 1.53 1.03 1.53 1.03.87 1.52 2.34 1.07 2.91.83.09-.65.35-1.09.63-1.34-2.22-.25-4.55-1.11-4.55-4.92 0-1.11.38-2 1.03-2.71-.1-.25-.45-1.29.1-2.64 0 0 .84-.27 2.75 1.02.79-.22 1.65-.33 2.5-.33.85 0 1.71.11 2.5.33 1.91-1.29 2.75-1.02 2.75-1.02.55 1.35.2 2.39.1 2.64.65.71 1.03 1.6 1.03 2.71 0 3.82-2.34 4.66-4.57 4.91.36.31.69.92.69 1.85V21c0 .27.16.59.67.5C19.14 20.16 22 16.42 22 12A10 10 0 0012 2z"/>
                        </svg>
                        GitHub 仓库
                    </a>
                </div>
                <!-- 二维码 -->
                <div>
                    <img src="/static/image/connect.jpg" alt="Connect" class="w-full rounded-lg dark:border-slate-600 border-slate-200 border">
                </div>
            </div>
        </div>

        <!-- 右侧对话界面 -->
        <div class="flex-1 flex flex-col">
            <!-- 消息列表 -->
            <div class="flex-1 overflow-y-auto p-4" id="messageList">
                <!-- 对话建议 -->
                <div id="suggestionBox" class="mb-4">
                    <div class="flex flex-wrap gap-2 text-xs">
                        <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                            帮我制定一份一周健康饮食计划
                        </button>
                        <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                            如何缓解工作压力和情绪
                        </button>
                        <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                            推荐一些室内植物养护小技巧
                        </button>
                        <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                            分享一些提高睡眠质量的方法
                        </button>
                        <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                            推荐几道简单美味的家常菜
                        </button>
                        <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                            如何整理和收纳小户型空间
                        </button>
                        <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                            分享一些省钱小妙招
                        </button>
                    </div>
                </div>
            </div>

            <!-- 输入框 -->
            <div class="p-4 border-t dark:border-slate-700 border-slate-200">
                <form onsubmit="sendMessage(); return false;">
                    <div class="relative">
                        <textarea 
                            id="prompt" 
                            class="input-base pr-24 resize-none"
                            rows="3"
                            placeholder="输入你想问的问题..."
                        ></textarea>
                        <button 
                            type="submit"
                            class="absolute bottom-3 right-3 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:focus:ring-offset-slate-800 focus:ring-offset-white"
                        >
                            发送
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // 在现有的 window.onload 函数开头添加
        window.onload = function() {
            // 检查是否是首次访问
            const hasVisited = localStorage.getItem('hasVisitedAIPalette');
            if (!hasVisited) {
                showWelcomeModal();
                localStorage.setItem('hasVisitedAIPalette', 'true');
            }

            // 恢复聊天记录
            restoreChatHistory();

            // 检测系统主题并设置初始状态
            if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
                document.documentElement.classList.remove('dark');
                updateThemeButtons('light');
            } else {
                updateThemeButtons('dark');
            }

            // 监听系统主题变化
            window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
                if (event.matches) {
                    document.documentElement.classList.add('dark');
                    updateThemeButtons('dark');
                } else {
                    document.documentElement.classList.remove('dark');
                    updateThemeButtons('light');
                }
            });

            // 加载已保存的配置
            const savedConfig = JSON.parse(localStorage.getItem('aiPaletteConfig') || '{}');
            if (savedConfig.modelType) {
                document.getElementById('modelType').value = savedConfig.modelType;
            }
            if (savedConfig.apiKey) {
                document.getElementById('apiKey').value = savedConfig.apiKey;
            }
            if (savedConfig.model) {
                document.getElementById('model').value = savedConfig.model;
            }
            if (savedConfig.hasOwnProperty('enableStreaming')) {
                document.getElementById('enableStreaming').checked = savedConfig.enableStreaming;
            }
            if (savedConfig.theme) {
                toggleTheme(savedConfig.theme);
            }

            // 确保在页面加载时更新 API Key 帮助链接
            updateApiKeyHelpLink();
            
            // 初始化后刷新模型列表
            handleModelTypeChange();
        };

        // 显示欢迎模态框
        function showWelcomeModal() {
            const modal = document.getElementById('welcomeModal');
            modal.style.opacity = '1';
            modal.style.pointerEvents = 'auto';
            const modalContent = modal.querySelector('.scale-95');
            setTimeout(() => {
                modalContent.classList.remove('scale-95');
                modalContent.classList.add('scale-100');
            }, 10);
        }

        // 关闭欢迎模态框
        function closeWelcomeModal() {
            const modal = document.getElementById('welcomeModal');
            const modalContent = modal.querySelector('.scale-100, .scale-95');
            if (modalContent) {
                modalContent.classList.remove('scale-100');
                modalContent.classList.add('scale-95');
            }
            setTimeout(() => {
                modal.style.opacity = '0';
                modal.style.pointerEvents = 'none';
            }, 200);
        }

        // 点击模态框背景关闭
        document.getElementById('welcomeModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeWelcomeModal();
            }
        });

        // 模型配置
        const modelConfigs = {
            'openai': ['gpt-4o-mini', 'gpt-4o', 'gpt-3.5-turbo'],
            'ernie': ['ernie-bot', 'ernie-bot-4'],
            'dashscope': ['qwen-turbo', 'qwen-plus', 'qwen-max'],
            'zhipu': ['GLM-4-Plus', 'GLM-4-Flash'],
            'minimax': ['abab6.5-chat', 'abab7-preview'],
            'ollama': [],
            'deepseek': ['deepseek-coder', 'deepseek-chat'],
            'siliconflow': ['deepseek-ai/DeepSeek-R1', 'Qwen/Qwen2.5-7B-Instruct']
        };

        // 存储所有模型列表
        let allModels = [];
        
        // 刷新模型列表
        async function refreshModels() {
            const modelType = document.getElementById('modelType').value;
            const apiKey = document.getElementById('apiKey').value;
            const modelList = document.getElementById('modelList');
            const modelInput = document.getElementById('model');
            
            try {
                // 显示加载状态
                modelInput.placeholder = '加载中...';
                modelInput.disabled = true;
                
                const response = await fetch(`/api/models?type=${modelType}&api_key=${apiKey}`);
                const data = await response.json();
                
                if (data.success) {
                    allModels = data.models || [];
                    updateModelList(allModels);
                    // 如果有模型，显示下拉框
                    if (allModels.length > 0) {
                        document.getElementById('modelDropdown').classList.remove('hidden');
                        modelInput.placeholder = '选择或输入模型名称';
                    } else {
                        modelInput.placeholder = '未找到可用模型';
                    }
                } else {
                    showError(data.error || '获取模型列表失败');
                    modelInput.placeholder = '获取模型失败';
                    allModels = [];
                }
            } catch (error) {
                showError('获取模型列表失败: ' + error.message);
                modelInput.placeholder = '获取模型失败';
                allModels = [];
            } finally {
                modelInput.disabled = false;
            }
        }
        
        // 修改过滤模型列表函数
        function filterModels(query) {
            const dropdown = document.getElementById('modelDropdown');
            const filteredModels = allModels.filter(model => 
                model.toLowerCase().includes(query.toLowerCase())
            );
            updateModelList(filteredModels);
            if (filteredModels.length > 0) {
                dropdown.classList.remove('hidden');
            }
        }
        
        // 修改显示模型下拉列表函数
        function showModelDropdown() {
            const dropdown = document.getElementById('modelDropdown');
            
            // 如果还没有模型列表数据，先获取
            if (allModels.length === 0) {
                refreshModels();
            } else {
                // 显示所有模型
                updateModelList(allModels);
                dropdown.classList.remove('hidden');
            }
        }
        
        // 更新模型列表显示
        function updateModelList(models) {
            const modelList = document.getElementById('modelList');
            modelList.innerHTML = '';
            
            if (models.length === 0) {
                const noModels = document.createElement('div');
                noModels.className = 'px-4 py-2 dark:text-slate-400 text-slate-500 text-center';
                noModels.textContent = '没有可用的模型';
                modelList.appendChild(noModels);
                return;
            }
            
            models.forEach(model => {
                const option = document.createElement('div');
                option.className = 'px-4 py-2 dark:hover:bg-slate-600 hover:bg-slate-100 cursor-pointer dark:text-slate-200 text-slate-700';
                option.textContent = model;
                option.onclick = () => {
                    document.getElementById('model').value = model;
                    document.getElementById('modelDropdown').classList.add('hidden');
                    
                    // 保存选择
                    const modelType = document.getElementById('modelType').value;
                    const config = JSON.parse(localStorage.getItem('aiPaletteConfig') || '{}');
                    config[`${modelType}_lastModel`] = model;
                    localStorage.setItem('aiPaletteConfig', JSON.stringify(config));
                };
                modelList.appendChild(option);
            });
        }
        
        // 显示错误信息
        function showError(message) {
            // 创建错误提示
            const errorDiv = document.createElement('div');
            errorDiv.className = 'fixed top-4 right-4 flex w-full max-w-md items-start justify-between rounded-xl dark:bg-slate-800 bg-white p-4 shadow-xl border dark:border-slate-700 border-slate-200';
            errorDiv.innerHTML = `
                <div class="flex gap-2 sm:gap-4">
                    <span class="text-red-500">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none">
                            <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path>
                            <path d="M12 9v4"></path>
                            <path d="M12 16v.01"></path>
                        </svg>
                    </span>
                    <div class="flex-1">
                        <strong class="block font-medium dark:text-slate-200 text-slate-900">错误</strong>
                        <p class="mt-1 text-sm dark:text-slate-300 text-slate-600">${message}</p>
                    </div>
                </div>
                <button onclick="this.parentElement.remove()" class="dark:text-slate-400 text-slate-500 dark:hover:text-slate-300 hover:text-slate-700">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none">
                        <path d="M18 6l-12 12"></path>
                        <path d="M6 6l12 12"></path>
                    </svg>
                </button>
            `;
            document.body.appendChild(errorDiv);
            
            // 添加进入动画
            errorDiv.style.opacity = '0';
            errorDiv.style.transform = 'translateY(-20px)';
            errorDiv.style.transition = 'all 0.3s ease-out';
            
            // 强制重绘
            errorDiv.offsetHeight;
            
            // 显示
            errorDiv.style.opacity = '1';
            errorDiv.style.transform = 'translateY(0)';
            
            // 3秒后自动消失
            setTimeout(() => {
                errorDiv.style.opacity = '0';
                errorDiv.style.transform = 'translateY(-20px)';
                setTimeout(() => errorDiv.remove(), 300);
            }, 3000);
        }
        
        // 修改处理模型类型变化的函数
        async function handleModelTypeChange() {
            const modelType = document.getElementById('modelType').value;
            const apiKeyInput = document.getElementById('apiKey');
            const modelInput = document.getElementById('model');
            
            // 更新帮助链接
            updateApiKeyHelpLink();
            
            // 从本地存储获取该模型类型的上次配置
            const savedConfig = JSON.parse(localStorage.getItem('aiPaletteConfig') || '{}');
            
            // 恢复上次使用的 API Key
            apiKeyInput.value = savedConfig[`${modelType}_apiKey`] || '';
            
            // 恢复上次使用的模型
            modelInput.value = savedConfig[`${modelType}_lastModel`] || '';
            
            // 清空当前模型列表
            allModels = [];
            document.getElementById('modelDropdown').classList.add('hidden');
            
            // 自动刷新模型列表
            refreshModels();
        }

        // 点击页面其他地方时隐藏下拉框
        document.addEventListener('click', function(e) {
            const dropdown = document.getElementById('modelDropdown');
            const modelInput = document.getElementById('model');
            const refreshButton = modelInput.nextElementSibling;
            
            if (!modelInput.contains(e.target) && !refreshButton.contains(e.target) && !dropdown.contains(e.target)) {
                dropdown.classList.add('hidden');
            }
        });

        // 监听模型输入框点击事件
        document.getElementById('model').addEventListener('click', function() {
            if (allModels.length > 0) {
                filterModels(this.value);
            }
        });

        // 保存配置
        function saveConfig() {
            const modelType = document.getElementById('modelType').value;
            const currentModel = document.getElementById('model').value;
            const currentApiKey = document.getElementById('apiKey').value;
            const enableStreaming = document.getElementById('enableStreaming').checked;
            
            const config = JSON.parse(localStorage.getItem('aiPaletteConfig') || '{}');
            
            config.modelType = modelType;
            config[`${modelType}_apiKey`] = currentApiKey;
            config[`${modelType}_lastModel`] = currentModel;
            config.enableStreaming = enableStreaming;
            
            localStorage.setItem('aiPaletteConfig', JSON.stringify(config));
        }

        // 切换 API Key 显示/隐藏
        function toggleApiKeyVisibility() {
            const apiKeyInput = document.getElementById('apiKey');
            apiKeyInput.type = apiKeyInput.type === 'password' ? 'text' : 'password';
        }

        // 更新 API Key 帮助链接
        function updateApiKeyHelpLink() {
            const modelType = document.getElementById('modelType').value || 'siliconflow';  // 添加默认值
            const helpLink = document.getElementById('apiKeyHelp');
            
            const helpLinks = {
                'openai': 'https://platform.openai.com/api-keys',
                'ernie': 'https://console.bce.baidu.com/qianfan/overview',
                'dashscope': 'https://bailian.console.aliyun.com/?apiKey=1',
                'zhipu': 'https://open.bigmodel.cn/usercenter/apikeys',
                'minimax': 'https://platform.minimaxi.com/user-center/basic-information/interface-key',
                'ollama': 'https://ollama.com',
                'deepseek': 'https://platform.deepseek.com/',
                'siliconflow': 'https://cloud.siliconflow.cn/i/gQhQNfpv'
            };
            
            helpLink.href = helpLinks[modelType] || helpLinks['siliconflow'];  // 添加默认值
            helpLink.style.display = (modelType === 'ollama') ? 'none' : 'inline-block';
        }

        // 添加转义 HTML 的函数
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 简单的markdown解析
        function parseMarkdown(text) {
            if (!text) return '';
            
            // 处理加粗 **text**
            text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            
            // 处理标题 ### text
            text = text.replace(/^###### (.*?)$/gm, '<h6 class="text-sm font-bold my-3">$1</h6>');
            text = text.replace(/^##### (.*?)$/gm, '<h5 class="text-base font-bold my-3">$1</h5>');
            text = text.replace(/^#### (.*?)$/gm, '<h4 class="text-lg font-bold my-3">$1</h4>');
            text = text.replace(/^### (.*?)$/gm, '<h3 class="text-xl font-bold my-3">$1</h3>');
            text = text.replace(/^## (.*?)$/gm, '<h2 class="text-2xl font-bold my-3">$1</h2>');
            text = text.replace(/^# (.*?)$/gm, '<h1 class="text-3xl font-bold my-4">$1</h1>');
            
            // 处理列表 - text
            text = text.replace(/^- (.*?)$/gm, '<li class="ml-4">$1</li>');
            
            // 处理分隔线 ---
            text = text.replace(/^---$/gm, '<hr class="my-4 border-t dark:border-slate-700 border-slate-200">');
            
            // 处理换行，保持原有的换行
            text = text.split('\n').map(line => {
                if (!line.startsWith('<') && line.trim() !== '') {
                    return `<p class="mb-1">${line}</p>`;
                }
                return line;
            }).join('\n');
            
            return text;
        }

        // 发送消息
        async function sendMessage() {
            const messageList = document.getElementById('messageList');
            const prompt = document.getElementById('prompt').value;
            const modelType = document.getElementById('modelType').value;
            const apiKey = document.getElementById('apiKey').value;
            const model = document.getElementById('model').value;
            const enableStreaming = document.getElementById('enableStreaming').checked;

            if (!prompt) return;

            // 隐藏建议框
            const suggestionBox = document.getElementById('suggestionBox');
            if (suggestionBox) {
                suggestionBox.remove();  // 完全移除建议框
            }

            // 清除全局变量
            window.currentResponse = '';
            window.currentReasoning = '';
            window.isThinking = false;

            // 保存配置
            saveConfig();

            // 收集上下文
            let context = [];
            // 如果是重新发起的对话，使用保存的上下文
            if (window.reaskContext) {
                context = window.reaskContext;
                window.reaskContext = null;  // 使用后清除
            } else {
                // 正常收集上下文
                const messages = messageList.children;
                for (const message of messages) {
                    if (message.querySelector('.bg-blue-600')) {  // 用户消息
                        const pElement = message.querySelector('p');
                        context.push({
                            role: 'user',
                            content: pElement.dataset.originalContent || pElement.textContent.replace(/<br\s*\/?>/g, '\n')
                        });
                    } else if (message.querySelector('.bg-purple-600')) {  // AI 消息
                        const responseElement = message.querySelector('pre');
                        if (responseElement && responseElement.textContent && responseElement.textContent !== '...') {
                            context.push({
                                role: 'assistant',
                                content: responseElement.dataset.originalContent || responseElement.textContent.replace(/<br\s*\/?>/g, '\n')
                            });
                        }
                    }
                }
            }

            // 添加用户消息
            const userMessage = document.createElement('div');
            userMessage.className = 'flex items-start space-x-3 mb-4';
            // 将换行符转换为 <br/>
            const displayContent = prompt.replace(/\n/g, '<br/>');
            userMessage.innerHTML = `
                <div class="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center flex-shrink-0 text-white">U</div>
                <div class="flex-1 dark:bg-slate-800 bg-white rounded-lg p-4 dark:border-slate-700 border-slate-200 border">
                    <p class="dark:text-slate-200 text-slate-700" data-original-content="${escapeHtml(prompt)}">${displayContent}</p>
                </div>
            `;
            // 保存用户消息到聊天记录
            const messages = JSON.parse(localStorage.getItem('aiPaletteChatHistory') || '[]');
            messages.push({
                type: 'user',
                content: prompt  // 保存原始内容，包含 \n
            });
            localStorage.setItem('aiPaletteChatHistory', JSON.stringify(messages));

            messageList.appendChild(userMessage);

            // 添加 AI 回复容器
            const aiMessage = addAIMessage(prompt);
            messageList.appendChild(aiMessage);

            // 清空输入框
            document.getElementById('prompt').value = '';

            // 发送请求
            try {
                if (enableStreaming) {
                    const response = await fetch('/api/chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            model_type: modelType,
                            api_key: apiKey,
                            model: model,
                            prompt: prompt,
                            enable_streaming: true,
                            include_reasoning: true,
                            context: context
                        })
                    });

                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    const responseElement = aiMessage.querySelector('pre');
                    const reasoningElement = aiMessage.querySelector('div[id^="ai-reasoning"]');
                    responseElement.textContent = '';
                    window.currentResponse = '';  // 清除缓存

                    while (true) {
                        const {value, done} = await reader.read();
                        if (done) {
                            // 移除呼吸灯效果
                            document.querySelector('button[type="submit"]').classList.remove('breathing-button');
                            saveChatHistory();
                            break;
                        }

                        const text = decoder.decode(value);
                        const lines = text.split('\n');

                        for (const line of lines) {
                            if (line.startsWith('data: ')) {
                                try {
                                    const data = JSON.parse(line.slice(6));
                                    
                                    // 处理不同类型的消息
                                    if (data.type === 'reasoning') {
                                        // 如果还没有思考容器,创建一个
                                        if (!reasoningElement.querySelector('.reasoning-content')) {
                                            reasoningElement.innerHTML = `
                                                <div class="text-slate-400">
                                                    <div class="flex items-center cursor-pointer hover:text-slate-300 transition-colors duration-200" onclick="toggleReasoning(this)">
                                                        <svg class="w-4 h-4 mr-1 reasoning-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" style="transform: rotate(90deg)">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                                                        </svg>
                                                        <span class="thinking-label">思考过程</span>
                                                    </div>
                                                    <div class="pl-5 mt-2 reasoning-content" style="height: auto; transition: height 0.3s">
                                                        <div class="whitespace-pre-wrap text-slate-400"></div>
                                                    </div>
                                                </div>`;
                                        }
                                        
                                        // 添加内容
                                        const reasoningContent = reasoningElement.querySelector('.reasoning-content');
                                        const reasoningDiv = reasoningContent.querySelector('div');
                                        const text = data.content;
                                        // 累积推理内容
                                        if (!window.currentReasoning) window.currentReasoning = '';
                                        window.currentReasoning += text;
                                        // 保存原始内容
                                        reasoningDiv.dataset.originalContent = window.currentReasoning;
                                        // 应用 markdown 解析
                                        reasoningDiv.innerHTML = parseMarkdown(window.currentReasoning);
                                    } else if (data.type === 'content') {
                                        // 如果是<think>且没有思考容器,创建一个
                                        if (data.content === '<think>' && !reasoningElement.querySelector('.reasoning-content')) {
                                            reasoningElement.innerHTML = `
                                                <div class="text-slate-400">
                                                    <div class="flex items-center cursor-pointer hover:text-slate-300 transition-colors duration-200" onclick="toggleReasoning(this)">
                                                        <svg class="w-4 h-4 mr-1 reasoning-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" style="transform: rotate(90deg)">
                                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                                                        </svg>
                                                        <span class="thinking-label">思考过程</span>
                                                    </div>
                                                    <div class="pl-5 mt-2 reasoning-content" style="height: auto; transition: height 0.3s">
                                                        <div class="whitespace-pre-wrap text-slate-400"></div>
                                                    </div>
                                                </div>`;
                                            window.isThinking = true;
                                        }
                                        // 如果是</think>,收起思考过程
                                        else if (data.content === '</think>') {
                                            window.isThinking = false;
                                        }
                                        // 如果在思考过程中,内容添加到思考过程中
                                        else if (window.isThinking && reasoningElement.querySelector('.reasoning-content')) {
                                            const reasoningContent = reasoningElement.querySelector('.reasoning-content');
                                            const reasoningDiv = reasoningContent.querySelector('div');
                                            const text = data.content;
                                            // 累积推理内容
                                            if (!window.currentReasoning) window.currentReasoning = '';
                                            window.currentReasoning += text;
                                            // 应用 markdown 解析
                                            reasoningDiv.innerHTML = parseMarkdown(window.currentReasoning);
                                        }
                                        // 其他情况,显示在响应区域
                                        else {
                                            // 停止思考标签的动画
                                            const thinkingLabel = reasoningElement.querySelector('.thinking-label');
                                            if (thinkingLabel) {
                                                thinkingLabel.classList.add('thinking-done');
                                            }
                                            // 直接添加内容,不做markdown解析
                                            if (window.currentResponse === undefined) {
                                                window.currentResponse = '';
                                            }
                                            // 收到内容时就直接将连续换行符替换为单个换行符
                                            const content = data.content.replace(/\n\n/g, '\n');
                                            window.currentResponse += content;
                                            
                                            // 保存原始内容
                                            responseElement.dataset.originalContent = window.currentResponse;
                                            
                                            // 尝试解析整个内容的markdown
                                            try {
                                                responseElement.innerHTML = parseMarkdown(window.currentResponse);
                                                // 保存原始内容
                                                responseElement.dataset.originalContent = window.currentResponse;
                                            } catch (e) {
                                                // 如果解析失败,至少显示原始内容
                                                responseElement.textContent = window.currentResponse;
                                            }
                                        }
                                    }
                                } catch (e) {
                                    console.error('解析响应失败:', e);
                                }
                            }
                        }
                    }
                } else {
                    const response = await fetch('/api/chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            model_type: modelType,
                            api_key: apiKey,
                            model: model,
                            prompt: prompt,
                            enable_streaming: false,
                            include_reasoning: true,
                            context: context
                        })
                    });

                    const data = await response.json();
                    const responseElement = aiMessage.querySelector('pre');
                    const reasoningElement = aiMessage.querySelector('div[id^="ai-reasoning"]');
                    
                    if (data.success) {
                        responseElement.textContent = data.response;
                        if (data.reasoning) {
                            responseElement.innerHTML = parseMarkdown(data.response);
                            reasoningElement.innerHTML = `
                                <div class="text-slate-400">
                                    <div class="flex items-center cursor-pointer hover:text-slate-300 transition-colors duration-200" onclick="toggleReasoning(this)">
                                        <svg class="w-4 h-4 mr-1 reasoning-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" style="transform: rotate(0deg)">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                                        </svg>
                                        思考过程
                                    </div>
                                    <div class="pl-5 mt-2 reasoning-content" style="height: 0">
                                        <pre class="whitespace-pre-wrap">${data.reasoning}</pre>
                                    </div>
                                </div>`;
                        } else {
                            reasoningElement.remove();
                        }
                        // 在成功时保存聊天记录
                        saveChatHistory();
                    } else {
                        responseElement.textContent = '错误: ' + data.error;
                        responseElement.classList.add('text-red-500');
                        reasoningElement.remove();
                    }
                }
            } catch (error) {
                // 移除呼吸灯效果
                document.querySelector('button[type="submit"]').classList.remove('breathing-button');
                const responseElement = aiMessage.querySelector('pre');
                responseElement.textContent = '请求失败: ' + error.message;
                responseElement.classList.add('text-red-500');
            }
        }

        // 监听回车键发送消息
        document.getElementById('prompt').addEventListener('keydown', function(e) {
            // 如果正在使用输入法（IME），不处理回车事件
            if (e.isComposing || e.keyCode === 229) {
                return;
            }
            
            // 如果按下的是回车键，但同时按着 Shift 键，则允许换行
            if (e.key === 'Enter' && e.shiftKey) {
                return;
            }
            
            // 如果按下的是回车键
            if (e.key === 'Enter') {
                // 阻止默认的换行行为
                e.preventDefault();
                
                // 获取当前输入的内容
                const content = this.value.trim();
                
                // 如果内容为空，或者内容只包含换行符，则不发送
                if (!content || content.length === 0) {
                    return;
                }
                
                // 如果最后一次按键到现在的时间小于 500ms，则不发送
                // 这可以防止用户在快速输入时意外触发发送
                if (this.lastKeyTime && Date.now() - this.lastKeyTime < 500) {
                    return;
                }
                
                // 记录这次按键的时间
                this.lastKeyTime = Date.now();
                
                // 发送消息
                sendMessage();
            }
        });

        // 处理 API Key 变化
        function handleApiKeyChange() {
            const modelType = document.getElementById('modelType').value;
            const apiKey = document.getElementById('apiKey').value;
            
            // 保存到本地存储
            const config = JSON.parse(localStorage.getItem('aiPaletteConfig') || '{}');
            config[`${modelType}_apiKey`] = apiKey;
            localStorage.setItem('aiPaletteConfig', JSON.stringify(config));
            
            // 刷新模型列表
            if (modelType === 'ollama' || ['openai', 'dashscope', 'deepseek', 'siliconflow'].includes(modelType)) {
                refreshModels();
            }
        }

        // 修改折叠/展开功能
        function toggleReasoning(element) {
            const content = element.nextElementSibling;
            const arrow = element.querySelector('.reasoning-arrow');
            
            if (content.style.height === '0px' || content.style.height === '0') {
                content.style.height = content.scrollHeight + 'px';
                arrow.style.transform = 'rotate(90deg)';
                // 设置一个延时，等过渡动画完成后设置为 auto
                setTimeout(() => {
                    content.style.height = 'auto';
                }, 300);
            } else {
                // 先设置为具体高度，以便动画
                content.style.height = content.scrollHeight + 'px';
                // 强制重绘
                content.offsetHeight;
                // 然后设置为 0
                content.style.height = '0';
                arrow.style.transform = 'rotate(0deg)';
            }
            
            // 保存状态
            saveChatHistory();
        }

        // 修改重新发起对话函数
        function reaskQuestion(button) {
            const aiMessage = button.closest('.flex.items-start');
            const userMessage = aiMessage.previousElementSibling;
            const pElement = userMessage.querySelector('p');
            // 使用原始内容，如果没有则回退到显示内容
            const prompt = pElement.dataset.originalContent || pElement.innerHTML.replace(/<br\s*\/?>/g, '\n');
            
            // 收集之前的所有对话内容
            const messageList = document.getElementById('messageList');
            const context = [];
            const messages = messageList.children;
            
            // 遍历到当前消息为止的所有消息
            for (let i = 0; i < messages.length; i++) {
                const message = messages[i];
                // 如果到达当前用户消息，就停止
                if (message === userMessage) {
                    break;
                }
                
                if (message.querySelector('.bg-blue-600')) {  // 用户消息
                    const pElement = message.querySelector('p');
                    context.push({
                        role: 'user',
                        content: pElement.dataset.originalContent || pElement.innerHTML.replace(/<br\s*\/?>/g, '\n')
                    });
                } else if (message.querySelector('.bg-purple-600')) {  // AI 消息
                    const responseElement = message.querySelector('pre');
                    // 使用 dataset.originalContent 获取原始内容，如果没有则使用 textContent
                    const content = responseElement.dataset.originalContent || responseElement.textContent;
                    if (content && content !== '...') {
                        context.push({
                            role: 'assistant',
                            content: content
                        });
                    }
                }
            }
            
            // 设置输入框内容
            document.getElementById('prompt').value = prompt;
            
            // 移除当前的 AI 回复和用户消息
            aiMessage.remove();
            userMessage.remove();
            
            // 更新本地存储的聊天记录
            const storedMessages = JSON.parse(localStorage.getItem('aiPaletteChatHistory') || '[]');
            // 移除最后两条消息（当前的用户消息和AI回复）
            storedMessages.splice(-2, 2);
            localStorage.setItem('aiPaletteChatHistory', JSON.stringify(storedMessages));
            
            // 清除之前的推理内容
            window.currentReasoning = '';
            
            // 保存上下文到全局变量，供sendMessage使用
            window.reaskContext = context;
            
            sendMessage();
        }
        
        // 清空全部对话
        function clearAllMessages() {
            if (confirm('确定要清空全部对话吗？')) {
                // 清空本地存储中的聊天记录
                localStorage.removeItem('aiPaletteChatHistory');
                // 清空页面内容并显示推荐
                restoreChatHistory();
            }
        }

        // 修改复制响应内容函数
        function copyResponse(button) {
            const aiMessage = button.closest('.flex.items-start');
            const responseElement = aiMessage.querySelector('pre');
            
            // 获取原始内容（markdown 格式）
            const originalContent = responseElement.dataset.originalContent || responseElement.textContent;
            
            // 复制到剪贴板
            navigator.clipboard.writeText(originalContent).then(() => {
                // 显示复制成功提示
                const originalTitle = button.title;
                button.title = '复制成功!';
                setTimeout(() => {
                    button.title = originalTitle;
                }, 1000);
            }).catch(err => {
                console.error('复制失败:', err);
                button.title = '复制失败';
            });
        }

        // 使用提示词并直接发送
        function usePromptAndSend(button) {
            document.getElementById('prompt').value = button.textContent.trim();
            // 隐藏建议框
            document.getElementById('suggestionBox').style.display = 'none';
            // 直接发送消息
            sendMessage();
        }

        // 修改添加AI消息的部分
        function addAIMessage(message) {
            const modelType = document.getElementById('modelType').value;
            const model = document.getElementById('model').value;
            const modelInfo = `${modelType.toUpperCase()} / ${model}`;
            
            const aiMessage = document.createElement('div');
            aiMessage.className = 'flex items-start space-x-3 mb-4';
            aiMessage.innerHTML = `
                <div class="w-8 h-8 rounded-full bg-purple-600 flex items-center justify-center flex-shrink-0 text-white">AI</div>
                <div class="flex-1 dark:bg-slate-800 bg-white rounded-lg p-4 dark:border-slate-700 border-slate-200 border">
                    <div class="text-xs dark:text-slate-400 text-slate-500 mb-2">${modelInfo}</div>
                    <div class="dark:text-slate-400 text-slate-500 text-sm mb-2" id="ai-reasoning-${Date.now()}"></div>
                    <pre class="dark:text-slate-200 text-slate-700 whitespace-pre-wrap" id="ai-response-${Date.now()}">...</pre>
                    <div class="flex justify-end space-x-2 mt-2 dark:text-slate-400 text-slate-500">
                        <button onclick="copyResponse(this)" class="p-1.5 dark:hover:bg-slate-700 hover:bg-slate-100 rounded-lg" title="复制内容">
                            <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                            </svg>
                        </button>
                        <button onclick="reaskQuestion(this)" class="p-1.5 dark:hover:bg-slate-700 hover:bg-slate-100 rounded-lg" title="重新发起对话">
                            <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                            </svg>
                        </button>
                        <button onclick="deleteMessage(this)" class="p-1.5 dark:hover:bg-slate-700 hover:bg-slate-100 rounded-lg" title="删除这一轮对话">
                            <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                        </button>
                    </div>
                </div>
            `;
            return aiMessage;
        }

        // 删除当前对话轮次
        function deleteMessage(button) {
            const aiMessage = button.closest('.flex.items-start');
            const userMessage = aiMessage.previousElementSibling;
            if (userMessage && userMessage.querySelector('.bg-blue-600')) {
                userMessage.remove();
            }
            aiMessage.remove();
            
            // 更新存储的聊天记录
            saveChatHistory();
            
            // 如果没有消息了，显示推荐
            const messageList = document.getElementById('messageList');
            if (messageList.children.length === 0) {
                restoreChatHistory();
            }
        }

        // 添加主题切换函数
        function toggleTheme(theme) {
            if (theme === 'dark') {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }
            updateThemeButtons(theme);
            
            // 保存主题设置
            const config = JSON.parse(localStorage.getItem('aiPaletteConfig') || '{}');
            config.theme = theme;
            localStorage.setItem('aiPaletteConfig', JSON.stringify(config));
        }

        // 更新主题按钮状态
        function updateThemeButtons(activeTheme) {
            const darkButton = document.querySelector('.dark-toggle');
            const lightButton = document.querySelector('.light-toggle');
            
            if (activeTheme === 'dark') {
                darkButton.classList.add('bg-blue-600', 'text-slate-50');
                darkButton.classList.remove('dark:text-slate-300', 'text-slate-500');
                lightButton.classList.remove('bg-blue-600', 'text-slate-50');
                lightButton.classList.add('dark:text-slate-300', 'text-slate-500');
            } else {
                lightButton.classList.add('bg-blue-600', 'text-slate-50');
                lightButton.classList.remove('dark:text-slate-300', 'text-slate-500');
                darkButton.classList.remove('bg-blue-600', 'text-slate-50');
                darkButton.classList.add('dark:text-slate-300', 'text-slate-500');
            }
        }

        // 修改保存聊天记录函数
        function saveChatHistory() {
            const messageList = document.getElementById('messageList');
            const messages = [];
            
            for (const message of messageList.children) {
                if (message.id === 'suggestionBox') continue;
                
                if (message.querySelector('.bg-blue-600')) { // 用户消息
                    const pElement = message.querySelector('p');
                    // 将 <br/> 转换回 \n
                    const content = pElement.innerHTML.replace(/<br\s*\/?>/g, '\n');
                    messages.push({
                        type: 'user',
                        content: content
                    });
                } else if (message.querySelector('.bg-purple-600')) { // AI 消息
                    const modelInfo = message.querySelector('.text-xs').textContent;
                    const responseElement = message.querySelector('pre');
                    const reasoningElement = message.querySelector('div[id^="ai-reasoning"]');
                    
                    const messageData = {
                        type: 'ai',
                        modelInfo: modelInfo,
                        content: responseElement.dataset.originalContent || responseElement.textContent
                    };

                    // 如果有推理内容，也保存
                    const reasoningContent = reasoningElement?.querySelector('.reasoning-content');
                    if (reasoningContent) {
                        const reasoningDiv = reasoningContent.querySelector('div');
                        messageData.reasoning = reasoningDiv.dataset.originalContent || reasoningDiv.textContent;
                        // 保存展开/折叠状态
                        messageData.reasoningExpanded = reasoningContent.style.height !== '0px' && reasoningContent.style.height !== '0';
                    }

                    messages.push(messageData);
                }
            }
            
            localStorage.setItem('aiPaletteChatHistory', JSON.stringify(messages));
        }

        // 添加恢复聊天记录的函数
        function restoreChatHistory() {
            const messageList = document.getElementById('messageList');
            const savedMessages = localStorage.getItem('aiPaletteChatHistory');
            
            if (!savedMessages) {
                // 如果没有聊天记录，确保显示建议框
                if (!document.getElementById('suggestionBox')) {
                    messageList.innerHTML = `
                        <div id="suggestionBox" class="mb-4">
                            <div class="flex flex-wrap gap-2 text-xs">
                                <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                                    帮我制定一份一周健康饮食计划
                                </button>
                                <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                                    如何缓解工作压力和情绪
                                </button>
                                <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                                    推荐一些室内植物养护小技巧
                                </button>
                                <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                                    分享一些提高睡眠质量的方法
                                </button>
                                <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                                    推荐几道简单美味的家常菜
                                </button>
                                <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                                    如何整理和收纳小户型空间
                                </button>
                                <button onclick="usePromptAndSend(this)" class="rounded-lg dark:bg-slate-800 bg-white px-3 py-1.5 dark:hover:bg-blue-600 hover:bg-blue-50 dark:hover:text-slate-200 hover:text-blue-600 dark:text-slate-300 text-slate-600 dark:border-slate-700 border-slate-200 border">
                                    分享一些省钱小妙招
                                </button>
                            </div>
                        </div>`;
                }
                return;
            }

            const messages = JSON.parse(savedMessages);
            messageList.innerHTML = ''; // 清空现有内容
            
            for (const message of messages) {
                if (message.type === 'user') {
                    const userMessage = document.createElement('div');
                    userMessage.className = 'flex items-start space-x-3 mb-4';
                    // 将原始内容中的 \n 转换为 <br/>
                    const displayContent = message.content.replace(/\n/g, '<br/>');
                    userMessage.innerHTML = `
                        <div class="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center flex-shrink-0 text-white">U</div>
                        <div class="flex-1 dark:bg-slate-800 bg-white rounded-lg p-4 dark:border-slate-700 border-slate-200 border">
                            <p class="dark:text-slate-200 text-slate-700" data-original-content="${escapeHtml(message.content)}">${displayContent}</p>
                        </div>
                    `;
                    messageList.appendChild(userMessage);
                } else if (message.type === 'ai') {
                    const aiMessage = document.createElement('div');
                    aiMessage.className = 'flex items-start space-x-3 mb-4';
                    
                    let reasoningHtml = '';
                    if (message.reasoning) {
                        const arrowRotation = message.reasoningExpanded ? 'rotate(90deg)' : 'rotate(0deg)';
                        const contentHeight = message.reasoningExpanded ? 'auto' : '0';
                        reasoningHtml = `
                            <div class="text-slate-400">
                                <div class="flex items-center cursor-pointer hover:text-slate-300 transition-colors duration-200" onclick="toggleReasoning(this)">
                                    <svg class="w-4 h-4 mr-1 reasoning-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" style="transform: ${arrowRotation}">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                                    </svg>
                                    思考过程
                                </div>
                                <div class="pl-5 mt-2 reasoning-content" style="height: ${contentHeight}; transition: height 0.3s">
                                    <div class="whitespace-pre-wrap text-slate-400" data-original-content="${escapeHtml(message.reasoning)}">${parseMarkdown(message.reasoning)}</div>
                                </div>
                            </div>`;
                    }

                    aiMessage.innerHTML = `
                        <div class="w-8 h-8 rounded-full bg-purple-600 flex items-center justify-center flex-shrink-0 text-white">AI</div>
                        <div class="flex-1 dark:bg-slate-800 bg-white rounded-lg p-4 dark:border-slate-700 border-slate-200 border">
                            <div class="text-xs dark:text-slate-400 text-slate-500 mb-2">${message.modelInfo}</div>
                            <div class="dark:text-slate-400 text-slate-500 text-sm mb-2" id="ai-reasoning-${Date.now()}">${reasoningHtml}</div>
                            <pre class="dark:text-slate-200 text-slate-700 whitespace-pre-wrap" data-original-content="${escapeHtml(message.content)}">${parseMarkdown(message.content)}</pre>
                            <div class="flex justify-end space-x-2 mt-2 dark:text-slate-400 text-slate-500">
                                <button onclick="copyResponse(this)" class="p-1.5 dark:hover:bg-slate-700 hover:bg-slate-100 rounded-lg" title="复制内容">
                                    <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                                    </svg>
                                </button>
                                <button onclick="reaskQuestion(this)" class="p-1.5 dark:hover:bg-slate-700 hover:bg-slate-100 rounded-lg" title="重新发起对话">
                                    <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                    </svg>
                                </button>
                                <button onclick="deleteMessage(this)" class="p-1.5 dark:hover:bg-slate-700 hover:bg-slate-100 rounded-lg" title="删除这一轮对话">
                                    <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                    `;
                    messageList.appendChild(aiMessage);
                }
            }
        }
    </script>
</body>
</html> 