// ═══════════════════════════════════════
// Lead Flow — Main Chat + Stage Logic
// ═══════════════════════════════════════

const STAGE_COLORS = {
    1: '#3b82f6', 2: '#10b981', 3: '#f59e0b',
    4: '#ec4899', 5: '#8b5cf6'
};
const STAGE_NAMES = {
    1: 'AWARENESS', 2: 'INTEREST', 3: 'CONSIDERATION',
    4: 'DECISION', 5: 'RETENTION'
};

let currentStage = 0;
let turnCount = 0;
let stageLog = [];
let isSending = false;
let currentConversationId = null;

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

// ── Persistent device_id ──
let LEAD_DEVICE_ID = (() => {
    const KEY = 'canifa_lead_device_id';
    let id = localStorage.getItem(KEY);
    if (!id) { id = uuidv4(); localStorage.setItem(KEY, id); }
    return id;
})();

function handleDeviceIdChange() {
    const el = document.getElementById('deviceIdInput');
    if (!el) return;
    let val = el.value.trim();
    if (!val) {
        val = uuidv4();
        el.value = val;
    }
    LEAD_DEVICE_ID = val;
    localStorage.setItem('canifa_lead_device_id', val);
    
    // Hard reset conversation to prevent mingling histories
    localStorage.removeItem('canifa_lead_last_conv');
    window.location.search = '';
}

// ── Configure marked ──
if (typeof marked !== 'undefined') {
    marked.setOptions({ breaks: true, gfm: true, sanitize: false });
}

// ═══════════════════════════════════════
// Chat Logic
// ═══════════════════════════════════════
function sendQuick(text) {
    document.getElementById('chatInput').value = text;
    sendMessage();
}

async function sendMessage() {
    const input = document.getElementById('chatInput');
    const query = input.value.trim();
    if (!query || isSending) return;

    isSending = true;
    turnCount++;
    input.value = '';
    document.getElementById('sendBtn').disabled = true;

    const empty = document.getElementById('emptyState');
    if (empty) empty.style.display = 'none';

    addMessage(query, 'human');
    document.getElementById('typingIndicator').classList.add('show');

    try {
        const res = await fetch('/api/agent/chat-lead-flow', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                user_query: query,
                conversation_id: currentConversationId,
                device_id: LEAD_DEVICE_ID
            })
        });

        const data = await res.json();

        if (data.status === 'success') {
            const ls = data.lead_stage || {};
            const stage = ls.stage || 2;

            updateProgressBar(stage);
            addMessage(data.ai_response, 'ai', ls, data.products);
            updateDebug(data);

            stageLog.push({ turn: turnCount, stage, query: query.slice(0, 40), name: STAGE_NAMES[stage] });
            updateStageHistory();
        } else {
            addMessage('❌ ' + (data.message || 'Lỗi không xác định'), 'ai');
        }
    } catch (err) {
        addMessage('❌ Không thể kết nối server: ' + err.message, 'ai');
    } finally {
        document.getElementById('typingIndicator').classList.remove('show');
        document.getElementById('sendBtn').disabled = false;
        isSending = false;
    }
}

// ═══════════════════════════════════════
// Message Rendering
// ═══════════════════════════════════════
function scrollToBottom(force = false) {
    const container = document.getElementById('chatMessages');
    if (!container) return;
    if (!force) {
        const near = container.scrollHeight - container.scrollTop - container.clientHeight < 150;
        if (!near) return;
    }
    setTimeout(() => { container.scrollTop = container.scrollHeight; }, 50);
}

