<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>对话测试</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        /* 使用 dvh (Dynamic Viewport Height) 解决移动端工具栏遮挡高度的问题 */
        :root { --app-height: 100dvh; }
        
        body { 
            background-color: #f5f5f5; 
            font-family: -apple-system, system-ui, sans-serif; 
            height: var(--app-height);
            display: flex;
            flex-direction: column;
            overflow: hidden; 
        }
        
        /* 气泡尖角 */
        .bubble-left::before {
            content: ""; position: absolute; width: 0; height: 0;
            border-top: 5px solid transparent; border-bottom: 5px solid transparent;
            border-right: 7px solid white; left: -7px; top: 12px;
        }
        .bubble-right::after {
            content: ""; position: absolute; width: 0; height: 0;
            border-top: 5px solid transparent; border-bottom: 5px solid transparent;
            border-left: 8px solid #95ec69; right: -8px; top: 12px;
        }

        /* 隐藏滚动条但保持滚动 */
        .chat-scroll {
            flex: 1;
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
            scrollbar-width: none;
        }
        .chat-scroll::-webkit-scrollbar { display: none; }

        /* Markdown 内容样式 */
        .prose-chat { font-size: 16px; color: #191919; line-height: 1.6; word-break: break-word; }
        .prose-chat p { margin-bottom: 0.5rem; }
        .prose-chat p:last-child { margin-bottom: 0; }
        .prose-chat pre { background: #f8f8f8; padding: 10px; border-radius: 6px; overflow-x: auto; margin: 8px 0; font-size: 13px; }
        .prose-chat code { font-family: 'JetBrains Mono', monospace; background: rgba(0,0,0,0.05); padding: 2px 4px; border-radius: 3px; }

        /* 动画 */
        .msg-fade { animation: fadeIn 0.3s ease-out forwards; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
    </style>
</head>
<body x-data="weChat()">

    <header class="h-14 bg-[#ededed] border-b border-[#dbdbdb] flex items-center px-4 shrink-0 z-20">
        <div class="flex-1 flex items-center">
            <svg @click="window.history.back()" class="w-6 h-6 text-[#191919] cursor-pointer" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M15 19l-7-7 7-7" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"></path></svg>
            <span class="ml-2 text-[17px] font-bold text-[#191919]">对话测试</span>
        </div>
        <div class="flex items-center space-x-3">
            <a href="/pb/manage" class="text-[13px] font-semibold text-[#576b95] hover:text-[#3e5175] transition-colors">返回首页</a>
            <svg class="w-6 h-6 text-[#191919]" fill="currentColor" viewBox="0 0 24 24"><path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"></path></svg>
        </div>
    </header>

    <main id="chat-container" class="chat-scroll p-4 space-y-6 bg-[#f5f5f5]">
        <div class="text-center py-2">
            <span class="bg-[#dadada]/60 text-white text-[11px] px-2 py-0.5 rounded-sm" x-text="chatTime"></span>
        </div>

        <template x-for="(msg, index) in messages" :key="index">
            <div :class="msg.role === 'user' ? 'flex flex-row-reverse' : 'flex flex-row'" class="msg-fade">
                <div class="w-11 h-11 rounded-md shrink-0 overflow-hidden shadow-sm" :class="msg.role === 'user' ? 'ml-3' : 'mr-3'">
                    <img :src="msg.role === 'user' ? '/assets/images/user-avatar.svg?v=1' : '/assets/images/ai-avatar.svg?v=1'" 
                         class="w-full h-full bg-[#F3E5F5] object-cover"
                         @error="$el.src='https://api.dicebear.com/7.x/avataaars/svg?seed=Felix'">
                </div>

                <div class="relative max-w-[80%] px-3 py-2.5 rounded-md shadow-sm border border-black/[0.02]" 
                     :class="msg.role === 'user' ? 'bg-[#95ec69] bubble-right' : 'bg-white bubble-left'">
                    <div class="prose-chat" x-html="renderContent(msg.content)"></div>
                </div>
            </div>
        </template>

        <div x-show="isTyping" class="flex flex-row msg-fade">
            <div class="w-11 h-11 bg-white rounded-md mr-3 flex items-center justify-center text-slate-200">AI</div>
            <div class="bg-white bubble-left px-4 py-3 rounded-md shadow-sm flex items-center space-x-1.5">
                <div class="w-1.5 h-1.5 bg-slate-400 rounded-full animate-bounce"></div>
                <div class="w-1.5 h-1.5 bg-slate-400 rounded-full animate-bounce [animation-delay:0.2s]"></div>
                <div class="w-1.5 h-1.5 bg-slate-400 rounded-full animate-bounce [animation-delay:0.4s]"></div>
            </div>
        </div>
    </main>

    <footer class="bg-[#f7f7f7] border-t border-[#dbdbdb] px-4 pt-3 shrink-0" 
            style="padding-bottom: calc(env(safe-area-inset-bottom) + 15px); min-height: 85px;">
        <div class="flex items-end space-x-3">
            <textarea 
                x-model="inputMsg" 
                @input="autoResize($el)"
                @keydown.enter.prevent="sendMessage()"
                class="flex-1 bg-white border border-[#e2e2e2] rounded-lg px-4 py-2.5 text-[16px] leading-snug outline-none resize-none max-h-32 min-h-[44px] focus:ring-0 shadow-inner" 
                rows="1"
                placeholder="请输入消息..."></textarea>
            
            <button 
                @click="sendMessage()"
                :disabled="!inputMsg.trim() || isTyping"
                class="mb-1 px-5 py-2 rounded-lg font-bold text-[15px] transition-all transform active:scale-95"
                :class="inputMsg.trim() ? 'bg-[#07c160] text-white' : 'bg-[#e1e1e1] text-[#b2b2b2]'"
                x-text="isTyping ? '...' : '发送'">
            </button>
        </div>
    </footer>

    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('weChat', () => ({
                messages: [
                    { role: 'ai', content: '您好！我是您的专属助理小宝。有什么可以帮到您？' }
                ],
                inputMsg: '',
                isTyping: false,
                chatTime: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),

                autoResize(el) {
                    el.style.height = '44px';
                    el.style.height = el.scrollHeight + 'px';
                },

                renderContent(raw) {
                    if (!raw) return '';
                    // 过滤思考过程
                    let cleanText = raw.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
                    // 过滤多余的推理前缀逻辑
                    const filtered = cleanText.replace(/^用户(再次)?要求我[\s\S]*?。/g, '').trim();
                    return marked.parse(filtered.length > 2 ? filtered : cleanText);
                },

                scrollToBottom() {
                    setTimeout(() => {
                        const container = document.getElementById('chat-container');
                        container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });
                    }, 100);
                },

                async sendMessage() {
                    const msg = this.inputMsg.trim();
                    if (!msg || this.isTyping) return;

                    // 用户消息上屏
                    this.messages.push({ role: 'user', content: msg });
                    this.inputMsg = '';
                    const ta = document.querySelector('textarea');
                    if(ta) ta.style.height = '44px';
                    
                    this.isTyping = true;
                    this.scrollToBottom();

                    try {
                        const res = await fetch('/pb/pb-api-v1/chat/send', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ message: msg })
                        });
                        const json = await res.json();
                        
                        if (json.code === 200) {
                            const fullReply = json.reply || "";
                            const targetIndex = this.messages.length;
                            // 预留 AI 气泡位置
                            this.messages.push({ role: 'ai', content: '' });

                            // 模拟前端打字机效果
                            let i = 0;
                            const timer = setInterval(() => {
                                if (i < fullReply.length) {
                                    this.messages[targetIndex].content += fullReply.charAt(i);
                                    i++;
                                    this.scrollToBottom();
                                } else {
                                    clearInterval(timer);
                                }
                            }, 25);

                        } else {
                            this.messages.push({ role: 'ai', content: '⚠️ 抱歉，我刚才走神了，请重试。' });
                        }
                    } catch (e) {
                        this.messages.push({ role: 'ai', content: '❌ 信号似乎不太好，请稍后再试。' });
                    } finally {
                        this.isTyping = false;
                        this.scrollToBottom();
                    }
                }
            }));
        });
    </script>
</body>
</html>