
// ——— SHOPIFY CREDENTIALS (SEO section) ———
async function saveShopifyCredsSEO() {
  const st    = document.getElementById('shopify-save-status-seo');
  const badge = document.getElementById('shopify-status-badge');
  const domain = (document.getElementById('shopify-domain-seo')?.value || '').trim();
  const token  = (document.getElementById('shopify-token-seo')?.value  || '').trim();
  if (!currentClient || currentClient==='all') { if(st){st.style.color='var(--y)';st.textContent='Selecciona un cliente primero';} return; }
  if (!domain || !token) { if(st){st.style.color='var(--y)';st.textContent='Completa los 2 campos';} return; }
  if (st) { st.style.color='var(--m)'; st.textContent='Guardando...'; }
  try {
    const r = await fetchJSON('api/save-credentials.php', {client_id:currentClient, service:'shopify', fields:{shop_domain:domain, access_token:token}});
    if (r.ok) {
      if (st) { st.style.color='var(--g)'; st.textContent='✓ Shopify conectado'; }
      if (badge) { badge.style.background='rgba(150,191,77,.1)'; badge.style.border='1px solid rgba(150,191,77,.3)'; badge.style.color='#96bf4d'; badge.textContent='✓ Conectado'; }
    } else { if(st){st.style.color='var(--red)';st.textContent='✗ '+(r.error||'Error');} }
  } catch(e) { if(st){st.style.color='var(--red)';st.textContent='Error de red';} }
}

async function checkShopifyStatus() {
  const badge = document.getElementById('shopify-status-badge');
  if (!badge || !currentClient || currentClient==='all') return;
  try {
    const r = await fetch(`api/get-credentials.php?client_id=${currentClient}`).then(x=>x.json());
    const connected = r.has?.shopify;
    const sh = r.credentials?.shopify || {};
    if (connected) {
      badge.style.background='rgba(150,191,77,.1)'; badge.style.border='1px solid rgba(150,191,77,.3)'; badge.style.color='#96bf4d';
      badge.textContent = '✓ Conectado' + (sh.shop_domain ? ': '+sh.shop_domain : '');
      const domEl=document.getElementById('shopify-domain-seo'); if(domEl && sh.shop_domain) domEl.value=sh.shop_domain;
    } else {
      badge.style.background='rgba(250,204,21,.1)'; badge.style.border='1px solid rgba(250,204,21,.25)'; badge.style.color='var(--y)'; badge.textContent='Sin configurar';
    }
  } catch(e) {}
}

async function testShopifyConnection() {
  const btn = document.getElementById('shopify-test-btn');
  const st  = document.getElementById('shopify-save-status-seo');
  if (!currentClient || currentClient==='all') { if(st){st.style.color='var(--y)';st.textContent='Selecciona un cliente primero';} return; }
  if (btn) { btn.disabled=true; btn.textContent='Probando...'; }
  if (st)  { st.style.color='var(--m)'; st.textContent='Conectando...'; }
  const token = document.querySelector('meta[name="dm-csrf"]')?.content || '';
  try {
    const d = await fetch('api/shopify-publish.php', {
      method:'POST', headers:{'Content-Type':'application/json','X-CSRF-Token':token},
      body: JSON.stringify({action:'test', client_id:currentClient})
    }).then(r=>r.json());
    if (d.ok) {
      if (st) { st.style.color='var(--g)'; st.textContent='✓ Conectado — '+d.shop_name+(d.plan?' ('+d.plan+')':''); }
      const badge=document.getElementById('shopify-status-badge');
      if (badge) { badge.style.background='rgba(150,191,77,.1)'; badge.style.border='1px solid rgba(150,191,77,.3)'; badge.style.color='#96bf4d'; badge.textContent='✓ Conectado'; }
    } else { if(st){st.style.color='var(--red)';st.textContent='✗ '+(d.error||'Error');} }
  } catch(e) { if(st){st.style.color='var(--red)';st.textContent='Error de red';} }
  finally { if(btn){btn.disabled=false;btn.textContent='Probar conexión';} }
}

async function toggleShopifyPublishOpts() {
  const panel = document.getElementById('shopify-publish-opts');
  const btn   = document.getElementById('shopify-opts-toggle');
  if (!panel) return;
  const visible = panel.style.display !== 'none';
  panel.style.display = visible ? 'none' : 'block';
  if (btn) btn.textContent = visible ? '⚙ Opciones Shopify' : '✕ Cerrar opciones';
  if (!visible) {
    // Auto-sugerir handle desde el keyword
    const kw = (document.getElementById('art-keyword')?.value || '').trim();
    const hEl = document.getElementById('shopify-handle');
    if (hEl && !hEl.value && kw) hEl.value = kw.toLowerCase().replace(/[^a-z0-9\s-]/g,'').replace(/\s+/g,'-').slice(0,60);
    // Cargar lista de blogs
    await loadShopifyBlogs();
  }
}

