(function ($) {
    'use strict';

    let $window = $(window);
    let $document = $(document);
    let $body = $('body');
    let $lightbox, $lightboxImage, $pagination;

    function createLightbox() {
        if ($('.testimonial-gallery-lightbox').length === 0) {
            const lightboxHTML = `
                <div class="testimonial-gallery-lightbox">
                    <div class="testimonial-gallery-lightbox-content">
                        <img src="" alt="" class="testimonial-gallery-lightbox-image">
                        <div class="testimonial-gallery-lightbox-close">&times;</div>
                        <div class="testimonial-gallery-lightbox-nav">
                            <div class="testimonial-gallery-lightbox-prev"><i class="fas fa-chevron-left"></i></div>
                            <div class="testimonial-gallery-lightbox-next"><i class="fas fa-chevron-right"></i></div>
                        </div>
                    </div>
                    <div class="testimonial-gallery-pagination"></div>
                </div>
            `;
            $body.append(lightboxHTML);

            $lightbox = $('.testimonial-gallery-lightbox');
            $lightboxImage = $('.testimonial-gallery-lightbox-image');
            $pagination = $('.testimonial-gallery-pagination');
        }
    }

    function calculateVisibleImages() {
        $('.testimonial-gallery').each(function () {
            const $gallery = $(this);
            const $container = $gallery.find('.testimonial-gallery-container');
            const $images = $container.find('.testimonial-gallery-image');
            const galleryWidth = $gallery.width();

            if ($images.length === 0) return;

            let visibleWidth = 0;
            let lastVisibleIndex = -1;
            let hiddenCount = 0;

            $images.show().find('.more-images-overlay').hide();

            $images.each(function (index) {
                const imageWidth = $(this).outerWidth(true);
                if (visibleWidth + imageWidth <= galleryWidth) {
                    visibleWidth += imageWidth;
                    lastVisibleIndex = index;
                } else {
                    $(this).hide();
                    hiddenCount++;
                }
            });

            if (hiddenCount > 0 && lastVisibleIndex >= 0) {
                const $lastVisible = $images.eq(lastVisibleIndex);
                const $overlay = $lastVisible.find('.more-images-overlay');
                $overlay.show().find('.more-count').text(`+${hiddenCount}`);
            }
        });
    }

    const LightboxManager = {
        images: [],
        currentIndex: 0,
        totalImages: 0,

        init($gallery, clickedIndex) {
            this.loadImages($gallery);
            this.currentIndex = clickedIndex;
            this.totalImages = this.images.length;
            this.createPagination();
            this.updateImage();
            this.show();
            this.bindEvents();
        },

        loadImages($gallery) {
            const $images = $gallery.find('.testimonial-gallery-image img');
            this.images = $images.map((_, img) => $(img).attr('src')).get();
        },

        createPagination() {
            const bullets = Array.from({ length: this.totalImages }, (_, i) => {
                const activeClass = i === this.currentIndex ? ' active' : '';
                return `<div class="testimonial-gallery-pagination-bullet${activeClass}" data-index="${i}"></div>`;
            }).join('');

            $pagination.html(bullets);
        },

        updateImage() {
            $lightboxImage.attr('src', this.images[this.currentIndex]);
            $('.testimonial-gallery-pagination-bullet')
                .removeClass('active')
                .eq(this.currentIndex)
                .addClass('active');
        },

        next() {
            this.currentIndex = (this.currentIndex + 1) % this.totalImages;
            this.updateImage();
        },

        prev() {
            this.currentIndex = (this.currentIndex - 1 + this.totalImages) % this.totalImages;
            this.updateImage();
        },

        goTo(index) {
            this.currentIndex = parseInt(index);
            this.updateImage();
        },

        show() {
            $lightbox.addClass('active');
        },

        hide() {
            $lightbox.removeClass('active');
            this.unbindEvents();
        },

        bindEvents() {
            $lightbox.on('click.lightbox', '.testimonial-gallery-lightbox-next', (e) => {
                e.stopPropagation();
                this.next();
            });

            $lightbox.on('click.lightbox', '.testimonial-gallery-lightbox-prev', (e) => {
                e.stopPropagation();
                this.prev();
            });

            $lightbox.on('click.lightbox', '.testimonial-gallery-pagination-bullet', (e) => {
                e.stopPropagation();
                this.goTo($(e.target).data('index'));
            });

            $lightbox.on('click.lightbox', (e) => {
                if ($(e.target).is($lightbox) || $(e.target).hasClass('testimonial-gallery-lightbox-close')) {
                    this.hide();
                }
            });

            $document.on('keydown.lightbox', (e) => {
                switch (e.keyCode) {
                    case 27:
                        this.hide();
                        break;
                    case 37:
                        this.prev();
                        break;
                    case 39:
                        this.next();
                        break;
                }
            });
        },

        unbindEvents() {
            $lightbox.off('.lightbox');
            $document.off('.lightbox');
        }
    };

    $document.ready(function () {
        createLightbox();
        calculateVisibleImages();

        const debouncedCalculate = debounce(calculateVisibleImages, 250);
        $window.on('resize', debouncedCalculate);

        $document.on('click', '.testimonial-gallery-image', function () {
            const $gallery = $(this).closest('.testimonial-gallery');
            const clickedIndex = parseInt($(this).data('index'));

            LightboxManager.init($gallery, clickedIndex);
        });

        $document.on('click', '.testimonial-gallery-lightbox-content, .testimonial-gallery-pagination', function (e) {
            e.stopPropagation();
        });
    });
})(jQuery);