// --- Clean Data Tab Logic ---
function goToCleanData() {
  closeDetail();
  switchTab('cleanData');
  
  document.getElementById('cleanDataSearch').value = currentDetailCode || '';
  renderCleanDataForm();
}

async function loadCleanDataForInput() {
  const code = document.getElementById('cleanDataSearch').value.trim();
  if(!code) return alert("Nhập mã sản phẩm!");
  
  document.getElementById('cleanDataEditor').innerHTML = '<div class="table-loading"><div class="spinner-sm"></div> Đang tải...</div>';
  document.getElementById('cleanDataEditor').style.display = 'block';
  document.getElementById('cleanDataEmpty').style.display = 'none';
  
  try {
    const res = await fetch(`${API}/saved/${encodeURIComponent(code)}`);
    if (res.ok) {
      const saved = await res.json();
      if (saved.status === 'success' && saved.description) {
        window.currentDetailDataForCleanTab = { 
          data: saved.description.description_data,
          description: saved.description
        };
        window.currentDetailNameForCleanTab = saved.description.product_name || `Sản phẩm ${code}`;
        currentDetailCode = code;
        renderCleanDataForm();
        return;
      }
    }
    alert("Không tìm thấy dữ liệu cho mã này. Hãy generate trước ở tab Sản phẩm.");
    document.getElementById('cleanDataEditor').style.display = 'none';
    document.getElementById('cleanDataEmpty').style.display = 'block';
  } catch (e) { alert("Lỗi khi tải dữ liệu"); }
}

function renderCleanDataForm() {
  const data = window.currentDetailDataForCleanTab;
  const name = window.currentDetailNameForCleanTab;
  if(!data) return;
  
  document.getElementById('cleanDataEmpty').style.display = 'none';
  document.getElementById('cleanDataEditor').style.display = 'block';
  document.getElementById('cleanDataTitle').style.display = 'block';
  document.getElementById('btnSaveCleanData').style.display = 'inline-block';
  
  const c = data.description || {};
  const d = data.description?.description_data || data.data || {};
  document.getElementById('cleanDataTitle').innerHTML = `Đang chỉnh sửa: <span style="color:#000;">${name || c.internal_ref_code || currentDetailCode}</span> (${currentDetailCode})`;
  
  const editBody = document.getElementById('cleanDataEditor');
  let editHtml = `<div style="display:flex; flex-direction:column; gap:16px;">`;
  
  const orderedKeys = ['ten_san_pham', 'tagline', 'mo_ta_chinh', 'phong_cach', 'chat_lieu', 'tinh_nang_vai', 'huong_dan_bao_quan'];
  const allKeys = Object.keys(d);
  const remainingKeys = allKeys.filter(k => !orderedKeys.includes(k)).sort();
  const sortedKeys = [...orderedKeys.filter(k => allKeys.includes(k)), ...remainingKeys];
  
  sortedKeys.forEach(k => {
    editHtml += `
      <div style="background:#fff; border:1px solid #e5e7eb; border-radius:8px; padding:16px;">
        <label style="display:block; font-size:13px; font-weight:700; color:var(--primary); margin-bottom:8px; text-transform:uppercase;">${esc(k)} <button onclick="deleteField('${k}')" style="float:right; border:none; background:none; color:var(--warn); cursor:pointer; font-size:11px; font-weight:bold;">✕ Xóa trường này</button></label>
        <textarea id="editField_${k}" data-key="${k}" style="width:100%; box-sizing:border-box; border:1px solid #d1d5db; border-radius:6px; padding:10px; font-size:14px; font-family:inherit; min-height:60px; line-height:1.5; resize:vertical;">${esc(d[k] || '')}</textarea>
      </div>`;
  });
  
  editHtml += `
      <div style="background:#f0f9ff; border:2px dashed #bae6fd; border-radius:8px; padding:16px; margin-top:12px;">
        <label style="display:block; font-size:13px; font-weight:700; color:#0369a1; margin-bottom:10px;">➕ BỔ SUNG TRƯỜNG MỚI</label>
        <div style="display:flex; gap:10px;">
          <input type="text" id="newFieldKey" placeholder="Tên key (vd: dac_diem_noi_bat)" style="flex:1; border:1px solid #bae6fd; border-radius:6px; padding:10px; font-size:14px; outline:none;">
          <input type="text" id="newFieldValue" placeholder="Nội dung" style="flex:2; border:1px solid #bae6fd; border-radius:6px; padding:10px; font-size:14px; outline:none;">
          <button class="btn btn-sm" style="background:#0284c7;color:#fff;border:none;font-weight:bold;padding:0 20px;" onclick="addNewField()">Thêm</button>
        </div>
      </div>
  </div>`;
  editBody.innerHTML = editHtml;
}

