let messageHistory = []; // Store messages for reference
        let isPromptPanelOpen = false;

        async function resetChat() {
            if (!confirm('B?n c� ch?c mu?n l�m m?i cu?c tr� chuy?n? L?ch s? cu s? du?c luu tr?.')) return;

            const deviceId = document.getElementById('deviceId').value;
            if (!deviceId) return alert("Missing Device ID");

            try {
                const response = await fetch('/api/history/archive', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'device_id': deviceId
                    },
                    body: JSON.stringify({})
                });

                const data = await response.json();

                if (response.ok && data.status === 'success') {
                    document.getElementById('messagesArea').innerHTML = '';
                    const remaining = data.remaining_resets !== undefined ? ` (C�n ${data.remaining_resets} lu?t)` : '';
                    alert('? ' + (data.message || 'Reset th�nh c�ng!') + remaining);
                } else {
                    const errorMsg = data.message || data.detail || 'Kh�ng th? reset';
                    const prefix = data.error_code === 'RESET_LIMIT_EXCEEDED' ? '?? ' : '? L?i: ';
                    alert(prefix + errorMsg);
                }
            } catch (error) {
                console.error('Reset error:', error);
                alert('C� l?i x?y ra khi reset.');
            }
        }

        function togglePromptEditor() {
            const panel = document.getElementById('promptPanel');
            isPromptPanelOpen = !isPromptPanelOpen;

            if (isPromptPanelOpen) {
                panel.classList.add('open');
                loadSystemPrompt();
            } else {
                panel.classList.remove('open');
            }
        }

        async function loadSystemPrompt() {
            const textarea = document.getElementById('systemPromptInput');
            textarea.value = "Loading...";
            textarea.disabled = true;

            try {
                const response = await fetch('/api/agent/system-prompt');
                const data = await response.json();

                if (data.status === 'success') {
                    textarea.value = data.content;
                } else {
                    textarea.value = "Error loading prompt: " + data.message;
                }
            } catch (error) {
                textarea.value = "Error connecting to server.";
                console.error(error);
            } finally {
                textarea.disabled = false;
            }
        }

        async function saveSystemPrompt() {
            const content = document.getElementById('systemPromptInput').value;
            const statusLabel = document.getElementById('promptStatus');
            if (!content) return;

            if (!confirm('B?n c� ch?c mu?n luu Prompt m?i? Bot s? b? reset graph d? h?c prompt m?i n�y.')) {
                return;
            }

            statusLabel.innerText = "Saving...";

            try {
                const response = await fetch('/api/agent/system-prompt', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ content: content })
                });
                const data = await response.json();

                if (data.status === 'success') {
                    statusLabel.innerText = "Saved!";
                    alert('? �� luu Prompt th�nh c�ng!\nBot d� s?n s�ng v?i prompt m?i.');
                } else {
                    statusLabel.innerText = "Error!";
                    alert('? L?i: ' + data.detail);
                }
            } catch (error) {
                statusLabel.innerText = "Connection Error";
                alert('? L?i k?t n?i server');
                console.error(error);
            }
        }

        function toggleMessageView(messageId) {
            const filteredContent = document.getElementById('filtered-' + messageId);
            const rawContent = document.getElementById('raw-' + messageId);
            const filteredBtn = document.getElementById('filtered-btn-' + messageId);
            const rawBtn = document.getElementById('raw-btn-' + messageId);

            if (filteredContent.style.display === 'none') {
                // Switch to filtered
                filteredContent.style.display = 'block';
                rawContent.style.display = 'none';
                filteredBtn.classList.add('active');
                rawBtn.classList.remove('active');
            } else {
                // Switch to raw
                filteredContent.style.display = 'none';
                rawContent.style.display = 'block';
                rawBtn.classList.add('active');
                filteredBtn.classList.remove('active');
            }
        }
        let currentCursor = null;
        let isTyping = false;

        async function loadHistory(isRefresh) {
            const deviceId = document.getElementById('deviceId').value;
            const accessToken = document.getElementById('accessToken').value.trim();
            const messagesArea = document.getElementById('messagesArea');
            const loadMoreBtn = document.getElementById('loadMoreBtn');

            if (!deviceId) {
                alert('Please enter a Device ID');
                return;
            }

            if (isRefresh) {
                messagesArea.innerHTML = '';
                currentCursor = null;
            }

            // G?i API v?i device_id trong URL, nhung g?i k�m headers d? middleware resolve d�ng identity
            const url = `/api/history/${deviceId}?limit=20${currentCursor ? `&before_id=${currentCursor}` : ''}`;

            // Build headers for identity resolution (middleware s? d�ng token d? override n?u c�)
            const headers = {
                'Content-Type': 'application/json',
                'device_id': deviceId
            };
            if (accessToken) {
                headers['Authorization'] = 'Bearer ' + accessToken;
            }

            try {
                const response = await fetch(url, { headers: headers });
                const data = await response.json();

                const messages = data.data || data;
                const cursor = data.next_cursor || null;

                if (Array.isArray(messages) && messages.length > 0) {
                    currentCursor = cursor;

                    if (isRefresh) {
                        // Refresh: reverse d? oldest ? tr�n, newest ? du?i
                        const batch = [...messages].reverse();
                        batch.forEach(msg => appendMessage(msg, 'bottom'));
                        setTimeout(() => {
                            const chatBox = document.getElementById('chatBox');
                            chatBox.scrollTop = chatBox.scrollHeight;
                        }, 100);
                    } else {
                        // Load more: messages t? API theo DESC (newest first c?a batch cu)
                        const chatBox = document.getElementById('chatBox');
                        const oldHeight = chatBox.scrollHeight;

                        for (let i = 0; i < messages.length; i++) {
                            appendMessage(messages[i], 'top');
                        }

                        // Adjust scroll to keep view stable
                        chatBox.scrollTop = chatBox.scrollHeight - oldHeight;
                    }

                    loadMoreBtn.style.display = currentCursor ? 'block' : 'none';
                } else {
                    if (isRefresh) {
                        messagesArea.innerHTML = '<div class="message system">No history found. Start chatting!</div>';
                    }
                    loadMoreBtn.style.display = 'none';
                }

            } catch (error) {
                console.error('Error loading history:', error);
                alert('Failed to load history');
            }
        }

        function appendMessage(msg, position = 'bottom') {
            const messagesArea = document.getElementById('messagesArea');

            // Container wrapper for alignment
            const container = document.createElement('div');
            container.className = `message-container ${msg.is_human ? 'user' : 'bot'}`;

            // Sender Name Label
            const sender = document.createElement('div');
            sender.className = 'sender-name';
            sender.innerText = msg.is_human ? 'You' : 'Canifa AI';
            container.appendChild(sender);

            // Message Bubble
            const div = document.createElement('div');
            div.className = `message ${msg.is_human ? 'user' : 'bot'}`;

            // Generate unique message ID for toggle
            const messageId = 'hist-' + (msg.id || Date.now() + Math.random());

            if (msg.is_human) {
                // User message: simple text
                div.innerText = msg.message;
            } else {
                // Bot message: add Widget/Raw JSON toggle

                // FILTERED CONTENT (default visible)
                const filteredDiv = document.createElement('div');
                filteredDiv.id = 'filtered-' + messageId;
                filteredDiv.className = 'filtered-content';
                filteredDiv.innerText = msg.message;
                div.appendChild(filteredDiv);

                // RAW CONTENT (hidden by default)
                const rawDiv = document.createElement('div');
                rawDiv.id = 'raw-' + messageId;
                rawDiv.className = 'raw-content';
                rawDiv.style.display = 'none';

                const rawJsonDiv = document.createElement('div');
                rawJsonDiv.className = 'raw-json-view';
                const pre = document.createElement('pre');
                pre.textContent = JSON.stringify({
                    id: msg.id,
                    message: msg.message,
                    product_ids: msg.product_ids || [],
                    timestamp: msg.timestamp,
                    is_human: msg.is_human
                }, null, 2);
                rawJsonDiv.appendChild(pre);
                rawDiv.appendChild(rawJsonDiv);
                div.appendChild(rawDiv);

                // Toggle Buttons
                const toggleDiv = document.createElement('div');
                toggleDiv.className = 'message-view-toggle';

                const filteredBtn = document.createElement('button');
                filteredBtn.id = 'filtered-btn-' + messageId;
                filteredBtn.className = 'active';
                filteredBtn.innerText = '?? Widget';
                filteredBtn.onclick = () => toggleMessageView(messageId);

                const rawBtn = document.createElement('button');
                rawBtn.id = 'raw-btn-' + messageId;
                rawBtn.innerText = '??? Raw JSON';
                rawBtn.onclick = () => toggleMessageView(messageId);

                toggleDiv.appendChild(filteredBtn);
                toggleDiv.appendChild(rawBtn);
                div.appendChild(toggleDiv);
            }

            // Timestamp inside bubble
            const time = document.createElement('span');
            time.className = 'timestamp';
            time.innerText = new Date(msg.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
            div.appendChild(time);

            container.appendChild(div);

            if (position === 'top') {
                messagesArea.insertBefore(container, messagesArea.firstChild);
            } else {
                messagesArea.appendChild(container);
            }
        }

        async function sendMessage() {
            const input = document.getElementById('userInput');
            const deviceIdInput = document.getElementById('deviceId');
            const accessTokenInput = document.getElementById('accessToken');
            const deviceId = deviceIdInput.value.trim();
            const accessToken = accessTokenInput.value.trim();
            const text = input.value.trim();
            const sendBtn = document.getElementById('sendBtn');
            const typingIndicator = document.getElementById('typingIndicator');
            const chatBox = document.getElementById('chatBox');

            if (!deviceId) {
                alert('Please enter a Device ID first!');
                deviceIdInput.focus();
                return;
            }

            if (!text) return;

            // Disable input
            input.disabled = true;
            sendBtn.disabled = true;
            typingIndicator.style.display = 'block';

            // Add user message immediately
            appendMessage({
                message: text,
                is_human: true,
                timestamp: new Date().toISOString(),
                id: 'pending'
            });
            input.value = '';
            chatBox.scrollTop = chatBox.scrollHeight;

            // Save config to localStorage
            saveConfig();

            // Track response time
            const startTime = Date.now();

            try {
                // Build headers
                const headers = {
                    'Content-Type': 'application/json',
                    'device_id': deviceId
                };

                // Add Authorization if access token provided
                if (accessToken) {
                    headers['Authorization'] = 'Bearer ' + accessToken;
                }

                const response = await fetch('/api/agent/chat', {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify({
                        user_query: text,
                        device_id: deviceId
                    })
                });

                // Handle API Errors (Rate Limit, System Error) with Widget/Raw View
                if (response.status === 429 || response.status === 500) {
                    const errorData = await response.json();
                    const responseTime = ((Date.now() - startTime) / 1000).toFixed(2);
                    const messageId = 'msg-error-' + Date.now();

                    // Create bot message container
                    const messagesArea = document.getElementById('messagesArea');
                    const container = document.createElement('div');
                    container.className = 'message-container bot';

                    const sender = document.createElement('div');
                    sender.className = 'sender-name';
                    sender.innerText = 'Canifa AI';
                    container.appendChild(sender);

                    const botMsgDiv = document.createElement('div');
                    botMsgDiv.className = 'message bot';

                    // 1. FILTERED CONTENT (Widget View)
                    const filteredDiv = document.createElement('div');
                    filteredDiv.id = 'filtered-' + messageId;
                    filteredDiv.className = 'filtered-content';
                    filteredDiv.style.color = '#ff6b6b';

                    // Extract message
                    const errorMessage = errorData.message ||
                        errorData.detail?.message ||
                        'C� l?i x?y ra!';

                    filteredDiv.innerHTML = `
                            <div style="font-weight: bold; margin-bottom: 8px;">?? ${errorData.error_code || 'ERROR'}</div>
                            <div>${errorMessage}</div>
                            ${errorData.require_login ? '<div style="margin-top: 10px; padding: 8px; background: #3d2d2d; border-radius: 6px;">?? �ang nh?p ngay d? ti?p t?c!</div>' : ''}
                        `;
                    botMsgDiv.appendChild(filteredDiv);

                    // 2. RAW CONTENT (JSON View)
                    const rawDiv = document.createElement('div');
                    rawDiv.id = 'raw-' + messageId;
                    rawDiv.className = 'raw-content';
                    rawDiv.style.display = 'none';

                    const rawJsonDiv = document.createElement('div');
                    rawJsonDiv.className = 'raw-json-view';
                    const pre = document.createElement('pre');
                    pre.textContent = JSON.stringify(errorData, null, 2);
                    rawJsonDiv.appendChild(pre);
                    rawDiv.appendChild(rawJsonDiv);
                    botMsgDiv.appendChild(rawDiv);

                    // 3. Toggle Buttons
                    const toggleDiv = document.createElement('div');
                    toggleDiv.className = 'message-view-toggle';

                    const filteredBtn = document.createElement('button');
                    filteredBtn.id = 'filtered-btn-' + messageId;
                    filteredBtn.className = 'active';
                    filteredBtn.innerText = '?? Widget';
                    filteredBtn.onclick = () => toggleMessageView(messageId);

                    const rawBtn = document.createElement('button');
                    rawBtn.id = 'raw-btn-' + messageId;
                    rawBtn.innerText = '??? Raw JSON';
                    rawBtn.onclick = () => toggleMessageView(messageId);

                    toggleDiv.appendChild(filteredBtn);
                    toggleDiv.appendChild(rawBtn);
                    botMsgDiv.appendChild(toggleDiv);

                    // Response time
                    const timeDiv = document.createElement('div');
                    timeDiv.className = 'response-time';
                    timeDiv.innerText = `?? ${responseTime}s`;
                    botMsgDiv.appendChild(timeDiv);

                    container.appendChild(botMsgDiv);
                    messagesArea.appendChild(container);
                    chatBox.scrollTop = chatBox.scrollHeight;

                    input.disabled = false;
                    sendBtn.disabled = false;
                    typingIndicator.style.display = 'none';
                    return;
                }

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.detail?.message || errorData.detail || 'C� l?i x?y ra');
                }

                const data = await response.json();
                const responseTime = ((Date.now() - startTime) / 1000).toFixed(2);

                // Generate unique message ID
                const messageId = 'msg-' + Date.now();

                // Store message data
                messageHistory.push({
                    type: 'bot',
                    data: data,
                    responseTime: responseTime,
                    timestamp: new Date().toISOString(),
                    id: messageId
                });

                // Create bot message placeholder
                const messagesArea = document.getElementById('messagesArea');

                const container = document.createElement('div');
                container.className = 'message-container bot';

                const sender = document.createElement('div');
                sender.className = 'sender-name';
                sender.innerText = 'Canifa AI';
                container.appendChild(sender);

                const botMsgDiv = document.createElement('div');
                botMsgDiv.className = 'message bot';

                if (data.status === 'success') {
                    // FILTERED CONTENT (default visible)
                    const filteredDiv = document.createElement('div');
                    filteredDiv.id = 'filtered-' + messageId;
                    filteredDiv.className = 'filtered-content';

                    // Display AI text response
                    const textDiv = document.createElement('div');
                    textDiv.innerText = data.ai_response || 'No response';
                    filteredDiv.appendChild(textDiv);

                    // Render product cards if available
                    if (data.product_ids && data.product_ids.length > 0) {
                        const productsContainer = document.createElement('div');
                        productsContainer.className = 'product-cards-container';

                        data.product_ids.forEach(product => {
                            const card = document.createElement('div');
                            card.className = 'product-card';

                            // Product image
                            const img = document.createElement('img');
                            img.src = product.thumbnail_image_url || 'https://via.placeholder.com/200';
                            img.alt = product.name;
                            img.onerror = function () { this.src = 'https://via.placeholder.com/200?text=No+Image'; };
                            card.appendChild(img);

                            // Product body
                            const body = document.createElement('div');
                            body.className = 'product-card-body';

                            // SKU
                            const sku = document.createElement('div');
                            sku.className = 'product-sku';
                            sku.innerText = product.sku;
                            body.appendChild(sku);

                            // Name
                            const name = document.createElement('div');
                            name.className = 'product-name';
                            name.innerText = product.name;
                            body.appendChild(name);

                            // Price
                            const priceDiv = document.createElement('div');
                            priceDiv.className = 'product-price';

                            if (product.sale_price && product.sale_price < product.price) {
                                // Show original price with strikethrough
                                const originalPrice = document.createElement('span');
                                originalPrice.className = 'price-original';
                                originalPrice.innerText = product.price.toLocaleString('vi-VN') + 'd';
                                priceDiv.appendChild(originalPrice);

                                // Show sale price
                                const salePrice = document.createElement('span');
                                salePrice.className = 'price-sale';
                                salePrice.innerText = product.sale_price.toLocaleString('vi-VN') + 'd';
                                priceDiv.appendChild(salePrice);
                            } else {
                                // Show regular price
                                const regularPrice = document.createElement('span');
                                regularPrice.className = 'price-regular';
                                regularPrice.innerText = product.price.toLocaleString('vi-VN') + 'd';
                                priceDiv.appendChild(regularPrice);
                            }
                            body.appendChild(priceDiv);

                            // Link button
                            const link = document.createElement('a');
                            link.className = 'product-link';
                            link.href = product.url;
                            link.target = '_blank';
                            link.innerText = '??? Xem chi ti?t';
                            body.appendChild(link);

                            card.appendChild(body);
                            productsContainer.appendChild(card);
                        });

                        filteredDiv.appendChild(productsContainer);
                    }

                    botMsgDiv.appendChild(filteredDiv);

                    // RAW CONTENT (hidden by default)
                    const rawDiv = document.createElement('div');
                    rawDiv.id = 'raw-' + messageId;
                    rawDiv.className = 'raw-content';
                    rawDiv.style.display = 'none';

                    const rawJsonDiv = document.createElement('div');
                    rawJsonDiv.className = 'raw-json-view';
                    const pre = document.createElement('pre');
                    pre.textContent = JSON.stringify({
                        status: data.status,
                        ai_response: data.ai_response,
                        product_ids: data.product_ids,
                        limit_info: data.limit_info || null
                    }, null, 2);
                    rawJsonDiv.appendChild(pre);
                    rawDiv.appendChild(rawJsonDiv);
                    botMsgDiv.appendChild(rawDiv);

                    // Add toggle button
                    const toggleDiv = document.createElement('div');
                    toggleDiv.className = 'message-view-toggle';

                    const filteredBtn = document.createElement('button');
                    filteredBtn.id = 'filtered-btn-' + messageId;
                    filteredBtn.className = 'active';
                    filteredBtn.innerText = '?? Widget';
                    filteredBtn.onclick = () => toggleMessageView(messageId);

                    const rawBtn = document.createElement('button');
                    rawBtn.id = 'raw-btn-' + messageId;
                    rawBtn.innerText = '??? Raw JSON';
                    rawBtn.onclick = () => toggleMessageView(messageId);

                    toggleDiv.appendChild(filteredBtn);
                    toggleDiv.appendChild(rawBtn);
                    botMsgDiv.appendChild(toggleDiv);

                    // Add response time
                    const timeDiv = document.createElement('div');
                    timeDiv.className = 'response-time';
                    timeDiv.innerText = `?? ${responseTime}s`;
                    botMsgDiv.appendChild(timeDiv);
                } else {
                    // ERROR CASE: Limit exceeded or other errors

                    // FILTERED CONTENT (error message - default visible)
                    const filteredDiv = document.createElement('div');
                    filteredDiv.id = 'filtered-' + messageId;
                    filteredDiv.className = 'filtered-content';
                    filteredDiv.style.color = '#ff6b6b';
                    filteredDiv.innerHTML = `
                            <div style="font-weight: bold; margin-bottom: 8px;">?? ${data.error_code || 'ERROR'}</div>
                            <div>${data.message || 'Unknown error'}</div>
                            ${data.require_login ? '<div style="margin-top: 10px; padding: 8px; background: #3d2d2d; border-radius: 6px;">?? Vui l�ng dang nh?p d? ti?p t?c s? d?ng!</div>' : ''}
                        `;
                    botMsgDiv.appendChild(filteredDiv);

                    // RAW CONTENT (hidden by default)
                    const rawDiv = document.createElement('div');
                    rawDiv.id = 'raw-' + messageId;
                    rawDiv.className = 'raw-content';
                    rawDiv.style.display = 'none';

                    const rawJsonDiv = document.createElement('div');
                    rawJsonDiv.className = 'raw-json-view';
                    const pre = document.createElement('pre');
                    pre.textContent = JSON.stringify({
                        status: data.status,
                        error_code: data.error_code,
                        message: data.message,
                        require_login: data.require_login,
                        limit_info: data.limit_info || null
                    }, null, 2);
                    rawJsonDiv.appendChild(pre);
                    rawDiv.appendChild(rawJsonDiv);
                    botMsgDiv.appendChild(rawDiv);

                    // Toggle Buttons
                    const toggleDiv = document.createElement('div');
                    toggleDiv.className = 'message-view-toggle';

                    const filteredBtn = document.createElement('button');
                    filteredBtn.id = 'filtered-btn-' + messageId;
                    filteredBtn.className = 'active';
                    filteredBtn.innerText = '?? Widget';
                    filteredBtn.onclick = () => toggleMessageView(messageId);

                    const rawBtn = document.createElement('button');
                    rawBtn.id = 'raw-btn-' + messageId;
                    rawBtn.innerText = '??? Raw JSON';
                    rawBtn.onclick = () => toggleMessageView(messageId);

                    toggleDiv.appendChild(filteredBtn);
                    toggleDiv.appendChild(rawBtn);
                    botMsgDiv.appendChild(toggleDiv);
                }

                container.appendChild(botMsgDiv);
                messagesArea.appendChild(container);
                chatBox.scrollTop = chatBox.scrollHeight;

            } catch (error) {
                console.error('Error sending message:', error);
                appendMessage({
                    message: `Error: ${error.message}`,
                    is_human: false,
                    timestamp: new Date().toISOString(),
                    id: 'error'
                });
            } finally {
                input.disabled = false;
                sendBtn.disabled = false;
                typingIndicator.style.display = 'none';
                input.focus();
                chatBox.scrollTop = chatBox.scrollHeight;
            }
        }

        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }

        function clearUI() {
            document.getElementById('messagesArea').innerHTML = '';
        }

        // Apply token from login prompt in rate limit error
        function applyLoginToken() {
            const tokenInput = document.getElementById('loginTokenInput');
            if (tokenInput && tokenInput.value.trim()) {
                document.getElementById('accessToken').value = tokenInput.value.trim();
                saveConfig();
                alert('? Token d� du?c luu! B?n c� th? ti?p t?c chat.');
            } else {
                alert('Vui l�ng nh?p Access Token!');
            }
        }

        // Save config to localStorage (called on input change/blur)
        function saveConfig() {
            const deviceId = document.getElementById('deviceId').value.trim();
            const accessToken = document.getElementById('accessToken').value.trim();

            if (deviceId) {
                localStorage.setItem('canifa_device_id', deviceId);
            }
            if (accessToken) {
                localStorage.setItem('canifa_access_token', accessToken);
            } else {
                localStorage.removeItem('canifa_access_token');
            }
        }

        // Generate UUID for device_id
        function generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                const r = Math.random() * 16 | 0;
                const v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }

        // Load config from localStorage on page load
        window.onload = function () {
            // Load or generate Device ID
            let savedDeviceId = localStorage.getItem('canifa_device_id');
            if (!savedDeviceId) {
                savedDeviceId = 'device-' + generateUUID().substring(0, 8);
                localStorage.setItem('canifa_device_id', savedDeviceId);
            }
            document.getElementById('deviceId').value = savedDeviceId;

            // Load Access Token (optional)
            const savedAccessToken = localStorage.getItem('canifa_access_token');
            if (savedAccessToken) {
                document.getElementById('accessToken').value = savedAccessToken;
            }

            // Auto-load history
            setTimeout(() => loadHistory(true), 50);
        };