(function(){
  const sidebar=document.getElementById('sidebar'), toggle=document.getElementById('sidebarToggle');
  if(toggle&&sidebar){
    toggle.addEventListener('click',()=>{ sidebar.classList.toggle('open'); document.body.classList.toggle('sidebar-open'); });
    document.addEventListener('click',e=>{
      if(!sidebar.contains(e.target) && !toggle.contains(e.target)){
        sidebar.classList.remove('open'); document.body.classList.remove('sidebar-open');
      }
    });
  }
  document.addEventListener('click',e=>{
    const btn=e.target.closest('[data-confirm="delete"]'); if(!btn) return;
    e.preventDefault();
    const href=btn.getAttribute('href')||btn.dataset.href||'#';
    Swal.fire({title:'¿Eliminar?',text:'Esta acción no se puede deshacer.',icon:'warning',showCancelButton:true,confirmButtonText:'Sí, eliminar',cancelButtonText:'Cancelar',confirmButtonColor:'var(--brand)'}).then(r=>{ if(r.isConfirmed) window.location=href; });
  });
  document.querySelectorAll('form[novalidate]').forEach(f=>{
    f.addEventListener('submit',ev=>{
      if(!f.checkValidity()){
        ev.preventDefault(); ev.stopPropagation();
        Swal.fire({icon:'warning',title:'Revisa el formulario',text:'Hay campos por completar.'});
      }
      f.classList.add('was-validated');
    });
  });
  window.toast=(type,title)=>Swal.fire({toast:true,position:'top-end',showConfirmButton:false,timer:3500,timerProgressBar:true,icon:type||'info',title:title||''});
})();