document.addEventListener('DOMContentLoaded', () => {
  const sidebar = document.querySelector('.sidebar');
  const toggleBtn = document.getElementById('sidebarToggle');
  const KEY = 'admin_sidebar_open_v1';
  const SECTION_KEY_PREFIX = 'admin_sidebar_section_';
  let comboState = { last: null, time: 0 };

  function isMobile(){ return window.innerWidth < 768; }
  function setOpen(open){
    if(!sidebar) return;
    if(isMobile()){
      sidebar.classList.toggle('show', !!open);
    }
    try{ localStorage.setItem(KEY, open ? '1' : '0'); }catch(e){}
  }
  function getSaved(){
    try{ return localStorage.getItem(KEY) === '1'; }catch(e){ return false; }
  }

  // Initial state
  const saved = getSaved();
  if(isMobile()){
    setOpen(saved);
  }

  // Toggle button
  toggleBtn && toggleBtn.addEventListener('click', () => {
    const open = !(sidebar && sidebar.classList.contains('show'));
    setOpen(open);
  });

  // Keyboard shortcut: Ctrl+B
  document.addEventListener('keydown', (e) => {
    if(e.ctrlKey && e.key.toLowerCase() === 'b'){
      e.preventDefault();
      const open = !(sidebar && sidebar.classList.contains('show'));
      setOpen(open);
    }

    // g + key kısayolları
    const now = Date.now();
    const diff = now - (comboState.time || 0);
    if(e.key.toLowerCase() === 'g'){
      comboState = { last: 'g', time: now };
      return;
    }
    if(comboState.last === 'g' && diff < 800){
      const k = e.key.toLowerCase();
      if(k === 'u'){ window.location.href = 'users.php'; }
      else if(k === 'r'){ window.location.href = 'reports.php'; }
      else if(k === 'f'){ window.location.href = 'referrals.php'; }
      else if(k === 'l'){ window.location.href = 'logs_viewer.php'; }
      comboState = { last: null, time: 0 };
    }

    // Shift + ? ile kısayol modalini aç
    if(e.shiftKey && e.key === '?'){
      e.preventDefault();
      try{
        const el = document.getElementById('shortcutsModal');
        if(el && window.bootstrap){ new bootstrap.Modal(el).show(); }
      }catch(err){ console.log('Modal açılamadı', err); }
    }
  });

  // Keep in sync on resize
  window.addEventListener('resize', () => {
    if(!isMobile() && sidebar){ sidebar.classList.remove('show'); }
  });

  // Sidebar bölümleri: collapsible ve kalıcılık
  const sections = document.querySelectorAll('.sidebar-section');
  sections.forEach((section) => {
    const header = section.querySelector('.sidebar-section-header');
    const body = section.querySelector('.sidebar-section-body');
    if(!header || !body) return;
    const id = section.getAttribute('data-section') || Math.random().toString(36).slice(2);
    const storageKey = SECTION_KEY_PREFIX + id;

    // Restore state
    let collapsed = false;
    try { collapsed = localStorage.getItem(storageKey) === '1'; } catch(e) {}
    body.classList.toggle('collapsed', collapsed);
    header.classList.toggle('collapsed', collapsed);

    header.addEventListener('click', () => {
      const now = !body.classList.contains('collapsed');
      body.classList.toggle('collapsed', now);
      header.classList.toggle('collapsed', now);
      try { localStorage.setItem(storageKey, now ? '1' : '0'); } catch(e) {}
    });
  });

  // Global arama odağı: Ctrl+/
  document.addEventListener('keydown', (e)=>{
    if(e.ctrlKey && e.key === '/'){ const input = document.querySelector('#globalQuickSearch'); input && input.focus(); }
  });

  // Global toast bildirimi
  window.notify = function(type='info', message=''){
    try{
      if(window.Swal){
        const iconMap = {info:'info',success:'success',error:'error',warning:'warning'};
        Swal.fire({ toast: true, position: 'top-end', showConfirmButton: false, timer: 2500, icon: iconMap[type]||'info', title: message });
        return;
      }
    }catch(e){}
    // Fallback
    console.log(`[${type}] ${message}`); if(type==='error') alert(message);
  }

  // Tema anahtarı ve persist
  const THEME_KEY = 'admin_theme_v1';
  function applyTheme(theme){
    document.body.classList.toggle('theme-light', theme === 'light');
    const btn = document.getElementById('themeToggle');
    if(btn){ btn.innerHTML = theme === 'light' ? '<i class="bi bi-moon"></i>' : '<i class="bi bi-brightness-high"></i>'; }
  }
  try{
    const saved = localStorage.getItem(THEME_KEY) || 'dark';
    applyTheme(saved);
  }catch(e){ applyTheme('dark'); }
  const themeBtn = document.getElementById('themeToggle');
  if(themeBtn){
    themeBtn.addEventListener('click', ()=>{
      const current = document.body.classList.contains('theme-light') ? 'light' : 'dark';
      const next = current === 'light' ? 'dark' : 'light';
      applyTheme(next);
      try{ localStorage.setItem(THEME_KEY, next); }catch(e){}
    });
  }
});