function addMessage(text, type, leadStage, products = [], forceScroll = true) {
    const container = document.getElementById('chatMessages');
    const div = document.createElement('div');
    div.className = `msg ${type}`;

    // Stage badge
    if (type === 'ai' && leadStage && leadStage.stage) {
        const stage = leadStage.stage;
        const color = STAGE_COLORS[stage];
        const badge = document.createElement('div');
        badge.className = 'stage-badge';
        badge.style.background = color + '15';
        badge.style.color = color;
        badge.textContent = `Stage ${stage} · ${leadStage.tone_directive || ''}`;
        div.appendChild(badge);
    }

    // Text
    const textDiv = document.createElement('div');
    textDiv.className = 'msg-text';
    if (type === 'ai' && typeof marked !== 'undefined') {
        textDiv.innerHTML = marked.parse(text || '');
    } else {
        textDiv.textContent = text;
    }
    div.appendChild(textDiv);

    // Product cards
    if (type === 'ai' && products && products.length > 0) {
        const grid = document.createElement('div');
        grid.className = 'product-cards';

        products.slice(0, 6).forEach(p => {
            const card = document.createElement('div');
            card.className = 'product-card clickable';
            // QUAN TRỌNG: gắn data lên element, không dùng closure để tránh stale ref
            card.dataset.product = JSON.stringify(p);
            card.addEventListener('click', function () {
                try {
                    const prod = JSON.parse(this.dataset.product);
                    openProductPopup(prod);
                } catch (e) {
                    console.error('[Lead] openProductPopup error', e);
                }
            });

            const hasDiscount = p.original_price && p.original_price > p.price;
            const discStr = p.discount || (hasDiscount
                ? `-${Math.round((1 - p.price / p.original_price) * 100)}%`
                : null);

            card.innerHTML = `
                <img src="${p.image || ''}" alt="${p.name || ''}" class="product-card-img"
                     onload="scrollToBottom(false)"
                     onerror="this.onerror=null;this.src=''"/>
                ${discStr ? `<div class="product-card-discount">${discStr}</div>` : ''}
                <div class="product-card-body">
                    <div class="product-card-sku">${p.sku || ''}</div>
                    <div class="product-card-name">${p.name || ''}</div>
                    <div class="product-card-price">
                        ${p.price ? `<span class="sale">${p.price.toLocaleString()}đ</span>` : ''}
                        ${hasDiscount ? `<span class="original">${p.original_price.toLocaleString()}đ</span>` : ''}
                    </div>
                </div>
            `;
            grid.appendChild(card);
        });

        div.appendChild(grid);
    }

    container.appendChild(div);
    if (forceScroll) scrollToBottom(true);
}

// ═══════════════════════════════════════
// Progress Bar
// ═══════════════════════════════════════
function updateProgressBar(stage) {
    for (let i = 1; i <= 5; i++) {
        document.getElementById(`stageDot${i}`).classList.remove('active');
        document.getElementById(`stageLabel${i}`).classList.remove('active-label');
    }
    for (let i = 1; i <= 4; i++) {
        document.getElementById(`conn${i}`).classList.remove('passed');
    }
    document.getElementById(`stageDot${stage}`).classList.add('active');
    document.getElementById(`stageLabel${stage}`).classList.add('active-label');
    for (let i = 1; i < stage; i++) {
        document.getElementById(`stageDot${i}`).classList.add('active');
        document.getElementById(`stageLabel${i}`).classList.add('active-label');
        document.getElementById(`conn${i}`).classList.add('passed');
    }
    currentStage = stage;
}

// ═══════════════════════════════════════
// Debug Panel
// ═══════════════════════════════════════
function updateDebug(data) {
    const ls = data.lead_stage || {};
    const t = data.timing || {};
    const pipeline = data.pipeline || [];

    renderPipeline(pipeline);

    document.getElementById('tClassifier').textContent = t.classifier_ms ? t.classifier_ms + 'ms' : '—';
    document.getElementById('tStylist').textContent = t.stylist_ms ? t.stylist_ms + 'ms' : '—';
    document.getElementById('tTotal').textContent = t.total_ms ? Math.round(t.total_ms) + 'ms' : '—';

    const stage = ls.stage || 0;
    const color = STAGE_COLORS[stage] || '#888';
    document.getElementById('dStage').textContent = stage;
    document.getElementById('dStage').style.color = color;
    document.getElementById('dStageName').textContent = ls.stage_name || '—';
    document.getElementById('dStageName').style.color = color;
    document.getElementById('dTone').textContent = ls.tone_directive || '—';

    const conf = ls.confidence || 0;
    document.getElementById('dConfidence').textContent = (conf * 100).toFixed(0) + '%';
    const confBar = document.getElementById('confBar');
    confBar.style.width = (conf * 100) + '%';
    confBar.style.background = color;

    document.getElementById('dReasoning').textContent = ls.reasoning || 'Không có.';

    const hintsDiv = document.getElementById('dHints');
    hintsDiv.innerHTML = '';
    const hints = ls.behavioral_hints || [];
    if (hints.length === 0) {
        hintsDiv.innerHTML = '<div class="debug-hint">Không có gợi ý.</div>';
    } else {
        hints.forEach(h => {
            const el = document.createElement('div');
            el.className = 'debug-hint';
            el.style.borderLeftColor = color;
            el.textContent = h;
            hintsDiv.appendChild(el);
        });
    }
}

