// ═══ SIZE GUIDE ENRICHMENT ═══
async function generateSingleSize(code, name, btn) {
  const ogText = btn.textContent;
  btn.innerHTML = '<span class="spinner-sm"></span>';
  btn.disabled = true;

  try {
    const res = await fetch('/api/bulk/enrich-size-single', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ internal_ref_code: code }),
    });
    const data = await res.json();
    if (data.status === 'error') throw new Error(data.message);

    alert(`✅ Đã sinh Size Guide cho ${data.name || code}!\n\nSize: ${JSON.stringify(data.size_scale)}\n\nClick vào sản phẩm để xem chi tiết.`);
    
    // Refresh the detail if it's open
    if (currentDetailCode === code) {
      openDetail(code, name);
    }
  } catch (e) {
    alert('❌ Lỗi: ' + e.message);
  } finally {
    btn.textContent = ogText;
    btn.disabled = false;
  }
}

async function batchEnrichSize() {
  // First get stats
  try {
    const statsRes = await fetch('/api/bulk/size-stats');
    const stats = await statsRes.json();
    if (stats.status !== 'success') throw new Error(stats.message);

    if (stats.needs_enrichment <= 0) {
      alert('🎉 Tất cả sản phẩm đã có hướng dẫn size!');
      return;
    }

    if (!confirm(`📏 Phát hiện ${stats.needs_enrichment} sản phẩm cần bơm Size Guide AI.\n\n` +
      `Tổng matched: ${stats.matched_products}\n` +
      `Đã có size guide: ${stats.has_size_guide}\n` +
      `Cần bơm: ${stats.needs_enrichment}\n\n` +
      `Bấm OK để chạy batch AI (ngầm)?`)) return;

    const btn = document.getElementById('btnBatchSize');
    const ogText = btn.innerHTML;
    btn.innerHTML = '<div class="spinner-sm"></div> Đang gửi...';
    btn.disabled = true;

    const res = await fetch('/api/bulk/enrich-size-batch', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ codes: [] }) // Empty = all needing enrichment
    });
    const data = await res.json();
    if (data.status === 'error') throw new Error(data.message);

    alert(`✅ ${data.message}`);
    btn.innerHTML = ogText;
    btn.disabled = false;

  } catch (e) {
    alert('❌ Lỗi: ' + e.message);
    const btn = document.getElementById('btnBatchSize');
    if (btn) { btn.innerHTML = '📏 Bơm Size Guide'; btn.disabled = false; }
  }
}

