// Product table rendering - grouped by internal_ref_code
// Replaces inline rendering in product.html

function renderProductTable(d, maxSold) {
    // Smart search: detect if relevance scores are available
    const hasRelevance = d.sort === 'relevance' && d.products.some(p => p.relevance_score != null);
    const searchInput = document.getElementById('search-input');
    const searchTerm = searchInput ? searchInput.value.trim().toLowerCase() : '';

    let html = `<table><thead><tr>
        <th>Sản phẩm</th>${hasRelevance ? '<th>🎯</th>' : ''}<th>Giá bán</th><th>Giảm giá</th>
        <th>Đã bán</th><th>Màu sắc</th><th>Dòng SP</th><th>Giới tính</th><th>Link</th>
    </tr></thead><tbody>`;

    for (const p of d.products) {
        const e = emoji(p.product_line_vn);
        const hasImg = !!p.product_image_url_thumbnail;
        const imgHtml = hasImg
            ? `<img class="td-thumb" src="${p.product_image_url_thumbnail}" alt="" loading="lazy" onerror="this.outerHTML='<div class=\\'td-swatch\\' style=\\'background:var(--s2)\\'>${e}</div>'">`
            : `<div class="td-swatch" style="background:var(--s2)">${e}</div>`;

        const discount = p.discount_percent > 0
            ? `<span class="td-badge" style="background:var(--red-l);color:var(--red)">-${p.discount_percent}%</span>`
            : `<span style="color:var(--f)">—</span>`;

        const soldPct = Math.min((p.quantity_sold||0)/maxSold*100, 100);
        const soldColor = soldPct > 50 ? 'var(--green)' : soldPct > 20 ? 'var(--gold)' : 'var(--f)';
        const soldBar = `<div class="td-bar-wrap"><div class="td-bar" style="width:${soldPct}%;background:${soldColor}"></div></div><b>${fmt(p.quantity_sold||0)}</b>`;

        const gLabel = p.gender_by_product === 'men' ? '👨 Nam'
            : p.gender_by_product === 'women' ? '👩 Nữ'
            : p.gender_by_product === 'unisex' ? '🧑 Uni'
            : p.gender_by_product || '—';

        const link = p.product_web_url
            ? `<a href="${p.product_web_url}" target="_blank" class="td-link">Xem ↗</a>` : '—';

        const newTag = p.is_new_product
            ? ' <span class="td-badge" style="background:var(--blue-l);color:var(--blue)">NEW</span>' : '';

        // Size chips
        const sizeChips = p.size_scale
            ? `<div style="margin-top:3px;display:flex;gap:3px;flex-wrap:wrap">${p.size_scale.split('|').map(s =>
                `<span style="display:inline-block;padding:1px 6px;border-radius:4px;font-size:9px;font-weight:700;background:var(--bg);color:var(--m);border:1px solid var(--b)">${s.trim()}</span>`
            ).join('')}</div>` : '';

        // Color count badge with click to expand
        const colorCount = p.color_count || 1;
        const colorBadge = `<span class="color-expand-btn" data-code="${p.internal_ref_code}" onclick="toggleColors('${p.internal_ref_code}', this)" style="cursor:pointer;display:inline-flex;align-items:center;gap:4px;padding:4px 10px;border-radius:6px;font-size:11px;font-weight:700;background:var(--gold-l);color:var(--gold);border:1px solid var(--gold);transition:all .2s">🎨 ${colorCount} màu ▼</span>`;

        // Highlight search term in product name
        let displayName = p.product_name || 'N/A';
        if (searchTerm && displayName.toLowerCase().includes(searchTerm)) {
            const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
            displayName = displayName.replace(regex, '<mark style="background:#fef08a;color:#854d0e;border-radius:2px;padding:0 2px">$1</mark>');
        }

        // Relevance score badge
        let relevanceBadge = '';
        if (hasRelevance && p.relevance_score != null) {
            const score = p.relevance_score;
            const sc = score >= 90 ? 'var(--green)' : score >= 50 ? 'var(--gold)' : 'var(--f)';
            const bg = score >= 90 ? 'rgba(22,163,74,.1)' : score >= 50 ? 'rgba(234,179,8,.1)' : 'var(--s)';
            const label = score >= 90 ? '🎯' : score >= 70 ? '✓' : '~';
            relevanceBadge = `<td><span style="display:inline-block;padding:3px 8px;border-radius:6px;font-size:11px;font-weight:700;background:${bg};color:${sc};border:1px solid ${sc}">${label} ${score}</span></td>`;
        }

        const colSpan = hasRelevance ? 9 : 8;

        html += `<tr>
            <td><div class="td-product">${imgHtml}<div>
                <div class="td-name">${displayName}${newTag}</div>
                <div class="td-sku"><b>${p.internal_ref_code||''}</b></div>
                ${sizeChips}
            </div></div></td>
            ${hasRelevance ? relevanceBadge : ''}
            <td><b style="font-family:'Fraunces',serif;font-size:13px">${fmtK(p.sale_price)}₫</b>${p.original_price > p.sale_price ? `<br><span style="font-size:9px;color:var(--f);text-decoration:line-through">${fmtK(p.original_price)}₫</span>` : ''}</td>
            <td>${discount}</td>
            <td>${soldBar}</td>
            <td>${colorBadge}</td>
            <td><span class="td-badge" style="background:var(--purple-l);color:var(--purple)">${p.product_line_vn||'—'}</span></td>
            <td style="font-size:10px">${gLabel}</td>
            <td>${link}</td>
        </tr>
        <tr id="colors-${p.internal_ref_code}" style="display:none">
            <td colspan="${colSpan}" style="padding:0;background:var(--bg)">
                <div id="colors-content-${p.internal_ref_code}" style="padding:12px 16px 12px 70px">
                    <span style="color:var(--f);font-size:11px">⏳ Đang tải màu sắc...</span>
                </div>
            </td>
        </tr>`;
    }
    html += '</tbody></table>';
    return html;
}

