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

  try {
    const res = await fetch(`${API}/generate`, {
      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);

    currentDetail = data;
    currentDetailCode = code;
    showDetailPanel(data, name);

    // Update local state and re-render table row
    const p = currentProducts.find(x => x.internal_ref_code === code);
    if (p) {
      p.desc_status = 0; // Chờ duyệt
      renderTable(currentProducts);
    }
    loadOverview(); // Cập nhật lại board thống kê ở trên cùng
  } catch (e) {
    alert('Lỗi: ' + e.message);
  } finally {
    btn.textContent = ogText;
    btn.disabled = false;
  }
}

// ═══ Regenerate from Detail Modal ═══
async function regenerateFromDetail() {
  const code = currentDetailCode;
  if (!code) { alert('Không xác định được mã SP!'); return; }

  const btn = document.getElementById('btnRegenerate');
  const ogText = btn.textContent;
  btn.innerHTML = '<span class="spinner-sm"></span> Đang sinh...';
  btn.disabled = true;
  btn.style.opacity = '0.7';

  // Show loading in Clean tab
  const cleanBody = document.getElementById('detailBodyClean');
  cleanBody.innerHTML = '<div class="table-loading"><div class="spinner-sm"></div> AI đang sinh lại mô tả...<br><span style="font-size:11px;color:var(--muted-fg);">Thông thường mất 5-15 giây</span></div>';

  try {
    // Step 1: Call generate API (this saves to DB automatically)
    const genRes = await fetch(`${API}/generate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ magento_ref_code: code }),
    });
    const genData = await genRes.json();
    if (genData.status === 'error') throw new Error(genData.message);

    // Step 2: Re-fetch from /saved/ to get proper format (rendered_text, clean_description)
    const savedRes = await fetch(`${API}/saved/${encodeURIComponent(code)}`);
    const savedData = await savedRes.json();

    if (savedData.status === 'success' && savedData.description) {
      const desc = savedData.description;
      currentDetail = {
        phase: desc.phase,
        data: desc.description_data,
        saved: true,
        savedAt: desc.updated_at,
        descStatus: desc.status,
        description: desc
      };
      currentDetailCode = code;

      // Re-render modal with fresh content — stays open!
      showDetailPanel(currentDetail, desc.product_name || document.getElementById('detailTitle').textContent.split('(')[0].trim());
    } else {
      // Fallback: use generate response directly
      currentDetail = genData;
      currentDetailCode = code;
      const name = genData.product?.product_name || document.getElementById('detailTitle').textContent.split('(')[0].trim();
      showDetailPanel(genData, name);
    }

    // Update table row status
    const p = currentProducts.find(x => x.internal_ref_code === code);
    if (p) {
      p.desc_status = 0; // Chờ duyệt (vừa sinh mới)
      renderTable(currentProducts);
    }
    loadOverview();

  } catch (e) {
    cleanBody.innerHTML = `<div style="padding:24px;color:#dc3545;font-weight:600;">❌ Lỗi sinh lại: ${esc(e.message)}</div>`;
  } finally {
    btn.textContent = ogText;
    btn.disabled = false;
    btn.style.opacity = '1';
  }
}

// ═══ Detail Panel ═══
async function openDetail(code, name) {
  // Show loading state
  document.getElementById('detailTitle').textContent = name || 'Đang tải...';
  document.getElementById('detailBodyClean').innerHTML = '<div class="table-loading"><div class="spinner-sm"></div> Đang tải...</div>';
  document.getElementById('detailOverlay').classList.add('open');

  // Try to load saved description first
  try {
    const res = await fetch(`${API}/saved/${encodeURIComponent(code)}`);
    if (res.ok) {
      const saved = await res.json();
      if (saved.status === 'success' && saved.description) {
        const desc = saved.description;
        currentDetail = {
          phase: desc.phase,
          data: desc.description_data,
          saved: true,
          savedAt: desc.updated_at,
          descStatus: desc.status,
          description: desc
        };
        currentDetailCode = code;
        showDetailPanel(currentDetail, desc.product_name || name);
        return;
      }
    }
  } catch (e) { /* not found, will generate */ }

  // No saved description → generate new
  closeDetail();
  generateSingle(code, name, { textContent: '', innerHTML: '', disabled: false, closest: () => null });
}

function closeDetail() {
  document.getElementById('detailOverlay').classList.remove('open');
  // Clean up localStorage cache for this product (DB is source of truth)
  if (currentDetailCode) {
    try { localStorage.removeItem(`desc_cache_${currentDetailCode}`); } catch(e) {}
  }
}

function showDetailPanel(data, name) {
  const d = data.description?.description_data || data.data || {};
  const c = data.description || {};
  
  const title = name ? `${name} <span style="font-weight:400;color:var(--muted-fg);font-size:13px">(${c.internal_ref_code || currentDetailCode})</span>` : (c.internal_ref_code || currentDetailCode || 'Chi tiết');
  document.getElementById('detailTitle').innerHTML = title;

  // 1. Clean Tab - Render Format Đẹp Đẹp
  const cleanBody = document.getElementById('detailBodyClean');
  
  // Render "Dàn trang (Chuẩn)" — Premium structured view từ description_data
  const descData = d || {};
  const productName = name || descData['ten_san_pham'] || c.internal_ref_code || '';

  function _fv(v) {
    if (!v || v === 'null' || v === 'undefined') return '';
    return String(v).trim();
  }
  function _row(label, key, value) {
    const v = _fv(value);
    if (!v) return '';
    return `<div class="dd-row"><span class="dd-label">${label}</span><span class="dd-value" id="dantrang-val-${key}" contenteditable="true" title="Click để chỉnh sửa" style="outline:none;cursor:text;border-bottom:1px dashed transparent;border-radius:3px;padding:1px 4px;" onfocus="this.style.background='#fffbeb';this.style.borderColor='var(--primary)'" onblur="this.style.background='';this.style.borderColor='transparent'">${esc(v)}</span></div>`;
  }
  function _bullets(v) {
    if (!_fv(v)) return '';
    const items = _fv(v).split(/[\n•·]+/).map(x => x.trim()).filter(Boolean);
    if (!items.length) return '';
    return items.map(i => `<li>${esc(i)}</li>`).join('');
  }

  const sections = [];

  // ── THÔNG TIN CƠ BẢN ──
  const basicFields = [
    ['ten_san_pham','Tên sản phẩm'], ['tagline','Tagline'], ['mo_ta_chinh','Mô tả chính'],
    ['phong_cach','Phong cách'], ['tags','Tags'],
  ];
  let basicHtml = basicFields.map(([k,l]) => _row(l, descData[k])).join('');
  if (basicHtml) sections.push({ emoji:'🏷️', title:'THÔNG TIN CƠ BẢN', body: basicHtml });

  // ── CHẤT LIỆU & BẢO QUẢN ──
  let matHtml = [_row('Chất liệu', descData['chat_lieu']), _row('Tính năng vải', descData['tinh_nang_vai']), _row('Hướng dẫn bảo quản', descData['huong_dan_bao_quan'])].join('');
  if (matHtml) sections.push({ emoji:'🌿', title:'CHẤT LIỆU & BẢO QUẢN', body: matHtml });

  // ── ĐỐI TƯỢNG ──
  let targetHtml = [_row('Độ tuổi', 'do_tuoi', descData['do_tuoi']), _row('Giới tính', 'gioi_tinh', descData['gioi_tinh']), _row('Lối sống', 'loi_song', descData['loi_song']), _row('Tính cách', 'tinh_cach', descData['tinh_cach'])].join('');
  if (targetHtml) sections.push({ emoji:'👤', title:'ĐỐI TƯỢNG', body: targetHtml });

  // ── DỊP MẶC & STYLING ──
  const dipMac = _fv(descData['dip_mac']);
  const phoi = _fv(descData['phoi_do']);
  const nguyen = _fv(descData['nguyen_tac_phoi_do']);
  const layer = _fv(descData['layer'] || descData['goi_y_layer']);
  const mua = _fv(descData['mua_phu_hop']);
  let styleHtml = '';
  if (dipMac) styleHtml += `<div class="dd-row"><span class="dd-label">Dịp mặc</span><span class="dd-value"><ul class="dd-bullets">${_bullets(dipMac)}</ul></span></div>`;
  if (phoi)   styleHtml += `<div class="dd-row"><span class="dd-label">Gợi ý phối đồ</span><span class="dd-value"><ul class="dd-bullets">${_bullets(phoi)}</ul></span></div>`;
  if (nguyen) styleHtml += `<div class="dd-row"><span class="dd-label">Nguyên tắc phối</span><span class="dd-value">${esc(nguyen)}</span></div>`;
  if (layer)  styleHtml += `<div class="dd-row"><span class="dd-label">Gợi ý layering</span><span class="dd-value">${esc(layer)}</span></div>`;
  if (mua)    styleHtml += `<div class="dd-row"><span class="dd-label">Mùa phù hợp</span><span class="dd-value">${esc(mua)}</span></div>`;
  if (styleHtml) sections.push({ emoji:'👗', title:'DỊP MẶC & STYLING', body: styleHtml });

  // ── FAQ ──
  const faq = descData['faq'] || descData['FAQQ'] || '';
  if (_fv(faq)) {
    const pairs = _fv(faq).split(/Q:|💬/).map(x=>x.trim()).filter(Boolean);
    let faqHtml = '';
    pairs.forEach(pair => {
      const [q, ...aParts] = pair.split(/A:|→/);
      if (q) faqHtml += `<div class="dd-faq-q">💬 ${esc(q.trim())}</div>`;
      if (aParts.length) faqHtml += `<div class="dd-faq-a">${esc(aParts.join('').trim())}</div>`;
    });
    if (faqHtml) sections.push({ emoji:'❓', title:'FAQ', body: faqHtml });
  }

  // ── HỖ TRỢ BÁN HÀNG ──
  const hookQC = _fv(descData['hook_quang_cao']);
  const crossSell = _fv(descData['cross_sell'] || descData['upsell']);
  const sizeGuide = _fv(descData['huong_dan_size'] || descData['size_guide']);
  let salesHtml = '';
  if (hookQC)    salesHtml += `<div class="dd-highlight">${esc(hookQC)}</div>`;
  if (crossSell) salesHtml += `<div class="dd-row"><span class="dd-label">Cross-sell</span><span class="dd-value">${esc(crossSell)}</span></div>`;
  if (sizeGuide) salesHtml += `<div class="dd-row"><span class="dd-label">Hướng dẫn size</span><span class="dd-value"><ul class="dd-bullets">${_bullets(sizeGuide)}</ul></span></div>`;
  if (salesHtml) sections.push({ emoji:'🛒', title:'HỖ TRỢ BÁN HÀNG', body: salesHtml });

  // Fallback nếu không có data struct → dùng rendered_text
  const hasSections = sections.some(s => s.body);
  let finalHtml = '';

  if (hasSections) {
    finalHtml = `
      <div class="dd-product-name">${esc(productName).toUpperCase()}</div>
      ${sections.map(s => `
        <div class="dd-section">
          <div class="dd-section-header"><span class="dd-emoji">${s.emoji}</span> ${s.title}</div>
          <div class="dd-section-body">${s.body}</div>
        </div>
      `).join('')}
    `;
  } else if (c.rendered_text) {
    let html = c.rendered_text;
    if (!html.includes('<h2') && !html.includes('<div') && !html.includes('<li')) {
      let text = esc(html);
      text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      text = text.replace(/\n/g, '<br>');
      html = text;
    }
    finalHtml = html;
  } else {
    finalHtml = '<p style="color:var(--muted-fg);padding:24px;">Chưa có nội dung từ AI.</p>';
  }

  cleanBody.innerHTML = `
    <style>
      .dd-product-name{font-size:20px;font-weight:800;text-align:center;letter-spacing:.06em;color:#0b1c44;margin:0 0 20px;padding-bottom:16px;border-bottom:2px solid #e5e7eb}
      .dd-section{margin-bottom:20px;border:1px solid #e5e7eb;border-radius:10px;overflow:hidden;background:#fff}
      .dd-section-header{display:flex;align-items:center;gap:8px;padding:10px 16px;background:linear-gradient(135deg,#f8fafc,#f1f5f9);font-weight:700;font-size:12px;letter-spacing:.08em;color:#1e3a5f;border-bottom:1px solid #e5e7eb;text-transform:uppercase}
      .dd-emoji{font-size:16px}
      .dd-section-body{padding:14px 16px}
      .dd-row{display:flex;gap:12px;margin-bottom:10px;line-height:1.5;font-size:13.5px}
      .dd-label{font-weight:700;color:#374151;min-width:140px;flex-shrink:0}
      .dd-value{color:#4b5563;flex:1}
      .dd-bullets{margin:0;padding-left:18px}
      .dd-bullets li{margin-bottom:4px;font-size:13.5px;color:#4b5563}
      .dd-highlight{background:linear-gradient(135deg,#eff6ff,#dbeafe);border-left:3px solid #3b82f6;padding:10px 14px;border-radius:6px;font-size:13.5px;color:#1e40af;font-style:italic;margin-bottom:10px}
      .dd-faq-q{font-weight:700;font-size:13.5px;color:#374151;margin-bottom:4px;margin-top:12px}
      .dd-faq-q:first-child{margin-top:0}
      .dd-faq-a{font-size:13.5px;color:#4b5563;padding-left:16px;border-left:3px solid #10b981;margin-bottom:8px}
    </style>
    <div id="cleanTextEditor"
      style="padding:24px;font-family:'Inter',system-ui,sans-serif;min-height:200px">
      ${finalHtml}
    </div>
  `;

  // 2. We no longer render editBody here! Instead, we set up variables 
  // so that if the user clicks "Chỉnh sửa ở Tab Clean Data", it knows what to load.
  window.currentDetailDataForCleanTab = data;
  window.currentDetailNameForCleanTab = name;

  // 3. Fields Tab
  const fieldsBody = document.getElementById('detailBodyFields');
  let fHtml = '<div style="padding: 24px;">';
  for (const [k, v] of Object.entries(d)) {
    fHtml += `
      <div style="margin-bottom: 16px; padding: 12px; background: #f9fafb; border-radius: 8px; border: 1px solid #e5e7eb;">
        <div style="display:flex; justify-content:space-between; margin-bottom:8px;">
           <strong style="color:var(--primary); font-size:14px;">${esc(k)}</strong>
           <button class="btn btn-sm" style="background:#e0e7ff; color:#4f46e5; border:none; border-radius:4px; font-size:12px; font-weight:600; cursor:pointer;" onclick="rewriteField('${c.internal_ref_code || currentDetailCode}', '${esc(k)}', this)">✨ AI Viết Lại</button>
        </div>
        <div id="field-val-${k}" style="font-size: 14px; color: #374151; white-space: pre-wrap;">${esc(v)}</div>
      </div>
    `;
  }
  fHtml += '</div>';
  fieldsBody.innerHTML = fHtml;

  // 3.5 Embed (Clean Descripts) Tab
  const embedBody = document.getElementById('detailPreEmbed');
  const rawCleanDesc = c.clean_description || c.rendered_text || 'Chưa có clean description cho sản phẩm này.';
  embedBody.innerText = rawCleanDesc;

  const isApproved = c.status === 1 || data.descStatus === 1;
  if (!isApproved) {
     embedBody.contentEditable = "true";
     embedBody.style.border = "1px solid #10b981";
     embedBody.style.cursor = "text";
     embedBody.title = "Bạn có thể chỉnh sửa trực tiếp hoặc bôi đen văn bản để gọi AI Codex";
  } else {
     embedBody.contentEditable = "false";
     embedBody.style.border = "1px dashed #d1d5db";
     embedBody.style.cursor = "default";
     embedBody.title = "Đã duyệt - Bạn không thể sửa (Hãy nhấn Hủy duyệt nếu muốn sửa)";
  }

  // 4. Raw Tab
  const rawBody = document.getElementById('detailPreRaw');
  rawBody.textContent = JSON.stringify(d, null, 2);

  document.getElementById('detailOverlay').classList.add('open');
  switchDetailTab('clean');

  // Show/hide approve buttons
  const btnApprove = document.getElementById('btnApprove');
  const btnReject = document.getElementById('btnReject');
  
  if (c.saved_at || data.saved) {
    btnApprove.style.display = isApproved ? 'none' : '';
    btnReject.style.display = isApproved ? '' : 'none';
  } else {
    // Just generated -> waiting for save
    btnApprove.style.display = '';
    btnReject.style.display = 'none';
  }
}

let activeDetailTab = 'clean';
function switchDetailTab(tabId) {
  // Reset all
  document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.classList.remove('active');
    btn.style.color = 'var(--muted-fg)';
    btn.style.borderColor = 'transparent';
  });
  
  if(document.getElementById('detailBodyClean')) document.getElementById('detailBodyClean').style.display = 'none';
  if(document.getElementById('detailBodyFields')) document.getElementById('detailBodyFields').style.display = 'none';
  if(document.getElementById('detailBodyEmbed')) document.getElementById('detailBodyEmbed').style.display = 'none';
  if(document.getElementById('detailBodyRaw')) document.getElementById('detailBodyRaw').style.display = 'none';
  
  document.querySelector('.detail-panel').style.background = 'var(--card)';

  const activeTab = document.getElementById(tabId === 'clean' ? 'dTabClean' : 'dTabEmbed');
  if (activeTab) {
    activeTab.classList.add('active');
    activeTab.style.color = 'var(--primary)';
    activeTab.style.borderColor = 'var(--primary)';
  }

  if (tabId === 'clean') {
    document.getElementById('detailBodyClean').style.display = 'block';
    const _cleanEl = document.getElementById('detailBodyClean'); if(_cleanEl) _cleanEl.scrollTop = 0;
    document.getElementById('btnSavePopupText').style.display = 'inline-block';
  } else if (tabId === 'fields') {
    document.getElementById('detailBodyFields').style.display = 'block';
    document.getElementById('btnSavePopupText').style.display = 'none';
  } else if (tabId === 'embed') {
    document.getElementById('detailBodyEmbed').style.display = 'block';
    document.getElementById('btnSavePopupText').style.display = 'none';
  } else if (tabId === 'raw') {
    document.getElementById('detailBodyRaw').style.display = 'block';
    document.getElementById('btnSavePopupText').style.display = 'none';
  }
}

async function rewriteField(code, key, btn) {
  if(!code || !key) return;
  const vDiv = document.getElementById(`field-val-${key}`);
  
  btn.innerHTML = '<span class="spinner-sm" style="border-width:2px; width:12px; height:12px; border-color:#4f46e5 transparent transparent transparent;"></span> ...';
  btn.disabled = true;
  vDiv.style.opacity = '0.5';
  
  try {
    const res = await fetch(`${API}/saved/${encodeURIComponent(code)}/rewrite-field`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ field_key: key })
    });
    const data = await res.json();
    if (data.status === 'success') {
      vDiv.innerText = data.new_value;
      
      // Update local cache
      if(window.currentDetailDataForCleanTab && window.currentDetailDataForCleanTab.data) {
        window.currentDetailDataForCleanTab.data[key] = data.new_value;
      }
      if(window.currentDetailDataForCleanTab && window.currentDetailDataForCleanTab.description) {
        window.currentDetailDataForCleanTab.description.rendered_text = data.clean_description;
      }
      
      btn.innerHTML = '✅ OK';
      setTimeout(() => { btn.innerHTML = '✨ AI Viết Lại'; btn.disabled = false; }, 2000);
      
      // Attempt to re-render clean html implicitly
      const cleanEditor = document.getElementById('cleanTextEditor');
      if (cleanEditor && cleanEditor.innerHTML && !cleanEditor.innerHTML.trim().includes('<h2')) {
          // If pure text, let's just do a tiny logic to refresh the popup if they switch tabs
          // No big deal if not, they can refresh page.
      }
    } else {
      throw new Error(data.message || 'Lỗi');
    }
  } catch(e) {
    alert("Lỗi: " + e.message);
    btn.innerHTML = '✨ AI Viết Lại';
    btn.disabled = false;
  }
  vDiv.style.opacity = '1';
}

// Helper for formatting fake strings temporarily
function StrReplaceFake(str) { 
  return str; // If need markdown replacement later
}

// ═══ Approve / Reject ═══
async function approveDetail(newStatus) {
  if (!currentDetailCode) return;
  try {
    const res = await fetch(`${API}/approve`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ magento_ref_code: currentDetailCode, status: newStatus }),
    });
    const data = await res.json();
    if (data.status !== 'success') throw new Error(data.message);

    // Update buttons
    document.getElementById('btnApprove').style.display = newStatus === 1 ? 'none' : '';
    document.getElementById('btnReject').style.display = newStatus === 1 ? '' : 'none';

    // Flash feedback
    const label = newStatus === 1 ? '✅ Đã duyệt!' : '✕ Đã hủy duyệt';
    const body = document.getElementById('detailBody');
    if (body) {
        const toast = document.createElement('div');
        toast.style.cssText = 'padding:10px 14px;border-radius:8px;font-size:13px;font-weight:600;margin-bottom:12px;' +
          (newStatus === 1 ? 'background:var(--success-light);color:var(--success)' : 'background:#fff3cd;color:#856404');
        toast.textContent = label;
        body.prepend(toast);
        setTimeout(() => toast.remove(), 3000);
    }

    // Re-fetch latest description data from DB and refresh detail panel
    try {
      const savedRes = await fetch(`${API}/saved/${encodeURIComponent(currentDetailCode)}`);
      if (savedRes.ok) {
        const savedData = await savedRes.json();
        if (savedData.status === 'success' && savedData.data) {
          // Merge approval status into currentDetail and re-render Dàn trang
          currentDetail = { ...currentDetail, ...savedData.data, descStatus: newStatus };
          const tab = document.querySelector('.desc-tab-btn.active');
          if (tab) tab.click(); // Re-trigger active tab render
        }
      }
    } catch (_) { /* silently ignore refresh errors */ }

    // Refresh table stats
    loadOverview();
  } catch (e) {
    alert('Lỗi: ' + e.message);
  }
}


// ═══ Approve from Table Row ═══
async function approveRow(code, newStatus, btn) {
  const ogHtml = btn.innerHTML;
  btn.innerHTML = '<span class="spinner-sm"></span>';
  btn.disabled = true;
  try {
    const res = await fetch(`${API}/approve`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ internal_ref_code: code, status: newStatus }),
    });
    const data = await res.json();
    if (data.status !== 'success') throw new Error(data.message);

    // Update the button itself
    if (newStatus === 1) {
      btn.style.background = '#dc3545';
      btn.innerHTML = '✕ Hủy';
      btn.setAttribute('onclick', `event.stopPropagation();approveRow('${code}',0,this)`);
    } else {
      btn.style.background = '#28a745';
      btn.innerHTML = '✓ Duyệt';
      btn.setAttribute('onclick', `event.stopPropagation();approveRow('${code}',1,this)`);
    }

    // Update status badge in same row
    const row = btn.closest('tr');
    if (row) {
      const badge = row.querySelector('.status-badge');
      if (badge) {
        if (newStatus === 1) {
          badge.className = 'status-badge done';
          badge.textContent = '✅ Đã duyệt';
        } else {
          badge.className = 'status-badge pending';
          badge.textContent = '⏳ Chờ duyệt';
        }
      }
    }

    // Refresh stats
    loadOverview();
  } catch (e) {
    alert('Lỗi: ' + e.message);
    btn.innerHTML = ogHtml;
  } finally {
    btn.disabled = false;
  }
}

// ═══ Edit Text in Popup ═══
async function savePopupText() {
  if (!currentDetailCode) return;

  // Detect active tab
  const isCleanTab = document.getElementById('detailBodyClean')?.style.display !== 'none';

  if (isCleanTab) {
    // ── Tab "Dàn trang (Chuẩn)" → collect field-val-* and call /update ──
    const btn = document.getElementById('btnSavePopupText');
    const oldText = btn.innerText;
    btn.innerText = 'Đang lưu...';
    btn.disabled = true;

    try {
      // Collect all editable field values from Dàn trang tab only
      const newData = {};
      // Collect from dantrang-val-* (editable spans in Dàn trang view)
      document.querySelectorAll('#detailBodyClean [id^="dantrang-val-"]').forEach(el => {
        const key = el.id.replace('dantrang-val-', '');
        newData[key] = el.innerText.trim();
      });
      // Fallback: also collect from hidden field-val-* in Fields tab (for fields not shown as editable)
      document.querySelectorAll('#detailBodyFields [id^="field-val-"]').forEach(el => {
        const key = el.id.replace('field-val-', '');
        if (!(key in newData)) newData[key] = el.innerText.trim();
      });

      if (Object.keys(newData).length === 0) {
        btn.innerText = '⚠️ Không có field';
        setTimeout(() => { btn.innerText = oldText; btn.disabled = false; }, 2000);
        return;
      }

      console.log('[SAVE] Sending description_data:', newData);

      const res = await fetch(`${API}/saved/${encodeURIComponent(currentDetailCode)}/update`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ description_data: newData })
      });
      const data = await res.json();
      if (data.status !== 'success') throw new Error(data.message);

      // Patch currentDetail memory
      if (window.currentDetailDataForCleanTab?.data) {
        Object.assign(window.currentDetailDataForCleanTab.data, newData);
      }

      btn.innerText = '✅ Đã lưu';
      setTimeout(() => { btn.innerText = oldText; btn.disabled = false; }, 2000);
    } catch (e) {
      alert('Lỗi lưu: ' + e.message);
      btn.innerText = oldText;
      btn.disabled = false;
    }
    return;
  }

  // ── Tab "Clean Descripts" → save text via /update-text ──
  const embedEditor = document.getElementById('detailPreEmbed');
  if (!embedEditor) return;

  const updatedText = embedEditor.innerText;
  const btn2 = document.getElementById('btnSavePopupText');
  const oldText2 = btn2.innerText;
  btn2.innerText = 'Đang lưu...';
  btn2.disabled = true;

  try {
    const res = await fetch(`${API}/saved/${encodeURIComponent(currentDetailCode)}/update-text`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ clean_description: updatedText })
    });
    const data = await res.json();
    if (data.status === 'success') {
      btn2.innerText = '✅ Đã lưu';
      setTimeout(() => { btn2.innerText = oldText2; btn2.disabled = false; }, 2000);
      if (window.currentDetailDataForCleanTab?.description) {
        window.currentDetailDataForCleanTab.description.rendered_text = updatedText;
        window.currentDetailDataForCleanTab.description.clean_description = updatedText;
      }
      if (window.currentDetailDataForCleanTab) {
        window.currentDetailDataForCleanTab.clean_description = updatedText;
      }
    } else {
      throw new Error(data.message || 'Lỗi không xác định');
    }
  } catch (e) {
    alert('Lỗi lưu text: ' + e.message);
    btn2.innerText = oldText2;
    btn2.disabled = false;
  }
}

function copyPopupText() {
  const editor = document.getElementById('detailPreEmbed');
  if (!editor) return;
  navigator.clipboard.writeText(editor.innerText).then(() => {
    const btn = document.getElementById('btnCopyJson');
    const oldText = btn.innerText;
    btn.innerText = '✅ Đã Copy';
    setTimeout(() => { btn.innerText = oldText; }, 2000);
  });
}
// ─── AI CODEX INLINE EDITOR ───
let selectedTextInfo = { text: '', context: '', range: null };

function setupInlineEdit() {
  const embedBody = document.getElementById('detailPreEmbed');
  const popup = document.getElementById('inlineEditPopup');

  embedBody.addEventListener('mouseup', function(e) {
    if (embedBody.contentEditable !== "true") return; // Only trigger if unlocked

    const selection = window.getSelection();
    const text = selection.toString().trim();
    
    if (text.length > 5) {
        // Find whole text context
        const context = embedBody.innerText;
        
        selectedTextInfo = {
            text: text,
            context: context,
            range: selection.getRangeAt(0).cloneRange()
        };
        
        // Position popup next to cursor
        popup.style.display = 'block';
        popup.style.top = (e.pageY + 10) + 'px';
        popup.style.left = e.pageX + 'px';
    } else {
        popup.style.display = 'none';
    }
  });

  document.addEventListener('mousedown', function(e) {
    if (!popup.contains(e.target) && !embedBody.contains(e.target)) {
        popup.style.display = 'none';
    }
  });
}

async function triggerInlineEdit(action) {
  const popup = document.getElementById('inlineEditPopup');
  popup.style.display = 'none';
  if (!selectedTextInfo.text || !selectedTextInfo.range) return;

  // Visual feedback injection
  const span = document.createElement('span');
  span.className = 'agent-editing';
  span.style.backgroundColor = '#fbbf24';
  span.style.color = 'black';
  span.textContent = `[⏳ AI Codex đang xử lý...]`;
  selectedTextInfo.range.deleteContents();
  selectedTextInfo.range.insertNode(span);

  try {
      let enrichedContext = "";
      if (action === 'enrich') {
         enrichedContext = "Đây là thông tin của một sản phẩm thời trang. Hãy bổ sung gợi ý cực hay về dịp mặc thích hợp, những ngày lễ hội có thể diện sản phẩm, hoặc cách ứng dụng thực tế vào đời sống. Giữ giọng văn xuất sắc của Stylist chuyên gia thời trang, nhưng KHÔNG viết dài dòng lê thê.\n\n" + selectedTextInfo.context;
      } else {
         enrichedContext = "Đây là thông tin của một sản phẩm thời trang. Hãy thực hiện yêu cầu chỉnh sửa trên đoạn text được đánh dấu.\n\n" + selectedTextInfo.context;
      }

      // Reuse the existing ai-report capability
      const res = await fetch('/api/report-inline-edit', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
              selected_text: selectedTextInfo.text,
              action: action,
              context: enrichedContext
          })
      });
      const data = await res.json();
      
      span.style.backgroundColor = '#d1fae5'; // success green
      span.innerHTML = `${data.new_text} <em style="font-size:10px;color:#059669;cursor:pointer;padding-left:4px" title="Chấp nhận gợi ý này">[Chấp nhận]</em>`;
      
      const acceptBtn = span.querySelector('em');
      acceptBtn.onclick = function() {
          span.outerHTML = data.new_text;
      };
  } catch(e) {
      span.style.backgroundColor = '#fecaca';
      span.textContent = selectedTextInfo.text; // Revert safely
      alert('Lỗi gọi AI Codex: ' + e.message);
  }
}

// Initialize on load
setupInlineEdit();

