document.addEventListener('DOMContentLoaded', function() {
    initGalleryHelper(document);

    // MutationObserver to detect dynamically added galleries
    const observer = new MutationObserver(function(mutations) {
        let hasNewGalleries = false;
        mutations.forEach(function(mutation) {
            mutation.addedNodes.forEach(function(node) {
                if (node.nodeType === Node.ELEMENT_NODE) {
                    // Check if the added node or its descendants have gallery-helper-lightbox
                    let galleries = node.querySelectorAll ? Array.from(node.querySelectorAll('.gallery-helper-lightbox')) : [];
                    if (node.classList && node.classList.contains('gallery-helper-lightbox')) {
                        galleries.push(node); // If the node itself is the gallery
                    }
                    if (galleries.length > 0) {
                        hasNewGalleries = true;
                    }
                }
            });
        });
        if (hasNewGalleries) {
            initGalleryHelper(document);
        }
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

    // Listen for dynamic content loading events
    document.addEventListener('hideshowContentLoaded', function(event) {
        const contentDiv = event.detail.contentDiv;
        if (contentDiv) {
            initGalleryHelper(contentDiv);
        }
    });
});

function initGalleryHelper(container) {
    var galleries = container.querySelectorAll('.gallery-helper-lightbox');
    galleries.forEach(function(gallery) {
        if (!gallery.hasAttribute('data-gallery-helper-initialized')) {
            gallery.setAttribute('data-gallery-helper-initialized', 'true');
            gallery.addEventListener('click', function(e) {
                var figure = e.target.closest('figure');
                if (figure && figure.querySelector('img')) {
                    e.preventDefault();
                    var images = gallery.querySelectorAll('img');
                    var img = figure.querySelector('img');
                    var index = Array.from(images).indexOf(img);
                    var mode = gallery.getAttribute('data-slideshow-mode');
                    showLightbox(images, index, mode);
                }
            });
        }
    });
}

function showLightbox(images, startIndex, mode) {
    var modal = document.createElement('div');
    modal.className = 'gallery-helper-modal';
    modal.setAttribute('role', 'dialog');
    modal.setAttribute('aria-modal', 'true');
    modal.setAttribute('aria-label', 'Image gallery lightbox');
    modal.innerHTML = `
        <div class="gallery-helper-overlay"></div>
        <div class="gallery-helper-content" tabindex="0" aria-live="polite" aria-atomic="true">
            <button class="gallery-helper-close" aria-label="Close lightbox">&times;</button>
            <button class="gallery-helper-prev" aria-label="Previous image"><</button>
            <img class="gallery-helper-image" />
            <div class="gallery-helper-caption" id="gallery-helper-caption"></div>
            <button class="gallery-helper-next" aria-label="Next image">></button>
        </div>
    `;
    document.body.appendChild(modal);
    var currentIndex = startIndex;
    var imgElement = modal.querySelector('.gallery-helper-image');
    var captionElement = modal.querySelector('.gallery-helper-caption');
    captionElement.setAttribute('aria-live', 'polite');
    captionElement.setAttribute('aria-atomic', 'true');

    // Touch/swipe variables
    var swipeStartX = 0;
    var swipeStartY = 0;
    var swipeEndX = 0;
    var swipeEndY = 0;
    var minSwipeDistance = 50;

    // Mouse variables
    var mouseStartX = 0;
    var mouseStartY = 0;
    var mouseEndX = 0;
    var mouseEndY = 0;

    function updateImage() {
        var img = images[currentIndex];
        imgElement.src = img.src;
        imgElement.alt = img.alt;
        var figcaption = img.closest('figure').querySelector('figcaption');
        captionElement.textContent = figcaption ? figcaption.textContent : '';
    }

    updateImage();

    modal.querySelector('.gallery-helper-close').addEventListener('click', function() {
        modal.remove();
    });

    // Accessibility: Focus management
    var focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]';
    var focusableElements = modal.querySelectorAll(focusableElementsString);
    focusableElements = Array.prototype.slice.call(focusableElements);

    var firstTabStop = focusableElements[0];
    var lastTabStop = focusableElements[focusableElements.length - 1];

    // Save the element that had focus before the modal was opened
    var previouslyFocusedElement = document.activeElement;

    // Focus the modal content container initially
    modal.querySelector('.gallery-helper-content').focus();

    // Trap focus inside the modal
    modal.addEventListener('keydown', function(e) {
        if (e.key === 'Tab') {
            if (e.shiftKey) {
                // Shift + Tab
                if (document.activeElement === firstTabStop) {
                    e.preventDefault();
                    lastTabStop.focus();
                }
            } else {
                // Tab
                if (document.activeElement === lastTabStop) {
                    e.preventDefault();
                    firstTabStop.focus();
                }
            }
        }
    });

    // Restore focus to previously focused element when modal is removed
    modal.addEventListener('remove', function() {
        if (previouslyFocusedElement) {
            previouslyFocusedElement.focus();
        }
    });

    modal.querySelector('.gallery-helper-prev').addEventListener('click', function() {
        currentIndex = (currentIndex - 1 + images.length) % images.length;
        updateImage();
    });

    modal.querySelector('.gallery-helper-next').addEventListener('click', function() {
        currentIndex = (currentIndex + 1) % images.length;
        updateImage();
    });

    var interval;
    if (mode === 'auto') {
        interval = setInterval(function() {
            currentIndex = (currentIndex + 1) % images.length;
            updateImage();
        }, 3000);
        modal.addEventListener('click', function() {
            clearInterval(interval);
        });
    }

    modal.querySelector('.gallery-helper-overlay').addEventListener('click', function() {
        if (interval) {
            clearInterval(interval);
        }
        modal.remove();
    });

    // Touch event listeners for swipe support
    var content = modal.querySelector('.gallery-helper-content');
    content.addEventListener('touchstart', function(e) {
        touchStartX = e.changedTouches[0].screenX;
        touchStartY = e.changedTouches[0].screenY;
    }, { passive: false });

    content.addEventListener('touchmove', function(e) {
        // Prevent scrolling while swiping
        e.preventDefault();
    }, { passive: false });

    content.addEventListener('touchend', function(e) {
        touchEndX = e.changedTouches[0].screenX;
        touchEndY = e.changedTouches[0].screenY;
        handleSwipe();
    }, { passive: false });

    // Mouse event listeners for swipe support on the image element
    imgElement.addEventListener('mousedown', function(e) {
        mouseStartX = e.clientX;
        mouseStartY = e.clientY;
        e.preventDefault(); // Prevent default drag behavior
    });

    imgElement.addEventListener('mouseup', function(e) {
        mouseEndX = e.clientX;
        mouseEndY = e.clientY;
        swipeEndX = mouseEndX;
        swipeEndY = mouseEndY;
        swipeStartX = mouseStartX;
        swipeStartY = mouseStartY;
        handleSwipe();
    });

    // Also prevent drag on the image
    imgElement.addEventListener('dragstart', function(e) {
        e.preventDefault();
    });

    function handleSwipe() {
        var deltaX = swipeEndX - swipeStartX;
        var deltaY = swipeEndY - swipeStartY;
        var absDeltaX = Math.abs(deltaX);
        var absDeltaY = Math.abs(deltaY);

        // Only handle horizontal swipes that are longer than vertical movement
        if (absDeltaX > absDeltaY && absDeltaX > minSwipeDistance) {
            // Fade out current image
            imgElement.style.opacity = '0';

            // Update index after fade out
            setTimeout(function() {
                if (deltaX > 0) {
                    // Swipe right - previous image
                    currentIndex = (currentIndex - 1 + images.length) % images.length;
                } else {
                    // Swipe left - next image
                    currentIndex = (currentIndex + 1) % images.length;
                }
                updateImage();

                // Fade back in
                imgElement.style.opacity = '1';
            }, 10); // Small delay to ensure fade out starts
        }
    }

    // Keyboard event listeners
    function handleKeydown(e) {
        switch(e.key) {
            case 'ArrowLeft':
                e.preventDefault();
                currentIndex = (currentIndex - 1 + images.length) % images.length;
                updateImage();
                break;
            case 'ArrowRight':
                e.preventDefault();
                currentIndex = (currentIndex + 1) % images.length;
                updateImage();
                break;
            case 'Escape':
                e.preventDefault();
                if (interval) {
                    clearInterval(interval);
                }
                modal.remove();
                break;
        }
    }

    document.addEventListener('keydown', handleKeydown);

    // Remove keyboard listener when modal is closed
    modal.addEventListener('remove', function() {
        document.removeEventListener('keydown', handleKeydown);
    });
}