/**
 * Fichier  : assets/js/app-shell.js
 * Auteur   : KREMER Régis
 * Version  : 2.2.0
 * Date     : 2026-02-21
 * Description : JS — Shell applicatif : navigation, thème, layout
 *
 * Changelog :
 *   v2.1.0 (2026-02-21) — Version initiale auditée et sécurisée
 *   v2.1.1 (2026-02-21) — Corrections sécurité, utils.js centralisé
 *   v2.2.0 (2026-02-21) — Permissions magasins, bons de commande, rapport d'écart,
 *                      import CSV, historique prix, bon de livraison multi-lignes
 */
// ================================================================
// app-shell.js — WOW UI V5 (architecture)
// - Sidebar collapse (desktop)
// - Density modes (comfort / compact)
// - Sidebar theme button proxies existing theme toggle
// ================================================================

(function(){
  const STORAGE = {
    density: 'sm_density',
    sidebar: 'sm_sidebar_collapsed'
  };

  function setDensity(mode){
    const html = document.documentElement;
    const m = (mode==='compact') ? 'compact' : 'comfort';
    html.setAttribute('data-density', m);
    try{ localStorage.setItem(STORAGE.density, m); }catch(e){}
    const bC = document.getElementById('btnDensityComfort');
    const bP = document.getElementById('btnDensityCompact');
    if(bC) bC.classList.toggle('active', m==='comfort');
    if(bP) bP.classList.toggle('active', m==='compact');
  }

  function setSidebarCollapsed(collapsed){
    document.body.classList.toggle('sidebar-collapsed', !!collapsed);
    try{ localStorage.setItem(STORAGE.sidebar, collapsed ? '1' : '0'); }catch(e){}
  }

  function init(){
    // Default density
    let density = 'comfort';
    try{ density = localStorage.getItem(STORAGE.density) || 'comfort'; }catch(e){}
    setDensity(density);

    // Sidebar collapsed
    let collapsed = '0';
    try{ collapsed = localStorage.getItem(STORAGE.sidebar) || '0'; }catch(e){}
    setSidebarCollapsed(collapsed==='1');

    const btnCollapse = document.getElementById('btnSidebarCollapse');
    if(btnCollapse){
      btnCollapse.addEventListener('click', ()=>{
        const next = !document.body.classList.contains('sidebar-collapsed');
        setSidebarCollapsed(next);
      });
    }

    const bComfort = document.getElementById('btnDensityComfort');
    const bCompact = document.getElementById('btnDensityCompact');
    if(bComfort) bComfort.addEventListener('click', ()=> setDensity('comfort'));
    if(bCompact) bCompact.addEventListener('click', ()=> setDensity('compact'));

    // Sidebar theme button proxies #btnTheme (single source of truth)
    const btnThemeSidebar = document.getElementById('btnThemeSidebar');
    if(btnThemeSidebar){
      btnThemeSidebar.addEventListener('click', ()=>{
        const btnTheme = document.getElementById('btnTheme');
        if(btnTheme) btnTheme.click();
      });
    }

    // Ensure hamburger exists only for small screens (CSS handles, but safe)
  }

  window.AppShell = { init };
})();
