/**
 * ITSWEBER CMS – Default Theme JavaScript
 */
document.addEventListener('DOMContentLoaded', function () {

    // -------------------------------------------------------------------------
    // Mobile navigation toggle
    // -------------------------------------------------------------------------
    const navToggle = document.getElementById('navToggle');
    const navList   = document.getElementById('navList');

    if (navToggle && navList) {
        navToggle.addEventListener('click', function () {
            const isOpen = navList.classList.toggle('open');
            navToggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
        });
    }

    // -------------------------------------------------------------------------
    // Gallery Lightbox
    // -------------------------------------------------------------------------
    const galleryGrid = document.querySelector('.gallery-images-grid');
    if (!galleryGrid) return;

    const items = Array.from(galleryGrid.querySelectorAll('.gallery-image-item'));
    if (items.length === 0) return;

    let currentIndex = 0;
    let touchStartX  = 0;
    let touchStartY  = 0;

    // Build lightbox DOM once and append to body
    const lightbox = document.createElement('div');
    lightbox.className = 'gallery-lightbox';
    lightbox.setAttribute('role', 'dialog');
    lightbox.setAttribute('aria-modal', 'true');
    lightbox.setAttribute('aria-label', 'Image viewer');
    lightbox.innerHTML =
        '<button class="gallery-lightbox-close" aria-label="Close (Esc)">\u00d7</button>' +
        '<button class="gallery-lightbox-prev" aria-label="Previous image">\u2039</button>' +
        '<div class="gallery-lightbox-inner">' +
            '<img class="gallery-lightbox-img" src="" alt="">' +
            '<div class="gallery-lightbox-info">' +
                '<p class="gallery-lightbox-caption"></p>' +
                '<p class="gallery-lightbox-counter"></p>' +
            '</div>' +
        '</div>' +
        '<button class="gallery-lightbox-next" aria-label="Next image">\u203a</button>';

    document.body.appendChild(lightbox);

    const lbImg     = lightbox.querySelector('.gallery-lightbox-img');
    const lbCaption = lightbox.querySelector('.gallery-lightbox-caption');
    const lbCounter = lightbox.querySelector('.gallery-lightbox-counter');
    const lbClose   = lightbox.querySelector('.gallery-lightbox-close');
    const lbPrev    = lightbox.querySelector('.gallery-lightbox-prev');
    const lbNext    = lightbox.querySelector('.gallery-lightbox-next');

    // Reference to the item that was last opened, for focus-return on close
    let openerItem = null;

    function updateLightbox() {
        const item    = items[currentIndex];
        // querySelector('img') traverses into <picture> wrappers as well
        const img     = item.querySelector('img');
        const imgAlt  = img ? (img.getAttribute('alt') || '') : '';
        const caption = item.dataset.caption || imgAlt;

        // Prefer data-src (full original / WebP set by Phase 3d);
        // fall back to img.src (thumbnail) if data-src is absent.
        lbImg.src             = item.dataset.src || (img ? img.src : '');
        lbImg.alt             = imgAlt;
        lbCaption.textContent = caption;
        lbCaption.hidden      = caption === '';
        lbCounter.textContent = (currentIndex + 1) + '\u00a0/\u00a0' + items.length;
        lbPrev.disabled       = currentIndex === 0;
        lbNext.disabled       = currentIndex === items.length - 1;
    }

    function openAt(index) {
        openerItem   = items[index];
        currentIndex = index;
        updateLightbox();
        lightbox.classList.add('is-open');
        document.body.style.overflow = 'hidden';
        // Move focus into the lightbox for keyboard users
        lbClose.focus();
    }

    function close() {
        lightbox.classList.remove('is-open');
        document.body.style.overflow = '';
        if (openerItem) openerItem.focus();
    }

    function prev() {
        if (currentIndex > 0) { currentIndex--; updateLightbox(); }
    }

    function next() {
        if (currentIndex < items.length - 1) { currentIndex++; updateLightbox(); }
    }

    // Attach click + keyboard to each thumbnail
    items.forEach(function (item, idx) {
        item.addEventListener('click', function () { openAt(idx); });
        item.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                openAt(idx);
            }
        });
    });

    // Lightbox controls
    lbClose.addEventListener('click', close);
    lbPrev.addEventListener('click', prev);
    lbNext.addEventListener('click', next);

    // Close on backdrop click (not on inner content)
    lightbox.addEventListener('click', function (e) {
        if (e.target === lightbox) close();
    });

    // Keyboard: ESC + arrow navigation
    document.addEventListener('keydown', function (e) {
        if (!lightbox.classList.contains('is-open')) return;
        switch (e.key) {
            case 'Escape':     close(); break;
            case 'ArrowLeft':  prev();  break;
            case 'ArrowRight': next();  break;
        }
    });

    // Touch / swipe support (horizontal swipe only, ignore vertical scrolls)
    lightbox.addEventListener('touchstart', function (e) {
        touchStartX = e.changedTouches[0].clientX;
        touchStartY = e.changedTouches[0].clientY;
    }, { passive: true });

    lightbox.addEventListener('touchend', function (e) {
        const dx = touchStartX - e.changedTouches[0].clientX;
        const dy = touchStartY - e.changedTouches[0].clientY;
        // Only act on predominantly horizontal swipes (dx > dy, threshold 40 px)
        if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) {
            if (dx > 0) next();
            else prev();
        }
    }, { passive: true });

});