// Toggle color variants for a product
async function toggleColors(code, btn) {
    const row = document.getElementById('colors-' + code);
    if (!row) return;

    if (row.style.display !== 'none') {
        row.style.display = 'none';
        btn.innerHTML = '🎨 ' + btn.innerHTML.match(/\d+/)[0] + ' màu ▼';
        return;
    }

    row.style.display = '';
    btn.innerHTML = '🎨 ' + btn.innerHTML.match(/\d+/)[0] + ' màu ▲';

    const container = document.getElementById('colors-content-' + code);

    // Check if already loaded
    if (container.dataset.loaded) return;

    try {
        // Fetch color variants from API
        const r = await fetch(`/api/products/colors?code=${encodeURIComponent(code)}`);
        const d = await r.json();
        if (d.status !== 'success' || !d.variants?.length) {
            container.innerHTML = '<span style="color:var(--f)">Không có dữ liệu</span>';
            return;
        }

        // Also fetch stock for all color codes
        const colorCodes = d.variants.map(v => v.product_color_code).join(',');
        let stockMap = {};
        try {
            const sr = await fetch('/api/stock/check', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({codes: code, max_skus: 500, chunk_size: 50, timeout_sec: 15})
            });
            const sd = await sr.json();
            if (sd.status === 'success') {
                (sd.stock_responses || []).forEach(resp => {
                    (resp.result || []).forEach(item => {
                        const parts = item.sku.split('-');
                        const size = parts[parts.length - 1];
                        const colorCode = parts.slice(0, -1).join('-');
                        if (!stockMap[colorCode]) stockMap[colorCode] = {total: 0, sizes: {}};
                        stockMap[colorCode].total += (item.qty || 0);
                        stockMap[colorCode].sizes[size] = {qty: item.qty || 0, inStock: item.is_in_stock};
                    });
                });
            }
        } catch(e) { console.warn('Stock fetch error:', e); }

        const sizeOrder = ['XS','S','M','L','XL','XXL','2XL','3XL','100','110','120','130','140','150','160'];

        let html = '<div style="display:flex;flex-direction:column;gap:10px">';
        for (const v of d.variants) {
            const stock = stockMap[v.product_color_code];
            const totalQty = stock ? stock.total : 0;
            const qtyColor = totalQty > 20 ? 'var(--green)' : totalQty > 0 ? 'var(--gold)' : 'var(--red)';
            const qtyIcon = totalQty > 20 ? '✅' : totalQty > 0 ? '⚠️' : '❌';

            // Size breakdown chips
            let sizeHtml = '';
            if (stock && stock.sizes) {
                const sortedSizes = Object.keys(stock.sizes).sort((a, b) => {
                    const ia = sizeOrder.indexOf(a), ib = sizeOrder.indexOf(b);
                    return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib);
                });
                sizeHtml = sortedSizes.map(sz => {
                    const s = stock.sizes[sz];
                    const sc = s.qty > 10 ? 'var(--green)' : s.qty > 0 ? 'var(--gold)' : 'var(--red)';
                    const bg = s.qty > 10 ? 'rgba(22,163,74,.08)' : s.qty > 0 ? 'rgba(234,179,8,.08)' : 'rgba(220,38,38,.08)';
                    return `<span style="display:inline-block;padding:2px 6px;border-radius:4px;font-size:10px;font-weight:600;background:${bg};color:${sc};border:1px solid ${sc}">${sz}: ${s.qty}</span>`;
                }).join(' ');
            }

            const imgUrl = v.product_image_url_thumbnail;
            const imgTag = imgUrl
                ? `<img src="${imgUrl}" style="width:40px;height:40px;border-radius:6px;object-fit:cover;border:1px solid var(--b)" loading="lazy">`
                : `<div style="width:40px;height:40px;border-radius:6px;background:var(--s2);display:flex;align-items:center;justify-content:center;font-size:14px">🎨</div>`;

            html += `<div style="display:flex;align-items:flex-start;gap:12px;padding:10px 14px;background:var(--s);border-radius:8px;border:1px solid var(--b)">
                ${imgTag}
                <div style="flex:1;min-width:0">
                    <div style="display:flex;align-items:center;gap:8px;margin-bottom:4px">
                        <b style="font-family:'JetBrains Mono',monospace;font-size:12px">${v.product_color_code}</b>
                        <span style="font-size:11px;color:var(--m)">· ${v.master_color || ''}</span>
                        <span style="font-size:11px;color:var(--m)">${v.product_color_name || ''}</span>
                    </div>
                    <div style="display:flex;align-items:center;gap:6px;margin-bottom:4px">
                        <span style="font-weight:700;color:${qtyColor};font-size:13px">${qtyIcon} Tồn: ${totalQty}</span>
                        <span style="color:var(--f);font-size:10px">| Đã bán: ${fmt(v.quantity_sold || 0)}</span>
                    </div>
                    <div style="display:flex;flex-wrap:wrap;gap:4px">${sizeHtml || '<span style="color:var(--f);font-size:10px">Chưa có dữ liệu tồn kho</span>'}</div>
                </div>
            </div>`;
        }
        html += '</div>';
        container.innerHTML = html;
        container.dataset.loaded = 'true';

    } catch(e) {
        console.error('Colors error:', e);
        container.innerHTML = `<span style="color:var(--red)">❌ Lỗi: ${e.message}</span>`;
    }
}
