document.addEventListener('DOMContentLoaded',()=>{
 document.querySelector('.sidebar-toggle')?.addEventListener('click',()=>document.querySelector('.sidebar')?.classList.toggle('open'));
 document.querySelectorAll('.group-toggle').forEach(button=>button.addEventListener('click',()=>{let menu=document.getElementById(button.getAttribute('aria-controls'));let open=menu.classList.toggle('open');button.setAttribute('aria-expanded',open?'true':'false')}));
});
document.addEventListener('click',e=>{if(!e.target.closest('.autocomplete'))document.querySelectorAll('.autocomplete-results').forEach(x=>x.innerHTML='')});
window.autocomplete=function(input,hidden,type='clientes'){let box=input.parentElement.querySelector('.autocomplete-results');let timer;input.addEventListener('input',()=>{clearTimeout(timer);hidden.value='';timer=setTimeout(async()=>{let q=input.value.trim();if(q.length<2){box.innerHTML='';return}let data=await fetch(`${window.BASE_URL||'/websiscre'}/app.php?p=buscar&type=${type}&q=${encodeURIComponent(q)}`).then(r=>r.json());box.innerHTML=data.map(x=>`<button type="button" data-id="${x.id}" data-label="${x.label.replace(/"/g,'&quot;')}">${x.label}</button>`).join('');box.querySelectorAll('button').forEach(b=>b.onclick=()=>{input.value=b.dataset.label;hidden.value=b.dataset.id;box.innerHTML='';input.dispatchEvent(new Event('selected'))})},250)})};
