/* Daniel — front public : lazy-load (D-14) + lightbox GLightbox (D-15). */
(function () {
    function ready(fn) {
        if (document.readyState !== 'loading') { fn(); }
        else { document.addEventListener('DOMContentLoaded', fn); }
    }

    function reveal(img) {
        var parent = img.parentElement;
        if (parent && parent.tagName === 'PICTURE') {
            parent.querySelectorAll('source[data-srcset]').forEach(function (s) {
                s.srcset = s.getAttribute('data-srcset');
                s.removeAttribute('data-srcset');
            });
        }
        if (img.getAttribute('data-src')) {
            img.src = img.getAttribute('data-src');
            img.removeAttribute('data-src');
        }
    }

    ready(function () {
        var lazies = document.querySelectorAll('img[data-src]');
        if (lazies.length) {
            if ('IntersectionObserver' in window) {
                var io = new IntersectionObserver(function (entries, obs) {
                    entries.forEach(function (entry) {
                        if (entry.isIntersecting) {
                            reveal(entry.target);
                            obs.unobserve(entry.target);
                        }
                    });
                }, { rootMargin: '300px' });
                lazies.forEach(function (img) { io.observe(img); });
            } else {
                lazies.forEach(reveal);
            }
        }

        if (window.GLightbox) {
            GLightbox({ selector: '.glightbox', touchNavigation: true, loop: true });
        }

        // En-tête figé : très léger effet d'ombre au défilement
        var header = document.getElementById('siteHeader');
        if (header) {
            var setScrolled = function () { header.classList.toggle('scrolled', window.scrollY > 6); };
            window.addEventListener('scroll', setScrolled, { passive: true });
            setScrolled();
        }

        // Menu off-canvas : le fermer si on repasse au-dessus du point de bascule
        // (sinon il reste ouvert alors que la nav horizontale réapparaît).
        var mainMenu = document.getElementById('mainMenu');
        if (mainMenu && window.matchMedia) {
            var bp = parseInt(mainMenu.getAttribute('data-nav-breakpoint'), 10) || 992;
            var mqMobile = window.matchMedia('(max-width: ' + bp + 'px)');
            var closeOnDesktop = function () {
                if (!mqMobile.matches && window.bootstrap) {
                    var oc = bootstrap.Offcanvas.getInstance(mainMenu);
                    if (oc) { oc.hide(); }
                }
            };
            if (mqMobile.addEventListener) { mqMobile.addEventListener('change', closeOnDesktop); }
            else if (mqMobile.addListener) { mqMobile.addListener(closeOnDesktop); }
        }
    });
})();
