jQuery(document).ready(function($) {
    var $gallery = $('#didak-gallery');
    var $selection = $('#didak-gallery-selection');
    var $reset = $('#didak-gallery-reset');
    var $popup = $('#didak-gallery-popup');
    var $openButton = $('#didak-gallery-open');
    var $closeButton = $('#didak-gallery-close');
    var images = [];
    var imagesLoaded = false;

    function openFullscreen(elem) {
        if (elem.requestFullscreen) {
            elem.requestFullscreen();
        } else if (elem.webkitRequestFullscreen) { /* Safari */
            elem.webkitRequestFullscreen();
        } else if (elem.msRequestFullscreen) { /* IE11 */
            elem.msRequestFullscreen();
        }
    }

    function closeFullscreen() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) { /* Safari */
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) { /* IE11 */
            document.msExitFullscreen();
        }
    }

    $openButton.click(function() {
        $popup.show();
        openFullscreen($popup[0]);
        if (!imagesLoaded) {
            fetchImages();
        } else {
            organizeImages();
        }
    });

    $closeButton.click(function() {
        closeFullscreen();
        $popup.hide();
    });

    function fetchImages() {
        $gallery.html('<p>Indlæser billeder...</p>');
        $.ajax({
            url: didak_ajax.ajax_url,
            data: { 
                action: 'didak_get_images',
                nonce: didak_ajax.nonce
            },
            method: 'POST',
            dataType: 'json',
            success: function(response) {
                if (response.success && Array.isArray(response.data) && response.data.length > 0) {
                    images = response.data;
                    imagesLoaded = true;
                    randomizeGallery();
                    $reset.show();
                } else {
                    $gallery.html('<p>Ingen billeder fundet.</p>');
                    $reset.hide();
                }
            },
            error: function() {
                $gallery.html('<p>Fejl ved hentning af billeder. Prøv venligst igen senere.</p>');
            }
        });
    }

    function randomizeGallery() {
        $gallery.empty();
        $selection.empty();
        shuffleArray(images);
        images.forEach(function(src) {
            $('<div class="image-container"><img src="' + src + '" alt="Gallery image"></div>').appendTo($gallery);
        });
        organizeImages();
    }

    function organizeImages() {
        var containerWidth = $gallery.width();
        var containerHeight = $gallery.height();
        var imageCount = images.length;
        var aspectRatio = containerWidth / containerHeight;
        var rows = Math.round(Math.sqrt(imageCount / aspectRatio));
        var columns = Math.ceil(imageCount / rows);
        var imageWidth = Math.floor(containerWidth / columns);
        var imageHeight = Math.floor(containerHeight / rows);

        $gallery.find('.image-container').css({
            width: imageWidth + 'px',
            height: imageHeight + 'px'
        });
    }

    $gallery.on('click', '.image-container', function() {
        var $this = $(this);
        var $clone = $this.clone();
        $clone.css({
            width: 'auto',
            height: '100%',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
        });
        $clone.find('img').css({
            height: '100%',
            width: 'auto',
            objectFit: 'cover'
        });
        $clone.appendTo($selection);
        $this.remove();
        updateSelectionLayout();
    });

   $selection.on('click', '.image-container', function() {
        var $this = $(this);
        var src = $this.find('img').attr('src');
        showEnlargedImage(src);
        // Move the clicked image from selection to gallery
        $this.appendTo($gallery);
        organizeImages();
        updateSelectionLayout();
    });

    function showEnlargedImage(src) {
        var $enlargedPopup = $('<div id="enlarged-popup" class="fade-in"></div>');
        var $enlargedImage = $('<img src="' + src + '" alt="Enlarged image">');
        $enlargedPopup.append($enlargedImage);
        $('body').append($enlargedPopup);

        openFullscreen($enlargedPopup[0]);

        $enlargedPopup.click(function() {
            closeEnlargedImage($enlargedPopup);
        });

        $(document).keydown(function(e) {
            if (e.key === "Escape") {
                closeEnlargedImage($enlargedPopup);
            }
        });
    }

    function closeEnlargedImage($popup) {
        closeFullscreen();
        $popup.removeClass('fade-in').addClass('fade-out');
        setTimeout(function() {
            $popup.remove();
        }, 300);
    }

    function openFullscreen(elem) {
        if (elem.requestFullscreen) {
            elem.requestFullscreen();
        } else if (elem.webkitRequestFullscreen) { /* Safari */
            elem.webkitRequestFullscreen();
        } else if (elem.msRequestFullscreen) { /* IE11 */
            elem.msRequestFullscreen();
        }
    }

    function closeFullscreen() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) { /* Safari */
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) { /* IE11 */
            document.msExitFullscreen();
        }
    }


    $reset.click(function() {
        randomizeGallery();
    });

    function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
    }

    function updateSelectionLayout() {
        var selectionWidth = $selection.width();
        var imageCount = $selection.children().length;
        var imageWidth = selectionWidth / imageCount;
        $selection.children().css({
            width: imageWidth + 'px',
            height: '100%',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
        });
        $selection.children().find('img').css({
            height: '100%',
            width: 'auto',
            objectFit: 'cover'
        });
    }

    $(window).resize(function() {
        if (imagesLoaded) {
            organizeImages();
            updateSelectionLayout();
        }
    });

  $(document).on('fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange', function() {
        if (!document.fullscreenElement && !document.webkitFullscreenElement && !document.mozFullScreenElement && !document.msFullscreenElement) {
            var $enlargedPopup = $('#enlarged-popup');
            if ($enlargedPopup.length) {
                closeEnlargedImage($enlargedPopup);
            } else {
                $popup.hide();
            }
        }
    });

    // Håndter Escape-tasten for at lukke popup'en
    $(document).keydown(function(e) {
        if (e.key === "Escape" && $popup.is(":visible")) {
            closeFullscreen();
            $popup.hide();
        }
    });

    // Tilføj touch-understøttelse for mobile enheder
    var touchStartX = 0;
    var touchEndX = 0;

      $selection.on('touchstart', {passive: true}, function(e) {
        touchStartX = e.originalEvent.touches[0].clientX;
    });

    $selection.on('touchmove', {passive: true}, function(e) {
        touchEndX = e.originalEvent.touches[0].clientX;
    });

    $selection.on('touchend', function() {
        if (touchStartX - touchEndX > 50) {
            // Swipe venstre
            $selection.animate({scrollLeft: '+=200'}, 300);
        } else if (touchEndX - touchStartX > 50) {
            // Swipe højre
            $selection.animate({scrollLeft: '-=200'}, 300);
        }
    });

});