const messagesArea = document.getElementById('messagesArea');
const loadMoreBtn = document.getElementById('loadMoreBtn');
const emptyState = document.getElementById('emptyState');

let currentIdentityKey = '';
let nextCursor = null;
let totalMessages = 0;
let totalProducts = 0;

// Set default date to today
function setToday() {
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('dateFrom').value = today;
    document.getElementById('dateTo').value = today;
}

function clearResults() {
    messagesArea.innerHTML = '';
    messagesArea.appendChild(emptyState);
    emptyState.style.display = '';
    currentIdentityKey = '';
    nextCursor = null;
    totalMessages = 0;
    totalProducts = 0;
    loadMoreBtn.classList.remove('visible');
    document.getElementById('statsBar').style.display = 'none';
}

function formatTime(ts) {
    if (!ts) return '';
    const d = new Date(ts);
    return d.toLocaleString('vi-VN', { day:'2-digit', month:'2-digit', hour:'2-digit', minute:'2-digit' });
}

function formatPrice(p) {
    if (!p) return '';
    return Number(p).toLocaleString('vi-VN') + '₫';
}

function renderProductCards(products) {
    if (!products || !products.length) return '';
    const cards = products.map(p => {
        const name = (typeof p === 'object') ? (p.name || p.sku || '') : String(p);
        const sku = (typeof p === 'object') ? (p.sku || '') : String(p);
        const thumb = (typeof p === 'object') ? (p.thumbnail_image_url || '') : '';
        const price = (typeof p === 'object') ? p.price : null;
        const salePrice = (typeof p === 'object') ? p.sale_price : null;
        const url = (typeof p === 'object') ? p.url : '';
        
        const imgSrc = thumb || 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48"><rect fill="%23f0efec" width="48" height="48" rx="6"/><text x="24" y="28" text-anchor="middle" fill="%2378716c" font-size="10">📦</text></svg>';
        
        let priceHtml = '';
        if (salePrice && salePrice < price) {
            priceHtml = `<span class="sale">${formatPrice(salePrice)}</span><span class="original">${formatPrice(price)}</span>`;
        } else if (price) {
            priceHtml = `<span class="normal">${formatPrice(price)}</span>`;
        }

        const linkHtml = url ? `<a class="product-link" href="https://canifa.com/${url}" target="_blank">Xem SP ↗</a>` : '';
        
        return `<div class="product-card">
            <img src="${imgSrc}" alt="${name}" onerror="this.style.display='none'">
            <div class="product-info">
                <div class="product-name" title="${name}">${name || sku}</div>
                <div class="product-price">${priceHtml}</div>
                ${linkHtml}
            </div>
        </div>`;
    }).join('');
    return `<div class="product-row">${cards}</div>`;
}

function createMessageEl(item, rawData) {
    const isUser = item.is_human;
    const div = document.createElement('div');
    div.className = `msg ${isUser ? 'user' : 'bot'}`;
    
    const products = (!isUser && item.product_ids && item.product_ids.length) ? item.product_ids : [];
    totalProducts += products.length;
    
    const rawId = 'raw_' + (item.id || Math.random().toString(36).substr(2,6));
    
    div.innerHTML = `
        <div class="msg-sender">${isUser ? '👤 Khách hàng' : '🤖 AI'}</div>
        <div class="msg-bubble">${escapeHtml(item.message || '')}</div>
        ${!isUser ? renderProductCards(products) : ''}
        <div class="msg-time">
            ${formatTime(item.timestamp)}
            <span class="raw-toggle" onclick="document.getElementById('${rawId}').classList.toggle('open')">Raw</span>
        </div>
        <div class="msg-raw" id="${rawId}">${JSON.stringify(rawData || item, null, 2)}</div>
    `;
    return div;
}

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

async function loadHistory() {
    clearResults();
    const key = document.getElementById('identityKey').value.trim();
    if (!key) { alert('Nhập identity key trước!'); return; }
    currentIdentityKey = key;
    await fetchMessages();
}

async function loadMore() {
    if (!nextCursor || !currentIdentityKey) return;
    await fetchMessages(nextCursor);
}

async function fetchMessages(beforeId = null) {
    const params = new URLSearchParams({ limit: '30' });
    if (beforeId) params.append('before_id', beforeId);
    
    const dateFrom = document.getElementById('dateFrom').value;
    const dateTo = document.getElementById('dateTo').value;
    if (dateFrom) params.append('date_from', dateFrom);
    if (dateTo) params.append('date_to', dateTo);

    try {
        const res = await fetch(`/api/check-history/${encodeURIComponent(currentIdentityKey)}?${params.toString()}`);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const payload = await res.json();
        const items = payload.data || [];

        if (!items.length && !beforeId) {
            emptyState.innerHTML = '<i class="fas fa-search"></i><p>Không tìm thấy lịch sử cho identity key này</p>';
            return;
        }

        emptyState.style.display = 'none';

        // Items come newest-first, reverse for display
        const reversed = [...items].reverse();
        reversed.forEach(item => {
            if (beforeId) {
                messagesArea.insertBefore(createMessageEl(item, item), messagesArea.firstChild);
            } else {
                messagesArea.appendChild(createMessageEl(item, item));
            }
            totalMessages++;
        });

        nextCursor = payload.next_cursor;
        loadMoreBtn.classList.toggle('visible', !!nextCursor);

        // Update stats
        document.getElementById('statMessages').textContent = totalMessages;
        document.getElementById('statProducts').textContent = totalProducts;
        const dateRange = dateFrom && dateTo ? `${dateFrom} → ${dateTo}` : (dateFrom || dateTo || 'Tất cả');
        document.getElementById('statDateRange').textContent = dateRange;
        document.getElementById('statsBar').style.display = '';

        // Scroll to bottom on first load
        if (!beforeId) {
            const scroll = document.getElementById('chatScroll');
            scroll.scrollTop = scroll.scrollHeight;
        }
    } catch (err) {
        alert('Lỗi: ' + err.message);
    }
}