(function(){
  function ready(fn){ if(document.readyState !== 'loading') fn(); else document.addEventListener('DOMContentLoaded', fn); }
  ready(function(){
    var root = document.documentElement;
    var savedTheme = localStorage.getItem('webPanelTheme');
    if(savedTheme){ root.setAttribute('data-theme', savedTheme); }
    document.querySelectorAll('[data-theme-toggle]').forEach(function(btn){
      btn.addEventListener('click', function(){
        var next = root.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
        root.setAttribute('data-theme', next);
        localStorage.setItem('webPanelTheme', next);
      });
    });
    var aside = document.getElementById('sideNav');
    var scrim = document.querySelector('.mobile-scrim');
    function openMenu(){ if(aside){ aside.classList.add('open'); } if(scrim){ scrim.classList.add('show'); } }
    function closeMenu(){ if(aside){ aside.classList.remove('open'); } if(scrim){ scrim.classList.remove('show'); } }
    document.querySelectorAll('[data-open-menu]').forEach(function(btn){ btn.addEventListener('click', openMenu); });
    document.querySelectorAll('[data-close-menu], .mobile-scrim').forEach(function(btn){ btn.addEventListener('click', closeMenu); });
    document.addEventListener('keydown', function(e){ if(e.key === 'Escape') closeMenu(); });

    document.querySelectorAll('table[data-pro-table], .table-wrap table').forEach(function(table){
      var heads = Array.prototype.map.call(table.querySelectorAll('thead th'), function(th){ return (th.textContent || '').trim(); });
      table.querySelectorAll('tbody tr').forEach(function(tr){
        Array.prototype.forEach.call(tr.children, function(td, i){ if(!td.getAttribute('data-label')) td.setAttribute('data-label', heads[i] || ''); });
      });
    });

    document.querySelectorAll('textarea').forEach(function(ta){
      function resize(){ ta.style.height = 'auto'; ta.style.height = Math.max(120, ta.scrollHeight + 2) + 'px'; }
      ta.addEventListener('input', resize); resize();
    });

    if('onLine' in navigator){
      var badge = document.createElement('div');
      badge.style.cssText='position:fixed;left:12px;bottom:90px;z-index:9999;padding:8px 11px;border-radius:14px;background:#dc2626;color:white;font:12px tahoma;box-shadow:0 10px 30px #0002;display:none';
      badge.textContent='اتصال اینترنت قطع است';
      document.body.appendChild(badge);
      function sync(){ badge.style.display = navigator.onLine ? 'none' : 'block'; }
      window.addEventListener('online', sync); window.addEventListener('offline', sync); sync();
    }
  });
})();
