// ═══ STATE ═══
let offset = 0;
const LIMIT = 50;
let filterNew = false;
let filterDiscount = false;
let searchTimer = null;

// ═══ HELPERS ═══
function fmt(n) { return n == null ? '—' : Number(n).toLocaleString('vi-VN'); }
function fmtK(n) {
    if (n == null || n === 0) return '—';
    if (n >= 1000000) return (n/1e6).toFixed(1) + 'M';
    if (n >= 1000) return Math.round(n/1000) + 'K';
    return fmt(n);
}
function emoji(line) {
    return '';
}

// ═══ CLOCK ═══
setInterval(() => {
    document.getElementById('clock').textContent = new Date().toLocaleTimeString('vi-VN', {hour:'2-digit',minute:'2-digit',second:'2-digit'});
}, 1000);

// ═══ LOAD OVERVIEW ═══
async function loadOverview() {
    try {
        const r = await fetch('/api/products/overview');
        const d = await r.json();
        if (d.status !== 'success') return;
        const s = d.stats;
        document.getElementById('kpi-total').textContent = fmt(s.total_products);
        document.getElementById('kpi-total-sub').textContent = 'real-time StarRocks';
        document.getElementById('kpi-lines').textContent = fmt(s.total_lines);
        document.getElementById('kpi-lines-sub').textContent = 'loại sản phẩm';
        document.getElementById('kpi-avg').textContent = fmtK(s.avg_price) + '₫';
        document.getElementById('kpi-avg-sub').textContent = fmtK(s.min_price) + '₫ — ' + fmtK(s.max_price) + '₫';
        document.getElementById('kpi-discount').textContent = fmt(s.discounted_count);
        document.getElementById('kpi-discount-sub').textContent = 'SP đang khuyến mãi';
        document.getElementById('kpi-new').textContent = fmt(s.new_count);
        document.getElementById('kpi-new-sub').textContent = 'sản phẩm mới';
        document.getElementById('kpi-sold').textContent = fmt(s.total_sold);
        document.getElementById('kpi-sold-sub').textContent = fmt(s.selling_count) + ' SP đã bán';
        document.getElementById('topbar-meta').textContent = fmt(s.total_products) + ' SP · ' + fmt(s.total_lines) + ' dòng SP · StarRocks live';

        // Lines breakdown
        if (d.product_lines?.length) {
            document.getElementById('lines-breakdown').innerHTML = d.product_lines.map(l =>
                `<div class="bd-item"><span class="bd-name">${emoji(l.product_line_vn)} ${l.product_line_vn||'N/A'}</span><span class="bd-val">${fmt(l.count)} SP · ${fmtK(l.avg_price)}₫</span></div>`
            ).join('');
        }
        // Gender breakdown
        if (d.genders?.length) {
            document.getElementById('gender-breakdown').innerHTML = d.genders.map(g => {
                const e = '';
                const n = g.gender_by_product === 'men' ? 'Nam' : g.gender_by_product === 'women' ? 'Nữ' : g.gender_by_product === 'unisex' ? 'Unisex' : g.gender_by_product || 'N/A';
                return `<div class="bd-item"><span class="bd-name">${e} ${n}</span><span class="bd-val">${fmt(g.count)} SP</span></div>`;
            }).join('');
        }
        document.getElementById('breakdowns').style.display = 'grid';
    } catch(e) { console.error('Overview error:', e); }
}