function renderPipeline(steps) {
    // Reset all nodes
    ['flowUser','flowClassifier','flowTool','flowStylist'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.classList.remove('active','processing');
    });
    ['conn1','conn2','conn3'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.classList.remove('lit');
    });
    ['flowClassifierTime','flowToolTime','flowStylistTime'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.textContent = '';
    });
    ['detailClassifier','detailTool','detailStylist'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.style.display = 'none';
    });

    // Reset sublabels
    const userSub = document.getElementById('flowUserSub');
    const clsSub = document.getElementById('flowClassifierSub');
    const toolSub = document.getElementById('flowToolSub');
    const stylSub = document.getElementById('flowStylistSub');
    const toolLabel = document.getElementById('flowToolLabel');
    if (clsSub) clsSub.textContent = 'Intent + Tool routing';
    if (toolSub) toolSub.textContent = 'Search / Lookup';
    if (toolLabel) toolLabel.textContent = 'Tool';
    if (stylSub) stylSub.textContent = 'Response generation';

    if (!steps || steps.length === 0) return;

    // Light up User immediately
    document.getElementById('flowUser').classList.add('active');

    steps.forEach(step => {
        const s = step.step || '';

        if (s === 'user') {
            document.getElementById('flowUser').classList.add('active');
            if (userSub && step.content) {
                userSub.textContent = step.content.slice(0, 50) + (step.content.length > 50 ? '…' : '');
            }
        }

        if (s === 'classifier') {
            document.getElementById('conn1').classList.add('lit');
            document.getElementById('flowClassifier').classList.add('active');
            if (step.elapsed_ms) {
                document.getElementById('flowClassifierTime').textContent = step.elapsed_ms + 'ms';
            }

            // Update sublabel
            if (clsSub && step.tool_calls && step.tool_calls.length > 0) {
                const tc = step.tool_calls[0];
                const toolName = tc.name || '?';
                clsSub.textContent = '→ ' + toolName;
            }

            // Detail panel
            const dSec = document.getElementById('detailClassifier');
            const dBody = document.getElementById('detailClassifierBody');
            dSec.style.display = 'block';
            
            let html = '';
            if (step.content) {
                html += `<div class="fd-row"><span class="fd-key">Reasoning</span><span class="fd-val">${escHtml(step.content.slice(0, 300))}</span></div>`;
            }
            if (step.tool_calls && step.tool_calls.length > 0) {
                const tc = step.tool_calls[0];
                html += `<div class="fd-row"><span class="fd-key">Tool</span><span class="fd-val" style="color:#f97316;font-weight:700">${tc.name}</span></div>`;
                
                if (tc.args) {
                    const args = tc.args;
                    if (args.keywords && args.keywords.length > 0) {
                        html += `<div class="fd-row"><span class="fd-key">Keywords</span><span class="fd-val" style="color:#10b981">[${args.keywords.map(k => '"'+k+'"').join(', ')}]</span></div>`;
                    }
                    if (args.product_line_vn && args.product_line_vn.length > 0) {
                        html += `<div class="fd-row"><span class="fd-key">Product</span><span class="fd-val">[${args.product_line_vn.join(', ')}]</span></div>`;
                    }
                    if (args.gender_by_product) {
                        html += `<div class="fd-row"><span class="fd-key">Gender</span><span class="fd-val">${args.gender_by_product}</span></div>`;
                    }
                    if (args.price_max) {
                        html += `<div class="fd-row"><span class="fd-key">Price max</span><span class="fd-val">${Number(args.price_max).toLocaleString()}đ</span></div>`;
                    }
                }
            }
            dBody.innerHTML = html || '<span style="color:var(--muted-fg)">No data</span>';

            // Update Tool node label
            if (step.tool_calls && step.tool_calls.length > 0 && toolLabel) {
                const name = step.tool_calls[0].name || 'Tool';
                toolLabel.textContent = name.replace(/_/g,' ').replace('lead search tool','Lead Search').replace('check is stock','Stock Check');
            }
        }

        if (s === 'stylist_tool_call' || s === 'tool_result') {
            document.getElementById('conn2').classList.add('lit');
            document.getElementById('flowTool').classList.add('active');

            const dSec = document.getElementById('detailTool');
            const dBody = document.getElementById('detailToolBody');
            dSec.style.display = 'block';

            if (step.elapsed_ms) {
                document.getElementById('flowToolTime').textContent = step.elapsed_ms + 'ms';
            }

            let html = '';
            if (step.content) {
                try {
                    const data = JSON.parse(step.content);
                    const tierClass = data.tier <= 1 ? 'tier1' : data.tier <= 2 ? 'tier2' : 'tier3';
                    html += `<div class="fd-row"><span class="fd-key">Status</span><span class="fd-val">${data.status || '?'}</span></div>`;
                    html += `<div class="fd-row"><span class="fd-key">Results</span><span class="fd-val" style="font-weight:700">${data.count || 0} sản phẩm</span></div>`;
                    html += `<div class="fd-row"><span class="fd-key">Search</span><span class="fd-val"><span class="fd-badge ${tierClass}">${data.search_mode || 'tier'+data.tier}</span></span></div>`;
                    html += `<div class="fd-row"><span class="fd-key">Time</span><span class="fd-val">${data.elapsed_ms || '?'}ms</span></div>`;
                    if (data.keywords_used && data.keywords_used.length > 0) {
                        html += `<div class="fd-row"><span class="fd-key">Keywords</span><span class="fd-val" style="color:#10b981">[${data.keywords_used.join(', ')}]</span></div>`;
                    }
                    // Update Tool sublabel
                    if (toolSub) {
                        toolSub.textContent = `${data.count || 0} kết quả | ${data.search_mode || 'tier'+data.tier}`;
                    }
                    if (data.products && data.products.length > 0) {
                        html += `<div class="fd-row" style="margin-top:4px;border-top:1px solid var(--border);padding-top:4px"><span class="fd-key">Top 3</span><span class="fd-val">`;
                        data.products.slice(0,3).forEach(p => {
                            html += `${p.name} — ${Number(p.price).toLocaleString()}đ<br>`;
                        });
                        html += `</span></div>`;
                    }
                } catch(e) {
                    html = `<span style="color:var(--muted-fg)">${escHtml(step.content.slice(0, 200))}</span>`;
                }
            }
            dBody.innerHTML = html || '<span style="color:var(--muted-fg)">No data</span>';
        }

        if (s === 'stylist' || s === 'responder') {
            document.getElementById('conn3').classList.add('lit');
            document.getElementById('flowStylist').classList.add('active');
            if (step.elapsed_ms) {
                document.getElementById('flowStylistTime').textContent = step.elapsed_ms + 'ms';
            }

            // Update sublabel
            if (stylSub && step.elapsed_ms) {
                stylSub.textContent = `Generated in ${step.elapsed_ms}ms`;
            }

            const dSec = document.getElementById('detailStylist');
            const dBody = document.getElementById('detailStylistBody');
            dSec.style.display = 'block';

            let html = '';
            if (step.content) {
                html = `<div style="font-family:var(--font-sans);font-size:11px;line-height:1.6">${escHtml(step.content.slice(0, 400))}${step.content.length > 400 ? '…' : ''}</div>`;
            }
            dBody.innerHTML = html || '<span style="color:var(--muted-fg)">No data</span>';
        }
    });
}

