// Stock loader - fetches stock per product_color_code with per-size breakdown
async function fetchStock() {
    const cells = document.querySelectorAll('.td-stock[data-code]');
    if (!cells.length) return;
    const codeSet = new Set();
    cells.forEach(function(el) { if (el.dataset.code) codeSet.add(el.dataset.code); });
    const codes = Array.from(codeSet).join(',');
    try {
        const r = await fetch('/api/stock/check', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({codes: codes, max_skus: 500, chunk_size: 50, timeout_sec: 15})
        });
        const d = await r.json();
        if (d.status !== 'success') return;

        // Aggregate stock by product_color_code with per-size detail
        var stockMap = {};
        (d.stock_responses || []).forEach(function(resp) {
            (resp.result || []).forEach(function(item) {
                var parts = item.sku.split('-');
                var size = parts[parts.length - 1];
                var 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};
            });
        });

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

        cells.forEach(function(el) {
            var code = el.dataset.code;
            var info = stockMap[code];
            if (!info) { el.innerHTML = '<span style="color:var(--f);font-size:10px">\u2014</span>'; return; }

            var qty = info.total;
            var color = qty > 20 ? 'var(--green)' : qty > 0 ? 'var(--gold)' : 'var(--red)';
            var icon = qty > 20 ? '\u2705' : qty > 0 ? '\u26A0\uFE0F' : '\u274C';

            // Sort sizes
            var sortedSizes = Object.keys(info.sizes).sort(function(a, b) {
                var ia = sizeOrder.indexOf(a), ib = sizeOrder.indexOf(b);
                return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib);
            });

            // Build size chips
            var sizeHtml = sortedSizes.map(function(sz) {
                var s = info.sizes[sz];
                var sc = s.qty > 10 ? 'var(--green)' : s.qty > 0 ? 'var(--gold)' : 'var(--red)';
                var 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;margin:1px;border-radius:4px;font-size:10px;font-weight:600;background:' + bg + ';color:' + sc + ';border:1px solid ' + sc + '">' + sz + ': ' + s.qty + '</span>';
            }).join('');

            var detailId = 'stk_' + code.replace(/[^a-zA-Z0-9]/g, '_');

            el.innerHTML =
                '<div onclick="var dd=document.getElementById(\'' + detailId + '\');dd.style.display=dd.style.display===\'none\'?\'flex\':\'none\'" style="cursor:pointer">' +
                    '<span style="color:' + color + ';font-weight:700;font-size:13px">' + icon + ' ' + qty + '</span>' +
                    '<span style="color:var(--f);font-size:9px;margin-left:3px">\u25BC</span>' +
                '</div>' +
                '<div id="' + detailId + '" style="display:none;flex-wrap:wrap;gap:2px;margin-top:4px;max-width:220px">' + sizeHtml + '</div>';
        });
    } catch(e) {
        console.error('Stock error:', e);
        cells.forEach(function(el) { el.innerHTML = '<span style="color:var(--f)">err</span>'; });
    }
}
