const messagesEl = document.getElementById('chatMessages');
        const inputEl = document.getElementById('chatInput');
        const sendBtn = document.getElementById('sendBtn');
        const pipelineEl = document.getElementById('pipelineSteps');
        const pathBadge = document.getElementById('pathBadge');

        let requestCount = 0;

        function addMsg(type, html, meta) {
            const div = document.createElement('div');
            div.className = 'msg ' + type;
            div.innerHTML = html;
            if (meta && type === 'ai') {
                const metaDiv = document.createElement('div');
                metaDiv.className = 'meta';
                metaDiv.innerHTML = meta;
                div.appendChild(metaDiv);
            }
            messagesEl.appendChild(div);
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }

        function showThinking() {
            const div = document.createElement('div');
            div.className = 'msg ai thinking';
            div.id = 'thinkingMsg';
            div.innerHTML = '<span></span><span></span><span></span>';
            messagesEl.appendChild(div);
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }

        function hideThinking() {
            const el = document.getElementById('thinkingMsg');
            if (el) el.remove();
        }

        function md(text) {
            if (!text) return '';
            try {
                marked.setOptions({ breaks: true, gfm: true });
                return marked.parse(text);
            } catch(e) {
                // Fallback nếu marked lỗi
                return text
                    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                    .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>')
                    .replace(/`(.*?)`/g, '<code>$1</code>')
                    .replace(/\n/g, '<br>');
            }
        }

        function escHtml(s) { return (s || '').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }

        // ═══════ PIPELINE RENDERING ═══════
        function renderPipeline(pipeline, elapsedMs, agentPath) {
            // Ghi đè flow cũ — chỉ hiện flow mới nhất
            requestCount++;
            pipelineEl.innerHTML = '';

            pathBadge.textContent = agentPath + ' · ' + elapsedMs + 'ms';

            pipeline.forEach((step, i) => {
                const div = document.createElement('div');
                div.className = `p-step s-${step.step} new`;

                let contentHtml = '';

                if (step.step === 'user') {
                    contentHtml = `<div class="step-content">${escHtml(step.content)}</div>`;
                } else if (step.step === 'planner') {
                    contentHtml = '';
                    if (step.content && step.content !== '(gọi tool...)') {
                        contentHtml += `<div class="step-content">${escHtml(step.content)}</div>`;
                    }
                    // Show tool calls with args
                    if (step.tool_calls && step.tool_calls.length) {
                        step.tool_calls.forEach(tc => {
                            contentHtml += `<div class="tool-args"><div class="arg-row"><span class="arg-key">🔧 tool:</span><span class="arg-val">${escHtml(tc.name)}</span></div>`;
                            if (tc.args) {
                                Object.entries(tc.args).forEach(([k, v]) => {
                                    if (v !== null && v !== undefined && v !== '') {
                                        contentHtml += `<div class="arg-row"><span class="arg-key">${escHtml(k)}:</span><span class="arg-val">${escHtml(String(v))}</span></div>`;
                                    }
                                });
                            }
                            contentHtml += '</div>';
                        });
                    }
                } else if (step.step === 'tool_result') {
                    contentHtml = `<div class="step-content">${escHtml(step.content)}</div>`;
                    if (step.raw_json) {
                        contentHtml += `<details class="raw-json-toggle"><summary>📋 Xem raw JSON</summary><pre>${escHtml(step.raw_json)}</pre></details>`;
                    }
                } else if (step.step === 'responder') {
                    contentHtml = `<div class="step-content truncated">${escHtml(step.content)}</div>`;
                }

                div.innerHTML = `<div class="step-label">${step.label}</div>${contentHtml}`;
                pipelineEl.appendChild(div);

                // Remove animation class after it runs
                setTimeout(() => div.classList.remove('new'), 350);
            });

            pipelineEl.scrollTop = pipelineEl.scrollHeight;
        }

        // ═══════ SEND MESSAGE ═══════
        async function sendMsg() {
            const query = inputEl.value.trim();
            if (!query) return;

            inputEl.value = '';
            sendBtn.disabled = true;
            addMsg('user', escHtml(query));
            showThinking();

            try {
                const token = (parent && parent.localStorage) ? parent.localStorage.getItem('canifa_token') : localStorage.getItem('canifa_token');
                const resp = await fetch('/api/sku-search/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        ...(token ? { 'Authorization': 'Bearer ' + token } : {}),
                    },
                    body: JSON.stringify({ query }),
                });
                const data = await resp.json();
                hideThinking();

                if (data.status === 'success') {
                    const meta = `⏱ ${data.elapsed_ms}ms · ${data.agent_path}`;
                    addMsg('ai', md(data.response), meta);

                    // Render pipeline on the right
                    if (data.pipeline && data.pipeline.length) {
                        renderPipeline(data.pipeline, data.elapsed_ms, data.agent_path);
                    }
                } else {
                    addMsg('error', '❌ ' + (data.message || 'Lỗi'));
                }
            } catch (e) {
                hideThinking();
                addMsg('error', '❌ Lỗi kết nối: ' + e.message);
            } finally {
                sendBtn.disabled = false;
                inputEl.focus();
            }
        }

        function sendQuick(text) {
            inputEl.value = text;
            sendMsg();
        }

        inputEl.focus();