/**
 * slide-menu.js — MageStock v3.0
 * Script autonome : gère le volet latéral gauche (mobile/tablette)
 * Se charge en dernier, après app.js — override initSlideMenu
 */
(function(){
    'use strict';

    // Attendre que le DOM soit prêt
    function ready(fn){
        if(document.readyState !== 'loading') fn();
        else document.addEventListener('DOMContentLoaded', fn);
    }

    ready(function(){
        var backdrop = document.getElementById('slideBackdrop');
        var menu     = document.getElementById('slideMenu');
        var btnHam   = document.getElementById('btnHamburger');
        var btnMore  = document.getElementById('btnBnavMore');
        var btnClose = document.getElementById('btnSlideClose');

        if(!menu) { console.warn('[slide-menu] #slideMenu not found'); return; }
        if(!backdrop) { console.warn('[slide-menu] #slideBackdrop not found'); return; }

        function openMenu(){
            backdrop.classList.add('active');
            menu.classList.add('open');
            document.body.style.overflow = 'hidden';
        }

        function closeMenu(){
            menu.classList.remove('open');
            backdrop.classList.remove('active');
            document.body.style.overflow = '';
        }

        // Bind open
        if(btnHam)  btnHam.addEventListener('click', openMenu, false);
        if(btnMore) btnMore.addEventListener('click', openMenu, false);

        // Bind close
        if(btnClose) btnClose.addEventListener('click', closeMenu, false);
        if(backdrop) backdrop.addEventListener('click', closeMenu, false);

        // Escape
        document.addEventListener('keydown', function(e){
            if(e.key === 'Escape' && menu.classList.contains('open')) closeMenu();
        }, false);

        // Swipe left to close
        var startX = 0;
        menu.addEventListener('touchstart', function(e){
            startX = e.touches[0].clientX;
        }, { passive: true });
        menu.addEventListener('touchend', function(e){
            var endX = e.changedTouches[0].clientX;
            if(startX - endX > 60) closeMenu();
        }, { passive: true });

        // Neutraliser l'ancien initSlideMenu de App
        if(window.App && App.initSlideMenu) {
            App.initSlideMenu = function(){};
        }

        console.log('[slide-menu] initialized OK');
    });
})();