function toggleFlowDetail(sectionId) {
    const sec = document.getElementById(sectionId);
    if (sec) sec.classList.toggle('collapsed');
}

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

// ═══════════════════════════════════════
// Stage History
// ═══════════════════════════════════════
function updateStageHistory() {
    const container = document.getElementById('stageHistory');
    container.innerHTML = '';

    stageLog.slice(-8).reverse().forEach(entry => {
        const div = document.createElement('div');
        div.className = 'history-entry';

        const turn = document.createElement('span');
        turn.className = 'h-turn';
        turn.textContent = '#' + entry.turn;

        const badge = document.createElement('span');
        badge.className = 'h-stage';
        const color = STAGE_COLORS[entry.stage];
        badge.style.background = color + '18';
        badge.style.color = color;
        badge.textContent = 'S' + entry.stage;

        const query = document.createElement('span');
        query.className = 'h-query';
        query.textContent = entry.query;

        div.appendChild(turn);
        div.appendChild(badge);
        div.appendChild(query);
        container.appendChild(div);
    });
}

// ═══════════════════════════════════════
// History API (Postgres)
// ═══════════════════════════════════════
async function loadHistory(convId) {
    try {
        const res = await fetch(`/api/lead/history?conv_id=${convId}&limit=50`, {
            headers: { 'device_id': LEAD_DEVICE_ID }
        });
        if (!res.ok) return;
        const data = await res.json();

        const items = Array.isArray(data.data) ? data.data : [];
        if (items.length === 0) return;

        const empty = document.getElementById('emptyState');
        if (empty) empty.style.display = 'none';

        const chronological = items.slice().reverse();

        chronological.forEach(item => {
            if (item.is_human) {
                addMessage(String(item.message || ''), 'human', null, [], false);
            } else {
                let content = String(item.message || '');
                let leadStage = null;
                let products = [];

                try {
                    const parsed = JSON.parse(content);
                    if (parsed && parsed.ai_response) {
                        content = parsed.ai_response;
                        leadStage = parsed.lead_stage || null;
                        products = parsed.products || [];
                    }
                } catch (e) { /* plain text */ }

                addMessage(content, 'ai', leadStage, products, false);
            }
        });

        scrollToBottom(true);
    } catch (err) {
        console.error('[Lead] Failed to load history', err);
    }
}

