/**
 * Fichier  : assets/js/wow-shell.js
 * Auteur   : KREMER Régis
 * Version  : 2.2.0
 * Date     : 2026-02-21
 * Description : JS — Shell WOW UI : sidebar, responsive, animations
 *
 * 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
 */
// =============================================================================
// StockMaster Pro — WOW Shell (Sidebar + View/Density switches)
// SAFE overlay: clones existing nav, adds UX controls without breaking pages
// =============================================================================
(function(){
  const qs=(s,r=document)=>r.querySelector(s);
  const qsa=(s,r=document)=>Array.from(r.querySelectorAll(s));

  const isDesktop=()=>window.matchMedia('(min-width: 1100px)').matches;

  // ---- Sidebar (desktop) ----
  function buildSidebar(){
    if(!isDesktop()) return;
    if(qs('.wow-sidebar')) return;

    const dnav = qs('#desktopNav');
    if(!dnav) return;

    const items = qsa('a.dnav-item', dnav);
    if(!items.length) return;

    document.body.classList.add('wow-shell');

    const sidebar = document.createElement('aside');
    sidebar.className = 'wow-sidebar';

    // Brand
    const brand = document.createElement('div');
    brand.className = 'wow-side-brand';
    const logo = document.createElement('div');
    logo.className = 'wow-side-logo';
    const titleWrap = document.createElement('div');
    const title = document.createElement('div');
    title.className = 'wow-side-title';
    title.textContent = (function(){var el=qs(".hdr-title");return (el&&el.textContent)||"StockMaster";})();
    const sub = document.createElement('div');
    sub.className = 'wow-side-sub';
    sub.textContent = (function(){var el=qs(".hdr-user .hdr-username");return (el&&el.textContent||"").trim();})();
    titleWrap.appendChild(title);
    titleWrap.appendChild(sub);
    brand.appendChild(logo);
    brand.appendChild(titleWrap);

    // Actions (collapse + density)
    const actions = document.createElement('div');
    actions.className = 'wow-side-actions';

    const btnCollapse = document.createElement('button');
    btnCollapse.type = 'button';
    btnCollapse.className = 'wow-icon-btn';
    btnCollapse.title = 'Réduire/agrandir le menu';
    btnCollapse.innerHTML = '≡';

    const density = document.createElement('div');
    density.className = 'view-switch';
    density.style.padding = '6px';
    density.style.gap = '6px';
    density.setAttribute('aria-label','Densité');
    density.innerHTML = `
      <button type="button" class="vs-btn" data-density="comfort">Confort</button>
      <button type="button" class="vs-btn" data-density="compact">Compact</button>
    `;

    actions.appendChild(btnCollapse);
    actions.appendChild(density);

    // Nav list
    const nav = document.createElement('nav');
    nav.className = 'wow-side-nav';

    items.forEach(a=>{
      const href = a.getAttribute('href') || '#';
      var _lbl=qs('.dnav-label',a); const label = (((_lbl&&_lbl.textContent)||a.textContent||'')).trim();
      const isActive = a.classList.contains('active');
      var _bd=qs('.dnav-badge',a); const badge = (_bd&&_bd.textContent ? _bd.textContent.trim() : '');

      const it = document.createElement('a');
      it.className = 'wow-side-item' + (isActive ? ' active' : '');
      it.href = href;

      const ic = document.createElement('span');
      ic.className = 'wow-side-icon';
      // reuse existing icon token
      var _ic=qs('.dnav-icon',a); const iconToken = (_ic ? (_ic.getAttribute('data-icon')||'') : '');
      ic.setAttribute('data-icon', iconToken);
      ic.textContent = iconToken ? '' : '•';

      const lb = document.createElement('span');
      lb.className = 'wow-side-label';
      lb.textContent = label;

      it.appendChild(ic);
      it.appendChild(lb);

      if(badge){
        const bd = document.createElement('span');
        bd.className = 'wow-side-badge';
        bd.textContent = badge;
        it.appendChild(bd);
      }

      nav.appendChild(it);
    });

    sidebar.appendChild(brand);
    sidebar.appendChild(actions);
    sidebar.appendChild(nav);

    document.body.prepend(sidebar);

    // collapse state
    const ck = 'sm_sidebar_collapsed';
    const applyCollapsed = (v)=>{
      document.body.classList.toggle('wow-side-collapsed', !!v);
      localStorage.setItem(ck, v ? '1' : '0');
    };
    applyCollapsed(localStorage.getItem(ck)==='1');
    btnCollapse.addEventListener('click', ()=>applyCollapsed(!document.body.classList.contains('wow-side-collapsed')));

    // density state (global)
    const dk='sm_density';
    const applyDensity=(v)=>{
      document.body.setAttribute('data-density', v);
      localStorage.setItem(dk, v);
      qsa('.vs-btn', density).forEach(b=>b.classList.toggle('active', b.getAttribute('data-density')===v));
    };
    applyDensity(localStorage.getItem(dk) || 'comfort');
    density.addEventListener('click',(e)=>{
      const b=e.target.closest('.vs-btn');
      if(!b) return;
      applyDensity(b.getAttribute('data-density'));
    });
  }

  // ---- View switches inside pages (products, movements) ----
  function ensureViewSwitches(){
    const page = window.SM_PAGE || '';

    if(page==='products'){
      const right = qs('.sect-toolbar-right') || qs('.sect-toolbar-left');
      if(right && !qs('#prodViewSwitch')){
        const sw = document.createElement('div');
        sw.className = 'view-switch';
        sw.id = 'prodViewSwitch';
        sw.innerHTML = `
          <button type="button" class="vs-btn" data-view="grid">Grille</button>
          <button type="button" class="vs-btn" data-view="list">Liste</button>
          <button type="button" class="vs-btn" data-view="compact">Compact</button>
        `;
        right.appendChild(sw);
      }
    }

    if(page==='movements'){
      const bar = qs('.mv-stats-bar') || qs('.mv-actions');
      if(bar && !qs('#mvViewSwitch')){
        const sw = document.createElement('div');
        sw.className = 'view-switch';
        sw.id = 'mvViewSwitch';
        sw.style.marginLeft = 'auto';
        sw.innerHTML = `
          <button type="button" class="vs-btn" data-view="detailed">Détaillé</button>
          <button type="button" class="vs-btn" data-view="compact">Compact</button>
        `;
        bar.appendChild(sw);
      }
    }
  }

  // ---- Density CSS hooks (SAFE) ----
  function applyDensityClass(){
    const v = localStorage.getItem('sm_density');
    if(v) document.body.setAttribute('data-density', v);
  }

  // Init
  document.addEventListener('DOMContentLoaded', ()=>{
    applyDensityClass();
    buildSidebar();
    ensureViewSwitches();
  });

  window.addEventListener('resize', ()=>{
    // if crossing breakpoint, rebuild or remove
    if(isDesktop()){
      if(!qs('.wow-sidebar')) buildSidebar();
      document.body.classList.add('wow-shell');
    }else{
      var __sb=qs(".wow-sidebar"); if(__sb) __sb.remove();
      document.body.classList.remove('wow-shell','wow-side-collapsed');
    }
  });
})();
