// ═══ Generate Single Tags ═══
async function generateSingleTags(code, name, btn) {
  const ogText = btn.textContent;
  btn.innerHTML = '<span class="spinner-sm"></span>';
  btn.disabled = true;

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

    // Update local state and re-render table row
    const p = currentProducts.find(x => x.internal_ref_code === code);
    if (p) {
      if (data.tags) {
         p.tags = data.tags;
      } else {
         alert(data.message || "Đã gửi yêu cầu tạo Tags.");
      }
      renderTable(currentProducts);
    }
  } catch (e) {
    alert('Lỗi: ' + e.message);
  } finally {
    btn.textContent = ogText;
    btn.disabled = false;
  }
}

// ═══ Batch Generate TAGS ═══
async function batchGenerateTags() {
  if (!confirm(`Hệ thống sẽ chạy AI đọc toàn bộ clean_description (mô tả chuẩn) để tự động móc Tags (đi chơi, đi làm, thể thao...).\\nChỉ quét 500 SP đang trống tags.\\n\\nBạn có chắc chắn muốn bắt đầu?`)) return;

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

  try {
    const res = await fetch(`/api/bulk/batch-generate-tags`, { method: 'POST' });
    const data = await res.json();
    if (data.status === 'error') throw new Error(data.message);

    alert(data.message);
    startTagsBatchPolling();
  } catch (e) {
    alert('Lỗi bơm tags hàng loạt: ' + e.message);
  } finally {
    btn.innerHTML = ogText;
    btn.disabled = false;
  }
}

let tagsPollInterval = null;
function startTagsBatchPolling() {
  if (tagsPollInterval) return; 
  document.getElementById('tagsTrackingBox').style.display = 'flex';
  
  tagsPollInterval = setInterval(async () => {
    try {
      const res = await fetch(`/api/bulk/tags-batch-status`);
      const data = await res.json();
      
      if (!data.progress || !data.progress.is_running) {
        clearInterval(tagsPollInterval);
        tagsPollInterval = null;
        document.getElementById('tagsTrackTitle').innerText = '✅ Hoàn tất Auto-Tagging!';
        document.getElementById('tagsTrackFill').style.background = '#059669';
        setTimeout(() => {
          document.getElementById('tagsTrackingBox').style.display = 'none';
          loadProducts(); // refresh list to show new tags
        }, 5000);
        return;
      }
      
      const prog = data.progress;
      const pct = Math.round((prog.done / prog.total) * 100) || 0;
      document.getElementById('tagsTrackTitle').innerText = 'Hệ thống đang Auto-Tagging hàng loạt...';
      document.getElementById('tagsTrackFill').style.background = '#10b981';
      document.getElementById('tagsTrackText').innerText = `${prog.done} / ${prog.total} (${pct}%)`;
      document.getElementById('tagsTrackFill').style.width = pct + '%';
      document.getElementById('tagsTrackCode').innerText = prog.current_code || '—';
      document.getElementById('tagsTrackErrors').innerText = prog.errors || 0;
      
    } catch(e) {
      console.error("Lỗi poll status tags:", e);
    }
  }, 2000);
}

// 🏷️ DIRECT TAGS — Batch tagging thẳng PostgreSQL (không Redis/Worker)
let _directTagsPoller = null;

async function runTagsDirect() {
  const isForceAll = confirm('Bạn muốn Bơm Tags cho TẤT CẢ sản phẩm (OK) hay CHỈ SẢN PHẨM THIẾU TAGS (Cancel)?');
  
  const btn = document.getElementById('btnBatchTagsDirect');
  const ogText = btn.innerHTML;
  btn.innerHTML = '<div class="spinner-sm"></div> Đang gửi...';
  btn.disabled = true;

  try {
    const res = await fetch(`/api/tags-direct/run?force_all=${isForceAll}`, { method: 'POST' });
    const data = await res.json();
    if (res.status === 409) {
      alert(data.message);
      _startDirectTagsPoller();
    } else if (data.status === 'success') {
      alert(data.message);
      _startDirectTagsPoller();
    } else {
      throw new Error(data.message);
    }
  } catch (e) {
    alert('Lỗi bơm tags (Direct): ' + e.message);
  } finally {
    btn.innerHTML = ogText;
    btn.disabled = false;
  }
}

function _startDirectTagsPoller() {
  if (_directTagsPoller) return;
  document.getElementById('tagsTrackingBox').style.display = 'flex';
  
  _directTagsPoller = setInterval(async () => {
    try {
      const res = await fetch('/api/tags-direct/status');
      const data = await res.json();
      
      if (!data.is_running) {
        clearInterval(_directTagsPoller);
        _directTagsPoller = null;
        document.getElementById('tagsTrackTitle').innerText = '✅ Hoàn tất Direct Tagging!';
        document.getElementById('tagsTrackFill').style.background = '#059669';
        setTimeout(() => {
          document.getElementById('tagsTrackingBox').style.display = 'none';
          loadProducts(); 
        }, 5000);
        return;
      }
      
      const pct = data.total > 0 ? Math.round((data.done / data.total) * 100) : 0;
      document.getElementById('tagsTrackTitle').innerText = 'Hệ thống đang Direct Tagging...';
      document.getElementById('tagsTrackFill').style.background = '#f59e0b'; // orange for direct
      document.getElementById('tagsTrackText').innerText = `${data.done} / ${data.total} (${pct}%)`;
      document.getElementById('tagsTrackFill').style.width = pct + '%';
      document.getElementById('tagsTrackCode').innerText = data.current_code ? `→ ${data.current_code}` : '—';
      document.getElementById('tagsTrackErrors').innerText = data.errors || 0;
      
    } catch(e) {
      console.error('Lỗi poll status tags direct:', e);
    }
  }, 2000);
}

// Auto resume polling if page refreshed
setTimeout(() => {
  fetch('/api/tags-direct/status')
    .then(r => r.json())
    .then(s => {
      if (s.is_running) _startDirectTagsPoller();
    })
    .catch(()=>{});
}, 1000);