// ═══════════════════════════════════════
// Conversation Management
// ═══════════════════════════════════════
function saveConversationHistory(convId) {
    let histories = JSON.parse(localStorage.getItem('canifa_leadflow_histories') || '[]');
    histories = histories.filter(h => h.id !== convId);
    histories.unshift({ id: convId, date: new Date().toLocaleString() });
    if (histories.length > 20) histories = histories.slice(0, 20);
    localStorage.setItem('canifa_leadflow_histories', JSON.stringify(histories));
}

function loadConversationList(currentId) {
    const select = document.getElementById('historySelect');
    const histories = JSON.parse(localStorage.getItem('canifa_leadflow_histories') || '[]');
    select.innerHTML = '<option value="">-- Mở phiên Chat Mới --</option>';
    histories.forEach(h => {
        const opt = document.createElement('option');
        opt.value = h.id;
        opt.textContent = h.date + ' (' + h.id.split('-')[0] + ')';
        if (h.id === currentId) opt.selected = true;
        select.appendChild(opt);
    });
}

function switchConversation(val) {
    if (!val) val = uuidv4();
    localStorage.setItem('canifa_lead_last_conv', val);
    const urlParams = new URLSearchParams(window.location.search);
    urlParams.set('conversation_id', val);
    window.location.search = urlParams.toString();
}

// ═══════════════════════════════════════
// Init
// ═══════════════════════════════════════
window.addEventListener('DOMContentLoaded', async () => {
    // Populate device_id input
    const devInput = document.getElementById('deviceIdInput');
    if (devInput) devInput.value = LEAD_DEVICE_ID;

    const urlParams = new URLSearchParams(window.location.search);
    let convId = urlParams.get('conversation_id');

    if (!convId) convId = localStorage.getItem('canifa_lead_last_conv');
    if (!convId) convId = uuidv4();

    const newParams = new URLSearchParams(window.location.search);
    newParams.set('conversation_id', convId);
    window.history.replaceState({}, '', window.location.pathname + '?' + newParams.toString());

    currentConversationId = convId;
    localStorage.setItem('canifa_lead_last_conv', convId);
    document.getElementById('chatInput').focus();

    saveConversationHistory(convId);
    loadConversationList(convId);
    await loadHistory(convId);
});
