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) {
        return text
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>')
            .replace(/`(.*?)`/g, '<code>$1</code>')
            .replace(/~~(.*?)~~/g, '<del>$1</del>')
            .replace(/^- (.*)/gm, '• $1')
            .replace(/\n/g, '<br>');
    }
}

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

// ═══════ PIPELINE RENDERING ═══════
function renderPipeline(pipeline, elapsedMs, agentPath) {
    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') {
            if (step.content && step.content !== '(gọi tool...)') {
                contentHtml += `<div class="step-content">${escHtml(step.content)}</div>`;
            }
            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 !== '') {
                                const display = Array.isArray(v) ? v.join(', ') : String(v);
                                contentHtml += `<div class="arg-row"><span class="arg-key">${escHtml(k)}:</span><span class="arg-val">${escHtml(display)}</span></div>`;
                            }
                        });
                    }
                    contentHtml += '</div>';
                });
            }
        } else if (step.step === 'tool_result') {
            try {
                marked.setOptions({ breaks: true, gfm: true });
                contentHtml = `<div class="step-content truncated md-content">${marked.parse(step.content)}</div>`;
            } catch(e) {
                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);
        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/store-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);

            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();