document.addEventListener('DOMContentLoaded', function() {
    const chatBtn = document.getElementById('aiChatBtn');
    const chatWindow = document.getElementById('aiChatWindow');
    const closeBtn = document.querySelector('.ai-header .close-btn');
    const sendBtn = document.getElementById('aiSendBtn');
    const userInput = document.getElementById('aiUserInput');
    const messagesContainer = document.getElementById('aiMessages');

    // 切换窗口显示
    chatBtn.addEventListener('click', () => {
        chatWindow.classList.toggle('active');
        if(chatWindow.classList.contains('active')) {
            userInput.focus();
        }
    });

    closeBtn.addEventListener('click', () => {
        chatWindow.classList.remove('active');
    });

    // 发送消息逻辑
    async function sendMessage() {
        const text = userInput.value.trim();
        if (!text) return;

        // 1. 添加用户消息
        appendMessage('user', text);
        userInput.value = '';
        userInput.disabled = true;
        sendBtn.disabled = true;

        // 2. 创建AI消息占位符
        const thinkingDiv = appendMessage('thinking', 'DeepSeek 正在思考...');
        const answerDiv = appendMessage('ai', '');

        try {
            const response = await fetch('/api/plugins/ai/chat/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    // 如果views.py去掉了@csrf_exempt，这里需要加上 'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({ message: text })
            });

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let thinkingText = '';
            let answerText = '';

            // 3. 读取流式数据
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value, { stream: true });
                const lines = chunk.split('\n\n');

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        try {
                            const jsonStr = line.replace('data: ', '');
                            const data = JSON.parse(jsonStr);

                            if (data.type === 'thinking') {
                                thinkingText += data.content;
                                thinkingDiv.textContent = thinkingText; // 实时更新思考内容
                            } else if (data.type === 'answer') {
                                if (thinkingDiv.textContent === 'DeepSeek 正在思考...') {
                                    thinkingDiv.style.display = 'none'; // 如果没真的思考，就隐藏占位
                                }
                                answerText += data.content;
                                answerDiv.innerHTML = formatText(answerText); // 简单格式化
                                messagesContainer.scrollTop = messagesContainer.scrollHeight;
                            } else if (data.type === 'error') {
                                answerDiv.textContent = "Error: " + data.content;
                            }
                        } catch (e) {
                            console.error('JSON Parse error', e);
                        }
                    }
                }
            }
        } catch (error) {
            console.error('Fetch error:', error);
            appendMessage('ai', '抱歉，网络连接出现问题。');
        } finally {
            userInput.disabled = false;
            sendBtn.disabled = false;
            userInput.focus();
        }
    }

    sendBtn.addEventListener('click', sendMessage);
    userInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') sendMessage();
    });

    function appendMessage(type, content) {
        const div = document.createElement('div');
        div.className = `message ${type}`;
        div.textContent = content;
        messagesContainer.appendChild(div);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
        return div;
    }

    // 简单的换行转br处理，如果后续需要markdown支持可以引入marked.js
    function formatText(text) {
        return text.replace(/\n/g, '<br>');
    }
});