// ═══ Tabs & Fields ═══
let currentTab = 'products';

function switchTab(tab) {
  currentTab = tab;
  document.getElementById('tabProducts').className = tab === 'products' ? 'tab-btn active' : 'tab-btn';
  document.getElementById('tabProducts').style.borderBottomColor = tab === 'products' ? 'var(--primary)' : 'transparent';
  document.getElementById('tabProducts').style.color = tab === 'products' ? 'var(--primary)' : 'var(--muted-fg)';
  
  document.getElementById('tabFields').className = tab === 'fields' ? 'tab-btn active' : 'tab-btn';
  document.getElementById('tabFields').style.borderBottomColor = tab === 'fields' ? 'var(--primary)' : 'transparent';
  document.getElementById('tabFields').style.color = tab === 'fields' ? 'var(--primary)' : 'var(--muted-fg)';

  const tabCleanData = document.getElementById('tabCleanData');
  if (tabCleanData) {
    tabCleanData.className = tab === 'cleanData' ? 'tab-btn active' : 'tab-btn';
    tabCleanData.style.borderBottomColor = tab === 'cleanData' ? 'var(--primary)' : 'transparent';
    tabCleanData.style.color = tab === 'cleanData' ? 'var(--primary)' : 'var(--muted-fg)';
  }
  
  document.getElementById('sectionProducts').style.display = tab === 'products' ? 'block' : 'none';
  document.getElementById('sectionFields').style.display = tab === 'fields' ? 'block' : 'none';
  document.getElementById('sectionCleanData').style.display = tab === 'cleanData' ? 'block' : 'none';
  
  if (tab === 'fields') {
    loadFields();
  } else {
    loadProducts();
  }
}

async function loadFields() {
  const tbody = document.getElementById('fieldsTableBody');
  tbody.innerHTML = '<tr><td colspan="5" class="table-loading"><div class="spinner-sm"></div> Đang tải...</td></tr>';
  try {
    const res = await fetch(`${API}/fields`);
    const data = await res.json();
    if (data.status !== 'success') throw new Error(data.message);
    
    if (data.data.length === 0) {
      tbody.innerHTML = '<tr><td colspan="5" class="table-loading">Chưa có cấu hình trường nào.</td></tr>';
      return;
    }
    
    tbody.innerHTML = data.data.map((f, i) => `
      <tr style="opacity: ${f.is_active ? '1' : '0.5'}">
        <td style="font-family:var(--font-mono); font-size:12px; font-weight:600;">${esc(f.field_key)}</td>
        <td style="font-weight:600;">${esc(f.field_label)}</td>
        <td style="font-size:12px; color:var(--secondary-fg);">${esc(f.field_instruction)}</td>
        <td>
          <button class="btn btn-sm" style="background:${f.is_active ? '#28a745' : '#6c757d'}; color:#fff; border:none;" onclick="toggleField('${f.field_key}', ${!f.is_active})">${f.is_active ? 'Bật' : 'Tắt'}</button>
        </td>
        <td>
          <button class="btn btn-outline btn-sm" onclick="deleteField('${f.field_key}')" style="color:var(--warn); border-color:var(--warn);">Xóa</button>
        </td>
      </tr>
    `).join('');
  } catch (e) {
    tbody.innerHTML = `<tr><td colspan="5" class="table-loading" style="color:var(--warn)">Lỗi: ${esc(e.message)}</td></tr>`;
  }
}

async function toggleField(key, newStatus) {
  try {
    const res = await fetch(`${API}/fields/${key}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ is_active: newStatus }),
    });
    const data = await res.json();
    if (data.status !== 'success') throw new Error(data.message);
    loadFields();
  } catch (e) {
    alert('Lỗi: ' + e.message);
  }
}

async function deleteField(key) {
  if (!confirm(`Bạn có chắc chắn muốn xóa trường ${key}?`)) return;
  try {
    const res = await fetch(`${API}/fields/${key}`, { method: 'DELETE' });
    const data = await res.json();
    if (data.status !== 'success') throw new Error(data.message);
    loadFields();
  } catch (e) {
    alert('Lỗi: ' + e.message);
  }
}

async function showFieldForm() {
  const key = prompt('Nhập Key (viết liền không dấu, VD: chat_lieu_moi):');
  if (!key) return;
  const label = prompt('Nhập Label hiển thị:');
  if (!label) return;
  const instruction = prompt('Nhập Prompt (hướng dẫn AI sinh dữ liệu cho trường này):');
  
  try {
    const res = await fetch(`${API}/fields`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ field_key: key, field_label: label, field_instruction: instruction || '' }),
    });
    const data = await res.json();
    if (data.status !== 'success') throw new Error(data.message);
    loadFields();
  } catch (e) {
    alert('Lỗi: ' + e.message);
  }
}

