const API = '/api/v2/chat';
        let lastResult = null;
        let currentTab = 'sql';

        async function send() {
            const input = document.getElementById('input');
            const q = input.value.trim();
            if (!q) return;
            input.value = '';
            ask(q);
        }

        async function ask(q) {
            const msgs = document.getElementById('messages');
            const btn = document.getElementById('sendBtn');

            // Clear hint
            const hint = msgs.querySelector('.empty-hint');
            if (hint) hint.remove();

            // User message
            msgs.innerHTML += `<div class="msg msg-user"><div class="msg-label">Bạn</div><div class="msg-bubble">${esc(q)}</div></div>`;

            // Loading
            const loadId = 'load-' + Date.now();
            msgs.innerHTML += `<div class="msg msg-bot" id="${loadId}"><div class="msg-label">AI Stylist</div><div class="msg-bubble"><span class="loading-dots">Đang query DB</span></div></div>`;
            msgs.scrollTop = msgs.scrollHeight;
            btn.disabled = true;

            try {
                const res = await fetch(API, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ user_query: q })
                });
                const data = await res.json();
                lastResult = data;

                // Replace loading with response
                const loadEl = document.getElementById(loadId);
                if (loadEl) {
                    loadEl.querySelector('.msg-bubble').innerHTML = formatResponse(data.ai_response || 'Không có phản hồi');
                }

                // Update side panel
                renderSidePanel();
            } catch (e) {
                const loadEl = document.getElementById(loadId);
                if (loadEl) {
                    loadEl.querySelector('.msg-bubble').textContent = '❌ Lỗi: ' + e.message;
                }
            }

            btn.disabled = false;
            msgs.scrollTop = msgs.scrollHeight;
        }

        function formatResponse(text) {
            // Basic markdown: **bold**, ~~strike~~, \n
            return text
                .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
                .replace(/~~(.+?)~~/g, '<del style="color:#64748b">$1</del>')
                .replace(/\[([A-Z0-9]+)\]/g, '<code style="color:#38bdf8;background:#1e293b;padding:2px 6px;border-radius:4px">$1</code>')
                .replace(/\n/g, '<br>');
        }

        function switchTab(tab) {
            currentTab = tab;
            document.querySelectorAll('.side-tab').forEach(t => t.classList.remove('active'));
            document.querySelector(`.side-tab:nth-child(${tab === 'sql' ? 1 : tab === 'products' ? 2 : 3})`).classList.add('active');
            renderSidePanel();
        }

        function renderSidePanel() {
            const el = document.getElementById('sideContent');
            if (!lastResult) {
                el.innerHTML = '<div class="empty-hint"><div class="icon">📊</div><p>Chưa có kết quả</p></div>';
                return;
            }
            const d = lastResult;

            if (currentTab === 'sql') {
                el.innerHTML = `
      <h3 style="color:#38bdf8;font-size:0.9em;margin-bottom:8px;">Generated SQL</h3>
      <div class="sql-box">${esc(d.sql || 'N/A')}</div>
      <p style="font-size:0.8em;color:#64748b">${d.product_count || 0} sản phẩm từ DB</p>
    `;
            } else if (currentTab === 'products') {
                const products = d.products || [];
                if (!products.length) {
                    el.innerHTML = '<div class="empty-hint"><div class="icon">📭</div><p>Không có sản phẩm</p></div>';
                    return;
                }
                el.innerHTML = products.map(p => `
      <div class="product-mini">
        ${p.product_image_url_thumbnail ? `<img src="${p.product_image_url_thumbnail}" onerror="this.style.display='none'">` : ''}
        <div class="info">
          <div class="name">${esc(p.product_name || '?')}</div>
          <div class="code">${esc(p.magento_ref_code || '?')} • ${esc(p.master_color || '?')}</div>
          <div class="price">${Number(p.sale_price || 0).toLocaleString()}đ ${p.original_price > p.sale_price ? `<del style="color:#64748b;font-weight:normal;font-size:0.85em">${Number(p.original_price).toLocaleString()}đ</del>` : ''}</div>
        </div>
      </div>
    `).join('');
            } else if (currentTab === 'timing') {
                const t = d.timing || {};
                el.innerHTML = `
      <div class="timing-grid">
        <div class="timing-card"><div class="label">Embedding</div><div class="value">${t.embedding_ms || 0}ms</div></div>
        <div class="timing-card"><div class="label">DB Search</div><div class="value">${t.db_search_ms || 0}ms</div></div>
        <div class="timing-card"><div class="label">Response Gen</div><div class="value">${t.response_generation_ms || 0}ms</div></div>
        <div class="timing-card"><div class="label">Total</div><div class="value" style="color:#22c55e">${t.total_ms || 0}ms</div></div>
      </div>
      <p style="font-size:0.8em;color:#64748b">Flow: Embed (~200ms) → Vector Search → LLM Response<br>Target: ~2.5s (vs Bản 1: 3-6s)</p>
    `;
            }
        }

        function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }

        // Enter to send
        document.getElementById('input').addEventListener('keydown', e => { if (e.key === 'Enter') send(); });