const API='api.php';
function toast(msg,type='success'){const c=document.getElementById('toast-container');const t=document.createElement('div');t.className='toast toast-'+type;t.innerHTML=msg;c.appendChild(t);setTimeout(()=>t.remove(),4000);}
function api(action,data={},method='POST'){
  if(method==='GET'){const p=new URLSearchParams({action,...data});return fetch(API+'?'+p).then(r=>r.json());}
  const fd=new FormData();fd.append('action',action);
  for(let k in data){if(data[k]instanceof File)fd.append(k,data[k]);else fd.append(k,typeof data[k]==='object'?JSON.stringify(data[k]):data[k]);}
  return fetch(API,{method:'POST',body:fd}).then(r=>r.json());
}
function openModal(title,body,footer=''){
  document.getElementById('modal-title').textContent=title;
  document.getElementById('modal-body').innerHTML=body;
  document.getElementById('modal-footer').innerHTML=footer;
  document.getElementById('modal-overlay').classList.add('active');
}
function closeModal(){document.getElementById('modal-overlay').classList.remove('active');}
document.getElementById('modal-overlay')?.addEventListener('click',e=>{if(e.target.id==='modal-overlay')closeModal();});
// Navigation
document.querySelectorAll('.nav-item[data-page]').forEach(el=>{
  el.addEventListener('click',()=>{
    document.querySelectorAll('.nav-item').forEach(n=>n.classList.remove('active'));
    el.classList.add('active');
    document.querySelectorAll('.page').forEach(p=>p.style.display='none');
    const pg=document.getElementById('page-'+el.dataset.page);
    if(pg)pg.style.display='block';
    loadPage(el.dataset.page);
    document.querySelector('.sidebar')?.classList.remove('open');
  });
});
function loadPage(p){
  switch(p){
    case'dashboard':loadDashboard();break;
    case'apps':loadApps();break;
    case'audios':loadAudios();break;
    case'settings':loadSettings();break;
    case'api-keys':loadApiKeys();break;
    case'blocked':loadBlocked();break;
    case'logs':loadLogs();break;
  }
}
loadPage('dashboard');