async function loadShopifyBlogs() {
  const sel = document.getElementById('shopify-blog-sel');
  if (!sel || !currentClient || currentClient==='all') return;
  sel.innerHTML = '<option value="">Cargando...</option>';
  const token = document.querySelector('meta[name="dm-csrf"]')?.content || '';
  try {
    const d = await fetch('api/shopify-publish.php', {
      method:'POST', headers:{'Content-Type':'application/json','X-CSRF-Token':token},
      body: JSON.stringify({action:'blogs', client_id:currentClient})
    }).then(r=>r.json());
    if (d.ok && d.blogs?.length) {
      sel.innerHTML = d.blogs.map(b=>`<option value="${b.id}">${b.title}</option>`).join('');
    } else {
      sel.innerHTML = '<option value="">'+( d.error || 'Sin blogs disponibles')+'</option>';
    }
  } catch(e) { sel.innerHTML='<option value="">Error cargando blogs</option>'; }
}

async function publishToShopify() {
  const raw = typeof _lastSEOArticleRaw !== 'undefined' ? _lastSEOArticleRaw : '';
  if (!raw) { showToast('Genera un artículo primero', 'var(--y)'); return; }
  if (!currentClient || currentClient==='all') { showToast('Selecciona un cliente primero', 'var(--y)'); return; }

  let title = (document.getElementById('art-keyword')?.value || '').trim() || 'Artículo';
  const h1m = raw.match(/^#\s+(.+)$/m);
  if (h1m) title = h1m[1].replace(/\*\*/g,'').trim();

  const blog_id = document.getElementById('shopify-blog-sel')?.value || '';
  const handle  = (document.getElementById('shopify-handle')?.value || '').trim();
  const tags    = (document.getElementById('shopify-tags')?.value   || '').trim();
  const status  = document.querySelector('input[name="shopify-status"]:checked')?.value || 'draft';

  // Convertir Markdown a HTML limpio para Shopify
  let rawWithH1 = raw;
  if (!raw.match(/^#\s+.+$/m) && title) rawWithH1 = `# ${title}\n\n${raw}`;
  const content = mdToHTML(rawWithH1);

  const btn = document.getElementById('shopify-publish-btn');
  if (btn) { btn.disabled=true; btn.textContent = status==='publish' ? '🛍 Publicando...' : '🛍 Guardando...'; }
  const csrfToken = document.querySelector('meta[name="dm-csrf"]')?.content || '';
  try {
    const d = await fetch('api/shopify-publish.php', {
      method:'POST', headers:{'Content-Type':'application/json','X-CSRF-Token':csrfToken},
      body: JSON.stringify({action:'post', client_id:currentClient, title, content, tags, handle, status, blog_id:blog_id?parseInt(blog_id):0})
    }).then(r=>r.json());
    if (!d.ok) {
      showToast('✗ ' + (d.error || 'Error publicando en Shopify'), 'var(--red)');
    } else if (status === 'publish') {
      if (d.view_url && confirm('✅ Publicado en Shopify ¿Abrir el artículo?')) window.open(d.view_url, '_blank');
      else showToast('✅ Publicado en Shopify', 'var(--g)');
    } else {
      if (d.edit_url && confirm('✅ Artículo creado como oculto en Shopify.\n¿Abrir el editor para revisar y publicar?')) window.open(d.edit_url, '_blank');
      else showToast('✅ Artículo guardado en Shopify (oculto)', 'var(--g)');
    }
  } catch(e) { showToast('Error de red al conectar con Shopify', 'var(--red)'); }
  finally { if(btn){btn.disabled=false;btn.textContent='🛍 Publicar en Shopify';} }
}

// ——— SHOPIFY CREDENTIALS (Config / APIs section) ———
function saveShopifyCreds(){
  const domain = (document.getElementById('shopify-domain')?.value||'').trim();
  const token  = (document.getElementById('shopify-token')?.value ||'').trim();
  const st = document.getElementById('s-shopify');
  if(!currentClient||currentClient==='all'){if(st){st.style.color='var(--y)';st.textContent='Selecciona un cliente primero';}return;}
  if(!domain||!token){if(st){st.style.color='var(--y)';st.textContent='Completa los 2 campos';}return;}
  if(st){st.style.color='var(--m)';st.textContent='Guardando...';}
  fetchJSON('api/save-credentials.php',{client_id:currentClient,service:'shopify',fields:{shop_domain:domain,access_token:token}})
    .then(r=>{ if(st){st.style.color=r.ok?'var(--g)':'var(--red)';st.textContent=r.ok?'✓ Guardado':'✗ '+(r.error||'Error');} })
    .catch(()=>{ if(st){st.style.color='var(--red)';st.textContent='Error de red';} });
}
