// ═══════════════════════════════════════
// 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) {
    const container = document.getElementById('pipelineTrace');
    container.innerHTML = '';

    if (!steps || steps.length === 0) {
        container.innerHTML = '<div style="font-size:11px;color:var(--muted-fg)">Không có pipeline data.</div>';
        return;
    }

    steps.forEach((step, idx) => {
        const div = document.createElement('div');
        div.className = `pipe-step step-${step.step}`;

        const header = document.createElement('div');
        header.className = 'pipe-header';

        const label = document.createElement('span');
        label.className = 'pipe-label';
        label.textContent = step.label || step.step;
        header.appendChild(label);

        if (step.elapsed_ms) {
            const time = document.createElement('span');
            time.className = 'pipe-time';
            time.textContent = step.elapsed_ms + 'ms';
            header.appendChild(time);
        }
        div.appendChild(header);

        if (step.content) {
            const content = document.createElement('div');
            content.className = 'pipe-content';
            content.textContent = step.content.length > 300
                ? step.content.slice(0, 300) + '…'
                : step.content;
            div.appendChild(content);
        }

        if (step.raw_json) {
            const toggleId = 'pipeRaw_' + idx;
            const toggle = document.createElement('span');
            toggle.className = 'pipe-raw-toggle';
            toggle.textContent = '▸ Raw JSON';
            toggle.onclick = () => {
                const raw = document.getElementById(toggleId);
                const isOpen = raw.classList.toggle('open');
                toggle.textContent = isOpen ? '▾ Raw JSON' : '▸ Raw JSON';
            };
            div.appendChild(toggle);

            const raw = document.createElement('pre');
            raw.className = 'pipe-raw';
            raw.id = toggleId;
            raw.textContent = step.raw_json;
            div.appendChild(raw);
        }

        if (step.tool_calls) {
            step.tool_calls.forEach(tc => {
                const tcDiv = document.createElement('div');
                tcDiv.className = 'pipe-content';
                tcDiv.style.cssText = 'margin-top:4px;font-size:10px;color:#f97316';
                tcDiv.textContent = `→ ${tc.name}(${JSON.stringify(tc.args).slice(0, 200)})`;
                div.appendChild(tcDiv);
            });
        }

        container.appendChild(div);
    });
}

// ═══════════════════════════════════════
// 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);
});
