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');
const sessionBadge = document.getElementById('sessionBadge');
const historyCountEl = document.getElementById('historyCount');
const timingBadge = document.getElementById('timingBadge');
const traceBadge = document.getElementById('traceBadge');

let requestCount = 0;
let _lastTraceId = null;

// ═══════ SESSION ID — persist across reloads ═══════
function getSessionId() {
    let sid = sessionStorage.getItem('tag_search_session_id');
    if (!sid) {
        sid = 'ts_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8);
        sessionStorage.setItem('tag_search_session_id', sid);
    }
    return sid;
}
const SESSION_ID = getSessionId();
sessionBadge.textContent = SESSION_ID.slice(0, 16) + '…';
sessionBadge.title = 'Session: ' + SESSION_ID;

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);
                                if (k === 'reasoning') {
                                    contentHtml += `<div class="arg-row" style="margin-top:4px;padding:4px 6px;background:rgba(168,85,247,0.1);border-radius:4px;border-left:3px solid #a855f7;"><span class="arg-key" style="color:#a855f7;">💡 suy luận:</span><span class="arg-val" style="font-style:italic;color:#7c3aed;">${escHtml(display)}</span></div>`;
                                } else {
                                    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/tag-search/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                ...(token ? {'Authorization': 'Bearer ' + token} : {}),
            },
            body: JSON.stringify({ query, session_id: SESSION_ID }),
        });
        const data = await resp.json();
        hideThinking();

        if (data.status === 'success') {
            // ── Timing từ controller v2 ──
            const timing = data.timing || {};
            const wallMs = timing.wall_ms || timing.total_ms || data.elapsed_ms || '?';
            const plannerMs = timing.planner_ms || 0;
            const responderMs = timing.responder_ms || 0;

            // ── Meta line cho AI bubble ──
            const metaParts = [
                `⏱ ${wallMs}ms`,
                data.agent_path || null,
                data.product_count ? `📦 ${data.product_count} SP` : null,
            ].filter(Boolean);
            addMsg('ai', md(data.response), metaParts.join(' · '));

            // ── Product cards ──
            if (data.products && data.products.length) {
                renderProductCards(data.products);
            }

            // ── History count ──
            if (data.history_count !== undefined) {
                historyCountEl.textContent = `hist: ${data.history_count}`;
            }

            // ── Timing badge ──
            if (timing.wall_ms || timing.total_ms) {
                timingBadge.style.display = '';
                const parts = [];
                if (plannerMs) parts.push(`P:${plannerMs}ms`);
                if (responderMs) parts.push(`R:${responderMs}ms`);
                parts.push(`T:${wallMs}ms`);
                timingBadge.textContent = parts.join(' | ');
            }

            // ── Trace badge (Langfuse) ──
            if (data.trace_id) {
                _lastTraceId = data.trace_id;
                traceBadge.style.display = '';
                traceBadge.textContent = '🔍 ' + data.trace_id.slice(0,8) + '…';
                traceBadge.title = 'Langfuse: ' + data.trace_id + ' (click to copy)';
            }

            // ── Pipeline ──
            if (data.pipeline && data.pipeline.length) {
                renderPipeline(data.pipeline, wallMs, 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 copyTrace() {
    if (!_lastTraceId) return;
    navigator.clipboard.writeText(_lastTraceId).then(() => {
        const orig = traceBadge.textContent;
        traceBadge.textContent = '✅ Copied!';
        setTimeout(() => traceBadge.textContent = orig, 1500);
    });
}

function renderProductCards(products) {
    // Max 6 per turn
    const shown = products.slice(0, 6);
    const grid = document.createElement('div');
    grid.className = 'products-grid';

    shown.forEach(p => {
        const card = document.createElement('div');
        card.className = 'product-card';
        card.onclick = () => openProductPopup(p);

        // Fields từ tag_search_tool._format_products():
        // sku, name, price (sale), original_price, discount (string '-xx%'),
        // color, gender, product_line, image, url, in_stock, total_qty
        const salePrice = p.price || 0;
        const origPrice = p.original_price || 0;
        const hasDiscount = origPrice > salePrice && salePrice > 0;
        const discStr = p.discount || (hasDiscount ? `-${Math.round((1-salePrice/origPrice)*100)}%` : null);
        const priceStr = salePrice ? salePrice.toLocaleString('vi-VN') + '₫' : 'Liên hệ';
        const origStr = (origPrice && hasDiscount) ? origPrice.toLocaleString('vi-VN') + '₫' : '';
        const imgUrl = p.image || '';
        const stockDot = p.in_stock === false ? '<span style="color:#dc2626">● Hết</span>' : (p.in_stock === true ? '<span style="color:#16a34a">● Còn</span>' : '');

        card.innerHTML = `
            <img class="pc-img" src="${escHtml(imgUrl)}" alt="${escHtml(p.name || '')}" loading="lazy"
                 onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><rect fill=%22%23f5f5f4%22 width=%22100%22 height=%22100%22/><text x=%2250%22 y=%2252%22 text-anchor=%22middle%22 fill=%22%23a8a29e%22 font-size=%2212%22>No img</text></svg>'">
            <div class="pc-body">
                <div class="pc-name">${escHtml(p.name || '')}</div>
                <div class="pc-meta">
                    ${p.color ? `<span>🎨 ${escHtml(p.color)}</span>` : ''}
                    ${p.gender ? `<span>${escHtml(p.gender)}</span>` : ''}
                    ${stockDot}
                </div>
                <div class="pc-price-row">
                    <span class="pc-price">${priceStr}</span>
                    ${origStr ? `<span class="pc-orig">${origStr}</span>` : ''}
                    ${discStr ? `<span class="pc-disc">${escHtml(discStr)}</span>` : ''}
                </div>
                <div class="pc-sku">${escHtml(p.sku || '')}</div>
            </div>
        `;
        grid.appendChild(card);
    });

    if (products.length > 6) {
        const more = document.createElement('div');
        more.style.cssText = 'grid-column:1/-1;text-align:center;font-size:11px;color:var(--muted-fg);padding:4px 0;font-style:italic;';
        more.textContent = `+${products.length - 6} sản phẩm khác trong response`;
        grid.appendChild(more);
    }

    messagesEl.appendChild(grid);
    messagesEl.scrollTop = messagesEl.scrollHeight;
}

// ═══════ PRODUCT DETAIL POPUP (C-Stylist style) ═══════
// Lazy refs — HTML is below the script tag
function _pd(id) { return document.getElementById(id); }
let _pdSelectedSize = null;

function closeProductPopup() {
    _pd('pdOverlay')?.classList.remove('active');
    _pd('pdPopup')?.classList.remove('active');
    _pdSelectedSize = null;
}

async function openProductPopup(product) {
    _pd('pdOverlay').classList.add('active');
    _pd('pdPopup').classList.add('active');
    _pd('pdBody').innerHTML = '<div class="pd-loading"><div class="spin"></div><br>Đang tải...</div>';
    _pdSelectedSize = null;

    // Field mapping từ JSON mới (tag_search_tool._format_products)
    const sku = product.sku || '';
    const name = (product.name || '').replace(/[\uFFFD]/g, '');
    const imgUrl = product.image || '';
    const origPrice = product.original_price || 0;
    const finalPrice = product.price || 0;
    const discStr = product.discount || '';
    const discPct = discStr ? parseInt(discStr.replace(/[^0-9]/g,'')) || 0
                           : (origPrice > finalPrice ? Math.round((1-finalPrice/origPrice)*100) : 0);
    const webUrl = product.url || '#';
    const skuDisplay = sku;
    const inStock = product.in_stock ?? true;

    // Sizes from our DB (pipe-separated or array)
    let sizes = product.available_sizes || product.sizes || [];
    if (typeof sizes === 'string') sizes = sizes.split('|').map(s=>s.trim()).filter(Boolean);

    // Colors from our DB
    const colors = product.colors || [];

    // Render popup HTML
    const fmtP = (n) => n ? Number(n).toLocaleString('vi-VN') + ' đ' : '';

    _pd('pdBody').innerHTML = `
        <div class="pd-main">
            <div class="pd-img-col">
                <img class="pd-img-main" src="${escHtml(imgUrl)}" alt="${escHtml(name)}"
                     onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 180 240%22><rect fill=%22%23f5f5f5%22 width=%22180%22 height=%22240%22/><text x=%2290%22 y=%22125%22 text-anchor=%22middle%22 fill=%22%23ccc%22 font-size=%2214%22>No image</text></svg>'">
            </div>
            <div class="pd-info-col">
                <h4 class="pd-name">${escHtml(name)}</h4>
                <div class="pd-sku">
                    Mã: ${escHtml(skuDisplay)}
                    <button class="pd-sku-copy" onclick="navigator.clipboard.writeText('${escHtml(skuDisplay)}')" title="Copy mã">📋</button>
                </div>
                <div class="pd-price-block">
                    ${origPrice > finalPrice ? `<span class="pd-orig-price">${fmtP(origPrice)}</span>` : ''}
                    ${discPct > 0 ? `<span class="pd-discount">-${discPct}%</span>` : ''}
                </div>
                <div class="pd-final-price">${fmtP(finalPrice)}</div>
                <a class="pd-detail-link" href="${escHtml(webUrl)}" target="_blank" rel="noopener">Chi tiết &gt;&gt;</a>
            </div>
        </div>

        ${colors.length > 0 ? `
        <div class="pd-section">
            <div class="pd-section-label">Màu sắc: ${escHtml(colors[0]?.color || '')}</div>
            <div class="pd-colors">
                ${colors.map(c => `
                    <img class="pd-color-thumb" src="${escHtml(c.thumbnail || imgUrl)}" alt="${escHtml(c.color || '')}" title="${escHtml(c.color || '')}">
                `).join('')}
            </div>
        </div>` : ''}

        <div class="pd-section">
            <div class="pd-section-label">Kích cỡ: <span style="color:#3b82f6;cursor:pointer;font-weight:400;">Chọn kích cỡ</span></div>
            <div class="pd-sizes">
                ${sizes.length > 0 ? sizes.map(s => `
                    <button class="pd-size-btn" onclick="selectPdSize(this,'${escHtml(s)}')">${escHtml(s)}</button>
                `).join('') : '<span style="font-size:12px;color:#999;">Đang cập nhật...</span>'}
            </div>
        </div>

        <button class="pd-add-cart" id="pdAddCartBtn" onclick="addPdToCart()">
            THÊM VÀO GIỎ HÀNG
        </button>
    `;

    // Store current product data for cart
    _pd('pdPopup')._currentProduct = { name, sku: skuDisplay, price: finalPrice, originalPrice: origPrice, image: imgUrl, url: webUrl };
}

function selectPdSize(btn, size) {
    document.querySelectorAll('.pd-size-btn').forEach(b => b.classList.remove('selected'));
    btn.classList.add('selected');
    _pdSelectedSize = size;
    const addBtn = document.getElementById('pdAddCartBtn');
    if (addBtn) { addBtn.classList.add('ready'); }
}

function addPdToCart() {
    if (!_pdSelectedSize) {
        alert('Vui lòng chọn kích cỡ!');
        return;
    }
    const p = _pd('pdPopup')?._currentProduct;
    if (!p) return;
    // Use cart.js addToCart function
    if (typeof addToCart === 'function') {
        addToCart({
            sku: p.sku,
            cartKey: `${p.sku}:${_pdSelectedSize}`,
            name: p.name,
            size: _pdSelectedSize,
            price: p.price,
            originalPrice: p.originalPrice || p.price,
            image: p.image,
        });
    } else {
        alert(`Đã thêm ${p.name} - Size ${_pdSelectedSize} vào giỏ hàng!`);
    }
    closeProductPopup();
}

// ═══════ NEW SESSION (tạo mới, bỏ cũ) ═══════
function newSession() {
    // Tạo session mới, KHÔNG xoá Redis cũ (để nó tự expire)
    const newSid = 'ts_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8);
    sessionStorage.setItem('tag_search_session_id', newSid);
    location.reload();
}

// ═══════ CLEAR CHAT (xoá Redis + tạo mới) ═══════
async function clearChat() {
    try {
        const token = (parent && parent.localStorage) ? parent.localStorage.getItem('canifa_token') : localStorage.getItem('canifa_token');
        await fetch('/api/tag-search/clear', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                ...(token ? {'Authorization': 'Bearer ' + token} : {}),
            },
            body: JSON.stringify({ query: '', session_id: SESSION_ID }),
        });
    } catch(e) {
        console.warn('Clear error:', e);
    }
    // Tạo session mới + reload
    newSession();
}

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

// ═══════ LOAD HISTORY ON STARTUP ═══════
async function loadHistory() {
    try {
        const token = (parent && parent.localStorage) ? parent.localStorage.getItem('canifa_token') : localStorage.getItem('canifa_token');
        const res = await fetch(`/api/tag-search/history?session_id=${SESSION_ID}`, {
            headers: {
                ...(token ? {'Authorization': 'Bearer ' + token} : {}),
            }
        });
        const data = await res.json();
        if (data.status === 'success' && data.history && data.history.length > 0) {
            historyCountEl.textContent = `hist: ${data.count}`;
            data.history.forEach(msg => {
                const type = msg.role === 'user' ? 'user' : 'ai';
                // If it's AI, we can just print the content directly. For old messages there's no meta block.
                addMsg(type, msg.content); 
            });
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }
    } catch(e) {
        console.warn('Load history error:', e);
    }
}

inputEl.focus();
loadHistory();