// ═══ LOAD PRODUCTS ═══
async function loadProducts() {
    const c = document.getElementById('table-container');
    c.innerHTML = '<div class="loading"><div class="spinner"></div>Đang tải...</div>';

    const sort = document.getElementById('sort-select').value;
    const gender = document.getElementById('gender-select').value;
    const search = document.getElementById('search-input').value.trim();
    let order = sort === 'product_name' ? 'asc' : 'desc';

    let url = `/api/products/list?sort=${sort}&order=${order}&limit=${LIMIT}&offset=${offset}`;
    if (gender) url += `&gender=${gender}`;
    if (search) url += `&search=${encodeURIComponent(search)}`;
    const color = document.getElementById('color-select').value;
    if (color) url += `&color=${encodeURIComponent(color)}`;
    const line = document.getElementById('line-select').value;
    if (line) url += `&product_line=${encodeURIComponent(line)}`;
    if (filterNew) url += `&is_new=true`;
    if (filterDiscount) url += `&has_discount=true`;

    try {
        const r = await fetch(url);
        const d = await r.json();
        if (d.status !== 'success') throw new Error(d.message);

        document.getElementById('table-meta').textContent = fmt(d.total) + ' sản phẩm tìm thấy';

        if (!d.products?.length) {
            c.innerHTML = '<div class="empty">Không tìm thấy sản phẩm nào</div>';
            document.getElementById('pager').style.display = 'none';
            return;
        }

        // Determine max sold for bar scaling
        const maxSold = Math.max(...d.products.map(p => p.quantity_sold || 0), 1);

        c.innerHTML = renderProductTable(d, maxSold);

        // Pagination
        const pg = document.getElementById('pager');
        pg.style.display = 'flex';
        document.getElementById('page-info').textContent = `${offset+1}–${Math.min(offset+d.products.length, d.total)} / ${fmt(d.total)}`;
        document.getElementById('btn-prev').disabled = offset === 0;
        document.getElementById('btn-next').disabled = offset + LIMIT >= d.total;

    } catch(e) {
        console.error('Products error:', e);
        c.innerHTML = `<div class="empty">Lỗi: ${e.message}</div>`;
    }
}

// ═══ ACTIONS ═══
function prevPage() { offset = Math.max(0, offset-LIMIT); loadProducts(); }
function nextPage() { offset += LIMIT; loadProducts(); }
function toggleFilter(type) {
    if (type === 'new') { filterNew = !filterNew; document.getElementById('btn-new').classList.toggle('active', filterNew); }
    if (type === 'discount') { filterDiscount = !filterDiscount; document.getElementById('btn-discount').classList.toggle('active', filterDiscount); }
    offset = 0; loadProducts();
}
function debouncedSearch() {
  clearTimeout(searchTimer);
  searchTimer = setTimeout(() => {
    offset = 0;
    // Auto-switch to relevance sort when searching
    const searchVal = document.getElementById('search-input').value.trim();
    const sortSel = document.getElementById('sort-select');
    if (searchVal && sortSel.value === 'quantity_sold') {
      sortSel.value = 'relevance';
    } else if (!searchVal && sortSel.value === 'relevance') {
      sortSel.value = 'quantity_sold';
    }
    loadProducts();
  }, 400);
}
async function loadAll() { await Promise.all([loadOverview(), loadProducts()]); }

// ═══ LOAD FILTER OPTIONS ═══
async function loadFilterOptions() {
    try {
        const r = await fetch('/api/products/filters');
        const d = await r.json();
        if (d.status !== 'success') return;

        // Populate color dropdown
        const colorSel = document.getElementById('color-select');
        (d.colors || []).forEach(c => {
            const opt = document.createElement('option');
            opt.value = c.master_color;
            // Extract Vietnamese part: "Đen/ Black" → "Đen"
            const vn = c.master_color.split('/')[0].trim();
            opt.textContent = `${vn} (${c.cnt})`;
            colorSel.appendChild(opt);
        });

        // Populate product line dropdown
        const lineSel = document.getElementById('line-select');
        (d.product_lines || []).forEach(l => {
            const opt = document.createElement('option');
            opt.value = l.product_line_vn;
            opt.textContent = `${l.product_line_vn} (${l.cnt})`;
            lineSel.appendChild(opt);
        });
    } catch(e) { console.error('Filters error:', e); }
}

// ═══ INIT ═══
async function initAll() {
    await loadFilterOptions();
    await Promise.all([loadOverview(), loadProducts()]);
}
initAll();