document.addEventListener('DOMContentLoaded', function(){
  function qs(sel, root){ return (root||document).querySelector(sel); }
  function qsa(sel, root){ return Array.prototype.slice.call((root||document).querySelectorAll(sel)); }
  function applyPartial(html, selectors){
    var tmp = document.createElement('div');
    tmp.innerHTML = html;
    selectors.split(',').forEach(function(sel){
      var target = qs(sel.trim());
      var source = qs(sel.trim(), tmp);
      if (target && source) { target.innerHTML = source.innerHTML; }
    });
  }
  function showLoader(){
    var l = qs('#smoothLoader');
    if (!l){
      l = document.createElement('div');
      l.id = 'smoothLoader';
      l.style.position = 'fixed';
      l.style.inset = '0';
      l.style.background = 'rgba(255,255,255,0.6)';
      l.style.zIndex = '2000';
      l.style.display = 'flex';
      l.style.alignItems = 'center';
      l.style.justifyContent = 'center';
      l.innerHTML = '<div style="padding:12px 16px;border-radius:10px;background:#fff;border:1px solid #e5e7eb;box-shadow:0 6px 18px rgba(0,0,0,0.12);color:#334155;font-weight:600">Procesando…</div>';
      document.body.appendChild(l);
    } else { l.style.display = 'flex'; }
  }
  function hideLoader(){ var l = qs('#smoothLoader'); if (l) l.style.display = 'none'; }

  qsa('form.smooth-form').forEach(function(f){
    f.addEventListener('submit', function(ev){
      var targetSelectors = f.getAttribute('data-target');
      if (!targetSelectors) return; // fallback a navegación normal
      ev.preventDefault();
      showLoader();
      var fd = new FormData(f);
      fetch(window.location.href, { method: 'POST', body: fd, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
        .then(function(r){ return r.text(); })
        .then(function(html){ applyPartial(html, targetSelectors); })
        .catch(function(){ /* swallow */ })
        .finally(function(){ hideLoader(); window.scrollTo({ top: 0, behavior: 'smooth' }); });
    });
  });
});