function getSafeDetailData() {
  if (window.currentDetailDataForCleanTab) {
    if (window.currentDetailDataForCleanTab.description && window.currentDetailDataForCleanTab.description.description_data) return window.currentDetailDataForCleanTab.description.description_data;
    if (window.currentDetailDataForCleanTab.data) return window.currentDetailDataForCleanTab.data;
  }
  return {};
}

function gatherInputsIntoData() {
  const inputs = document.querySelectorAll('#cleanDataEditor textarea[data-key]');
  const d = getSafeDetailData();
  inputs.forEach(el => { d[el.getAttribute('data-key')] = el.value; });
  return d;
}

function deleteField(key) {
  if (!confirm(`Xóa trường [${key}]?`)) return;
  const d = gatherInputsIntoData();
  delete d[key];
  renderCleanDataForm();
}

function addNewField() {
  const k = document.getElementById('newFieldKey').value.trim();
  const v = document.getElementById('newFieldValue').value.trim();
  if (!k) return alert('Phải nhập Tên key!');
  const safe_k = k.toLowerCase().replace(/[^a-z0-9_]/g, '_');
  
  const d = gatherInputsIntoData();
  d[safe_k] = v;
  renderCleanDataForm();
}

async function saveDetailEdit() {
  if (!currentDetailCode) return;
  const btn = document.getElementById('btnSaveCleanData');
  const orgText = btn.textContent;
  btn.textContent = 'Đang lưu...';
  btn.disabled = true;
  
  try {
    const newData = gatherInputsIntoData();

    // Send update request
    const res = await fetch(`${API}/saved/${currentDetailCode}/update`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ description_data: newData })
    });
    const data = await res.json();
    if (data.status === 'error') throw new Error(data.message);
    
    btn.textContent = '✓ Lưu thành công!';

    // Re-fetch fresh data from server to refresh in-memory state correctly
    // (avoids shared-reference mutation bugs that made the form appear blank)
    try {
      const freshRes = await fetch(`${API}/saved/${encodeURIComponent(currentDetailCode)}`);
      const freshJson = await freshRes.json();
      if (freshJson.status === 'success' && freshJson.description) {
        window.currentDetailDataForCleanTab = {
          data: freshJson.description.description_data,
          description: freshJson.description,
        };
        renderCleanDataForm();
      }
    } catch (_) { /* non-critical — form already saved, just show stale data */ }

    // Refresh main table
    loadProducts();
    loadOverview();

    setTimeout(() => { btn.textContent = orgText; btn.disabled = false; }, 2000);

  } catch (e) {
    alert('Lỗi lưu thay đổi: ' + e.message);
    btn.textContent = '💾 Lưu';
    btn.disabled = false;
  }
}


function copyDetailJson() {
  if (!currentDetail) return;
  const text = currentDetail.description?.rendered_text || "";
  if (!text) {
    alert("Chưa có Nội dung chuẩn để copy. Hãy lưu lại trước.");
    return;
  }
  navigator.clipboard.writeText(text);
  const btn = document.getElementById('btnCopyJson');
  const og = btn.textContent;
  btn.textContent = '✓ Đã copy!';
  btn.style.borderColor = 'var(--success)';
  btn.style.color = 'var(--success)';
  setTimeout(() => { btn.textContent = og; btn.style.borderColor = ''; btn.style.color = ''; }, 2000);
}

