(function(){
  const shell=document.querySelector('.admin-shell');
  const sidebar=document.getElementById('premium-sidebar');
  const overlay=document.getElementById('sidebar-overlay');
  const desktopToggle=document.getElementById('sidebar-toggle');
  const mobileToggle=document.getElementById('mobile-menu-toggle');
  const key='afenixx.sidebar.collapsed';

  function setCollapsed(collapsed){
    if(!shell)return;
    shell.classList.toggle('sidebar-collapsed',collapsed);
    desktopToggle?.setAttribute('aria-expanded',collapsed?'false':'true');
    try{localStorage.setItem(key,collapsed?'1':'0')}catch(e){}
  }
  function closeMobile(){sidebar?.classList.remove('mobile-open');overlay?.classList.remove('active');mobileToggle?.setAttribute('aria-expanded','false')}
  function openMobile(){sidebar?.classList.add('mobile-open');overlay?.classList.add('active');mobileToggle?.setAttribute('aria-expanded','true')}
  try{if(localStorage.getItem(key)==='1'&&window.innerWidth>1024)setCollapsed(true)}catch(e){}
  desktopToggle?.addEventListener('click',()=>setCollapsed(!shell.classList.contains('sidebar-collapsed')));
  mobileToggle?.addEventListener('click',()=>sidebar?.classList.contains('mobile-open')?closeMobile():openMobile());
  overlay?.addEventListener('click',closeMobile);
  sidebar?.querySelectorAll('a').forEach(a=>a.addEventListener('click',()=>{if(window.innerWidth<=1024)closeMobile()}));
  window.addEventListener('resize',()=>{if(window.innerWidth>1024)closeMobile()});
})();
