// ═══ Products List ═══
async function loadProducts() {
  const body = document.getElementById('tableBody');
  body.innerHTML = '<tr><td colspan="10" class="table-loading"><div class="spinner-sm"></div> Đang tải...</td></tr>';

  const search = document.getElementById('searchInput').value.trim();
  const status = document.getElementById('statusFilter').value;
  const line = document.getElementById('lineFilter').value;
  const tagName = document.getElementById('tagsFilter').value.trim();

  const params = new URLSearchParams({ limit: PAGE_SIZE, page: currentPage + 1 });
  if (search) params.set('search', search);
  if (status) params.set('status', status);
  if (line) params.set('product_line', line);
  if (tagName) params.set('tag', tagName);
  
  try {
    const parentUrl = new URL(window.parent.location);
    parentUrl.searchParams.set('p', currentPage + 1);
    window.parent.history.replaceState(null, '', parentUrl.toString());
  } catch(e) {}

  try {
    const res = await fetch(`${API}/list?${params}`);
    const data = await res.json();
    if (data.status !== 'success') throw new Error(data.message);

    currentProducts = data.products || [];
    renderTable(currentProducts);
    renderPagination(data.total);
  } catch (e) {
    body.innerHTML = `<tr><td colspan="10" class="table-loading" style="color:var(--error)">⚠️ ${e.message}</td></tr>`;
  }
}

function renderTable(products) {
  const body = document.getElementById('tableBody');
  if (!products.length) {
    body.innerHTML = '<tr><td colspan="10" class="table-loading">Không tìm thấy sản phẩm nào</td></tr>';
    return;
  }
  body.innerHTML = products.map(p => {
    const descStatus = p.desc_status;
    let statusHtml;
    if (descStatus === 1) {
      statusHtml = '<span class="status-badge done">✅ Đã duyệt</span>';
    } else if (descStatus === 0) {
      statusHtml = '<span class="status-badge pending">⏳ Chờ duyệt</span>';
    } else {
      statusHtml = '<span class="status-badge missing">✕ Chưa có</span>';
    }
    const price = p.sale_price ? Number(p.sale_price).toLocaleString('vi-VN') + '₫' : '—';
    const sold = p.quantity_sold ? Number(p.quantity_sold).toLocaleString() : '0';
    const imgSrc = p.product_image_url_thumbnail || '';
    const imgTag = imgSrc
      ? `<img src="${esc(imgSrc)}" alt="" onerror="this.style.display='none'">`
      : `<div style="width:44px;height:44px;border-radius:6px;background:var(--muted);display:flex;align-items:center;justify-content:center;font-size:16px;">📦</div>`;

    // Use magento_ref_code as the primary key for all actions
    const actionCode = esc(p.magento_ref_code || p.internal_ref_code || '');
    const colorBadge = p.master_color
      ? `<span style="background:#e0f2fe;border:1px solid #7dd3fc;padding:1px 6px;border-radius:8px;font-size:10px;color:#0369a1;">${esc(p.master_color)}</span>`
      : '';
    // Show if magento differs from internal (split variant)
    const isVariant = p.magento_ref_code && p.magento_ref_code !== p.internal_ref_code;
    const codeDisplay = isVariant
      ? `<div class="code" style="font-size:10px;">${esc(p.magento_ref_code || '')} ${colorBadge}</div><div style="font-size:9px;color:#94a3b8;">${esc(p.internal_ref_code || '')}</div>`
      : `<div class="code">${esc(p.magento_ref_code || p.internal_ref_code || '')} ${colorBadge}</div>`;

    return `<tr onclick="openDetail('${actionCode}', '${esc(p.product_name || '')}')">
      <td>
        <div class="product-cell">
          ${imgTag}
          <div class="info">
            <div class="name" title="${esc(p.product_name || '')}">${esc(p.product_name || '—')}</div>
            ${codeDisplay}
          </div>
        </div>
      </td>
      <td>${esc(p.product_line_vn || '—')}</td>
      <td style="max-width:180px; font-size:11px;">
        <div style="display: flex; flex-wrap: wrap; gap: 4px;">
          ${p.tags && p.tags.length > 0 ? p.tags.map(t => `<span style="background:#f1f5f9;border:1px solid #cbd5e1;padding:2px 6px;border-radius:12px;white-space:nowrap;">${esc(t)}</span>`).join('') : '<span style="color:#94a3b8">Chưa có</span>'}
        </div>
      </td>
      <td>${price}</td>
      <td>${sold}</td>
      <td>${statusHtml}</td>
      <td>${p.has_size_guide
        ? '<span style="color:#7c3aed;font-weight:700;font-size:14px" title="\u0110\u00e3 c\u00f3 size guide">\u2714</span>'
        : '<span style="color:#cbd5e1;font-size:14px" title="Ch\u01b0a c\u00f3">\u2014</span>'
      }</td>
      <td style="font-size:11px;color:#64748b;white-space:nowrap">${p.updated_at ? new Date(p.updated_at).toLocaleDateString('vi-VN') + ' ' + new Date(p.updated_at).toLocaleTimeString('vi-VN',{hour:'2-digit',minute:'2-digit'}) : '\u2014'}</td>
      <td>${descStatus >= 0
        ? (descStatus === 1
          ? `<button class="btn btn-sm" style="background:#dc3545;color:#fff;border:none;font-size:11px;padding:4px 10px" onclick="event.stopPropagation();approveRow('${actionCode}',0,this)">✕ Hủy</button>`
          : `<button class="btn btn-sm" style="background:#28a745;color:#fff;border:none;font-size:11px;padding:4px 10px" onclick="event.stopPropagation();approveRow('${actionCode}',1,this)">✓ Duyệt</button>`)
        : '<span style="color:var(--muted-fg);font-size:11px">—</span>'
      }</td>
      <td>
        <div style="display:flex;gap:4px;flex-direction:column;">
          <button class="btn btn-outline-dark btn-sm" onclick="event.stopPropagation();generateSingle('${actionCode}','${esc(p.product_name || '')}',this)">Desc</button>
          <button class="btn btn-outline-dark btn-sm" onclick="event.stopPropagation();generateSingleTags('${actionCode}','${esc(p.product_name || '')}',this)">Tags</button>
          <button class="btn btn-sm" style="background:#7c3aed;color:#fff;border:none;padding:2px 5px;font-size:11px;" onclick="event.stopPropagation();generateSingleSize('${actionCode}','${esc(p.product_name || '')}',this)">📏 Size</button>
          <button class="btn btn-primary btn-sm" style="background:#0ea5e9; border:none; padding:2px 5px;" onclick="event.stopPropagation();openNativeBulkAiModal('${actionCode}')">🤖 Edit</button>
        </div>
      </td>
    </tr>`;
  }).join('');
}

function renderPagination(total) {
  const pages = Math.ceil(total / PAGE_SIZE);
  const el = document.getElementById('pagination');
  if (pages <= 1) { el.innerHTML = ''; return; }
  let html = `<button ${currentPage===0?'disabled':''} onclick="currentPage--;loadProducts()">← Trước</button>`;
  const start = Math.max(0, currentPage - 3);
  const end = Math.min(pages, start + 7);
  for (let i = start; i < end; i++) {
    html += `<button class="${i===currentPage?'active':''}" onclick="currentPage=${i};loadProducts()">${i+1}</button>`;
  }
  html += `<button ${currentPage>=pages-1?'disabled':''} onclick="currentPage++;loadProducts()">Sau →</button>`;
  el.innerHTML = html;
}

