var GgmCommerceGalleryWidgetHandler = function($scope, $) {
    // Find the elements within this specific widget's scope.
    var mainImage = $scope.find('.ggm-main-image img')[0]; // Get the raw DOM element
    var thumbnails = $scope.find('.ggm-gallery-thumbnail img');
    var container = $scope.find('.ggm-product-gallery-container');
    var thumbnailsContainer = $scope.find('.ggm-gallery-thumbnails');
    var prevBtn = $scope.find('.ggm-gallery-prev');
    var nextBtn = $scope.find('.ggm-gallery-next');

    // Lightbox elements (within this widget scope)
    var lightbox = $scope.find('.ggm-gallery-lightbox');
    var lightboxOverlay = $scope.find('.ggm-lightbox-overlay');
    var lightboxImage = $scope.find('.ggm-lightbox-image');
    var lightboxCounter = $scope.find('.ggm-lightbox-counter .current');
    var lightboxClose = $scope.find('.ggm-lightbox-close');
    var lightboxPrev = $scope.find('.ggm-lightbox-prev');
    var lightboxNext = $scope.find('.ggm-lightbox-next');

    if ( ! mainImage ) {
        return;
    }

    // Thumbnail navigation variables
    var maxVisible = parseInt(container.data('max-visible')) || 4;
    var totalImages = parseInt(container.data('total-images')) || 0;
    var enableLightbox = container.data('lightbox') === true || container.data('lightbox') === 'true';
    var enableZoom = container.data('zoom') === true || container.data('zoom') === 'true';
    var enableLazyLoading = container.data('lazy-loading') === true || container.data('lazy-loading') === 'true';
    var enablePreloading = container.data('preloading') === true || container.data('preloading') === 'true';
    var zoomLevel = parseFloat(container.data('zoom-level')) || 2;
    var currentOffset = 0;
    var currentLightboxIndex = 0;
    var preloadedImages = {}; // Cache for preloaded images

    // Set CSS zoom level
    if (enableZoom) {
        $scope.find('.ggm-zoom-container').css('--zoom-level', zoomLevel);
    }

    // Collect all lightbox images data - from thumbnail containers
    var lightboxImages = [];
    if (enableLightbox) {
        // Collect from thumbnail container divs, not the img elements
        $scope.find('.ggm-gallery-thumbnail').each(function() {
            var imageData = {
                url: $(this).data('lightbox-url'),
                index: $(this).data('image-index')
            };
            lightboxImages.push(imageData);
        });
        lightboxImages.sort(function(a, b) { return a.index - b.index; });
    }

    // Preloading functions
    function preloadImage(url) {
        if (enablePreloading && enableLightbox && url && !preloadedImages[url]) {
            var img = new Image();
            img.onload = function() {
                preloadedImages[url] = true;
            };
            img.src = url;
        }
    }

    function preloadAdjacentImages(currentIndex) {
        if (!enablePreloading || !enableLightbox) return;

        // Preload next image
        var nextIndex = (currentIndex + 1) % totalImages;
        if (lightboxImages[nextIndex]) {
            preloadImage(lightboxImages[nextIndex].url);
        }

        // Preload previous image
        var prevIndex = (currentIndex - 1 + totalImages) % totalImages;
        if (lightboxImages[prevIndex]) {
            preloadImage(lightboxImages[prevIndex].url);
        }
    }

    // Thumbnail click handler - click on the thumbnail container div
    $scope.find('.ggm-gallery-thumbnail').on('click', function(e) {
        e.preventDefault();

        var $thumbContainer = $(this);

        // Get both the new src and the new srcset from the thumbnail container's data attributes.
        var newImageSrc = $thumbContainer.data('full-src');
        var newImageSrcset = $thumbContainer.data('full-srcset');

        // If a new URL was found, update both attributes on the main image.
        if (newImageSrc) {
            mainImage.src = newImageSrc;
            mainImage.srcset = newImageSrcset ? newImageSrcset : '';

            // Update main image lightbox data
            if (enableLightbox) {
                var clickedIndex = $thumbContainer.data('image-index');
                $(mainImage).attr('data-lightbox-url', $thumbContainer.data('lightbox-url'));
                $(mainImage).attr('data-image-index', clickedIndex);
            }

            // Update main image zoom data
            if (enableZoom) {
                $(mainImage).attr('data-zoom-url', $thumbContainer.data('zoom-url'));
            }
        }

        // Handle the "active" class for styling.
        $scope.find('.ggm-gallery-thumbnail').removeClass('active');
        $thumbContainer.addClass('active');
    });

    // Lightbox functionality
    if (enableLightbox && lightbox.length) {
        // Main image click to open lightbox
        $(mainImage).on('click', function(e) {
            e.preventDefault();
            currentLightboxIndex = parseInt($(this).data('image-index')) || 0;
            openLightbox();
        });

        // Thumbnail double-click to open lightbox
        $scope.find('.ggm-gallery-thumbnail').on('dblclick', function(e) {
            e.preventDefault();
            currentLightboxIndex = parseInt($(this).data('image-index')) || 0;
            openLightbox();
        });

        function openLightbox() {
            if (lightboxImages[currentLightboxIndex]) {
                lightboxImage.attr('src', lightboxImages[currentLightboxIndex].url);
                lightboxCounter.text(currentLightboxIndex + 1);
                lightbox.fadeIn(300);
                $('body').addClass('ggm-lightbox-open').css('overflow', 'hidden');

                // Preload adjacent images for smooth navigation
                preloadAdjacentImages(currentLightboxIndex);
            }
        }

        function closeLightbox() {
            lightbox.fadeOut(300);
            $('body').removeClass('ggm-lightbox-open').css('overflow', '');
        }

        function navigateLightbox(direction) {
            if (direction === 'next') {
                currentLightboxIndex = (currentLightboxIndex + 1) % totalImages;
            } else {
                currentLightboxIndex = (currentLightboxIndex - 1 + totalImages) % totalImages;
            }

            if (lightboxImages[currentLightboxIndex]) {
                lightboxImage.attr('src', lightboxImages[currentLightboxIndex].url);
                lightboxCounter.text(currentLightboxIndex + 1);

                // Preload adjacent images for smooth navigation
                preloadAdjacentImages(currentLightboxIndex);
            }
        }

        // Lightbox event handlers
        lightboxClose.on('click', closeLightbox);
        lightboxPrev.on('click', function() { navigateLightbox('prev'); });
        lightboxNext.on('click', function() { navigateLightbox('next'); });

        // Close lightbox on overlay click
        lightboxOverlay.on('click', function(e) {
            if (e.target === this) {
                closeLightbox();
            }
        });

        // Keyboard navigation
        $(document).on('keydown.ggmc-lightbox', function(e) {
            if (lightbox.is(':visible')) {
                switch(e.keyCode) {
                    case 27: // ESC
                        closeLightbox();
                        break;
                    case 37: // Left arrow
                        navigateLightbox('prev');
                        break;
                    case 39: // Right arrow
                        navigateLightbox('next');
                        break;
                }
            }
        });
    }

    // Zoom functionality
    if (enableZoom) {
        var zoomContainer = $scope.find('.ggm-zoom-container');

        zoomContainer.on('mouseenter', function() {
            $(this).addClass('zooming');
            $(this).find('img').css('transform', 'scale(' + zoomLevel + ')');
        });

        zoomContainer.on('mouseleave', function() {
            $(this).removeClass('zooming');
            $(this).find('img').css({
                'transform': '',
                'transform-origin': ''
            });
        });

        zoomContainer.on('mousemove', function(e) {
            var rect = this.getBoundingClientRect();
            var x = ((e.clientX - rect.left) / rect.width) * 100;
            var y = ((e.clientY - rect.top) / rect.height) * 100;

            $(this).find('img').css('transform-origin', x + '% ' + y + '%');
        });
    }

    // Lazy loading functionality
    function loadLazyImages() {
        if (!enableLazyLoading) return;

        var visibleThumbnails = $scope.find('.ggm-gallery-thumbnail.visible img[data-src]');

        visibleThumbnails.each(function() {
            var $img = $(this);
            var dataSrc = $img.attr('data-src');

            if (dataSrc) {
                var $thumbContainer = $img.closest('.ggm-gallery-thumbnail');
                $img.attr('src', dataSrc);
                $img.removeAttr('data-src');

                // Handle load event to ensure smooth transition
                // Add loaded class to container (not img) to match CSS selector
                $img.on('load', function() {
                    $thumbContainer.addClass('loaded');
                });
            }
        });
    }

    // Navigation functions
    function updateThumbnailVisibility() {
        var thumbnailElements = $scope.find('.ggm-gallery-thumbnail');

        thumbnailElements.each(function(index) {
            var $thumb = $(this);
            if (index >= currentOffset && index < currentOffset + maxVisible) {
                $thumb.removeClass('hidden').addClass('visible');
            } else {
                $thumb.removeClass('visible').addClass('hidden');
            }
        });

        // Update navigation button states
        updateNavigationButtons();

        // Trigger lazy loading for newly visible images
        if (enableLazyLoading) {
            setTimeout(loadLazyImages, 100); // Small delay to ensure DOM updates
        }
    }

    function updateNavigationButtons() {
        if (prevBtn.length) {
            if (currentOffset <= 0) {
                prevBtn.addClass('disabled');
            } else {
                prevBtn.removeClass('disabled');
            }
        }

        if (nextBtn.length) {
            if (currentOffset + maxVisible >= totalImages) {
                nextBtn.addClass('disabled');
            } else {
                nextBtn.removeClass('disabled');
            }
        }
    }

    // Previous button click handler
    prevBtn.on('click', function(e) {
        e.preventDefault();
        if (currentOffset > 0) {
            currentOffset = Math.max(0, currentOffset - 1);
            updateThumbnailVisibility();
        }
    });

    // Next button click handler
    nextBtn.on('click', function(e) {
        e.preventDefault();
        if (currentOffset + maxVisible < totalImages) {
            currentOffset = Math.min(totalImages - maxVisible, currentOffset + 1);
            updateThumbnailVisibility();
        }
    });

    // Initialize navigation on load
    if (totalImages > maxVisible) {
        updateThumbnailVisibility();
    }

    // Initialize lazy loading for initially visible images
    if (enableLazyLoading) {
        loadLazyImages();
    }

    // =========================================================================
    // VARIATION CHANGE INTEGRATION
    // =========================================================================

    // Store reference to scope for variation handling
    var $galleryScope = $scope;
    var productId = container.data('product-id');
    var variationImageSets = container.data('variation-images') || {};
    var currentVariationRequest = 0; // Track current request to prevent race conditions

    /**
     * Update gallery with new images when variation changes
     * @param {Array} images - Array of image objects for the variation
     */
    function updateGalleryImages(images) {
        if (!images || images.length === 0) {
            return;
        }

        // Update main image
        var firstImage = images[0];
        if (firstImage && mainImage) {
            mainImage.src = firstImage.large_url || firstImage.url;
            if (firstImage.large_srcset) {
                mainImage.srcset = firstImage.large_srcset;
            }

            // Update lightbox data
            if (enableLightbox) {
                $(mainImage).attr('data-lightbox-url', firstImage.full_url || firstImage.url);
                $(mainImage).attr('data-image-index', 0);
            }

            // Update zoom data
            if (enableZoom) {
                $(mainImage).attr('data-zoom-url', firstImage.full_url || firstImage.url);
            }
        }

        // Update thumbnails
        var thumbnailElements = $galleryScope.find('.ggm-gallery-thumbnail');

        // Clear existing thumbnails and rebuild
        thumbnailElements.each(function(index) {
            var $thumb = $(this);
            var $thumbImg = $thumb.find('img');

            if (images[index]) {
                var imgData = images[index];

                // Update thumbnail image - clear srcset first to ensure src takes effect
                $thumbImg.removeAttr('srcset');
                $thumbImg.attr('src', imgData.thumbnail_url || imgData.url);
                if (imgData.thumbnail_srcset) {
                    $thumbImg.attr('srcset', imgData.thumbnail_srcset);
                }
                $thumbImg.attr('alt', imgData.alt || '');

                // Update thumbnail container data attributes
                $thumb.attr('data-full-src', imgData.large_url || imgData.url);
                $thumb.attr('data-full-srcset', imgData.large_srcset || '');
                $thumb.attr('data-lightbox-url', imgData.full_url || imgData.url);
                $thumb.attr('data-zoom-url', imgData.full_url || imgData.url);
                $thumb.attr('data-image-index', index);

                $thumb.show();
            } else {
                // Hide extra thumbnails if fewer images in variation
                $thumb.hide();
            }

            // Reset active state
            $thumb.removeClass('active');
        });

        // Set first thumbnail as active
        thumbnailElements.first().addClass('active');

        // Update lightbox images array
        if (enableLightbox) {
            lightboxImages = [];
            images.forEach(function(imgData, index) {
                lightboxImages.push({
                    url: imgData.full_url || imgData.url,
                    index: index
                });
            });
        }

        // Update total images count
        totalImages = images.length;
        currentOffset = 0;

        // Update navigation
        if (totalImages > maxVisible) {
            updateThumbnailVisibility();
        }

        // Update lightbox total counter
        var $totalCounter = $galleryScope.find('.ggm-lightbox-counter .total');
        if ($totalCounter.length) {
            $totalCounter.text(totalImages);
        }
    }

    /**
     * Listen for variation change events
     */
    $(document).on('ggmc_variation_changed', function(e, data) {
        // Only respond if this gallery is for the same product
        if (productId && data.productId && parseInt(productId) !== parseInt(data.productId)) {
            return;
        }

        // Increment request counter to invalidate any pending AJAX requests
        currentVariationRequest++;

        var variationId = data.variationId;

        // If no variation selected, show parent images
        if (!variationId || variationId === 'parent') {
            if (variationImageSets['parent']) {
                updateGalleryImages(variationImageSets['parent']);
            }
            return;
        }

        // Check if we have pre-loaded images for this variation
        if (variationImageSets[variationId]) {
            updateGalleryImages(variationImageSets[variationId]);
            return;
        }

        // Check if variation has images in the event data
        if (data.variation && data.variation.images && data.variation.images.length > 0) {
            // We have image IDs, need to fetch full image data via AJAX
            fetchVariationImages(variationId, data.variation.images, currentVariationRequest);
        } else {
            // No variation-specific images, use parent
            if (variationImageSets['parent']) {
                updateGalleryImages(variationImageSets['parent']);
            }
        }
    });

    /**
     * Fetch variation images via AJAX
     * @param {number} variationId - Variation ID
     * @param {Array} imageIds - Array of image IDs
     * @param {number} requestId - Request ID to prevent race conditions
     */
    function fetchVariationImages(variationId, imageIds, requestId) {
        if (!imageIds || imageIds.length === 0) {
            return;
        }

        // Show loading state
        $galleryScope.find('.ggm-main-image').addClass('loading');

        $.ajax({
            url: typeof ggmCommerceAjax !== 'undefined' ? ggmCommerceAjax.ajax_url : ajaxurl,
            type: 'POST',
            data: {
                action: 'ggmc_get_variation_gallery_images',
                nonce: typeof ggmCommerceAjax !== 'undefined' ? ggmCommerceAjax.nonce : '',
                variation_id: variationId,
                image_ids: imageIds
            },
            success: function(response) {
                $galleryScope.find('.ggm-main-image').removeClass('loading');

                // Check if this request is still current (user hasn't changed selection)
                if (requestId !== currentVariationRequest) {
                    // Stale request - user has since changed selection, ignore this response
                    return;
                }

                if (response.success && response.data.images) {
                    // Cache the images for future use
                    variationImageSets[variationId] = response.data.images;
                    updateGalleryImages(response.data.images);
                }
            },
            error: function() {
                $galleryScope.find('.ggm-main-image').removeClass('loading');
            }
        });
    }
};

/**
 * Slider Gallery Handler
 */
var GgmCommerceSliderHandler = function($scope, $) {
    var slider = $scope.find('.ggm-gallery-slider');

    if (!slider.length) {
        return;
    }

    var configData = slider.data('slider-config');
    if (!configData) {
        return;
    }

    var config = configData;
    var track = slider.find('.ggm-slider-track');
    var slides = slider.find('.ggm-slider-slide');
    var prevBtn = slider.find('.ggm-slider-prev');
    var nextBtn = slider.find('.ggm-slider-next');
    var dots = slider.find('.ggm-slider-dot');
    var currentIndex = 0;
    var totalSlides = slides.length;
    var autoplayInterval = null;
    var isTransitioning = false;

    // Set transition speed
    track.css('transition-duration', config.transitionSpeed + 'ms');

    // Add transition class based on effect
    if (config.transition === 'fade') {
        slider.addClass('transition-fade');
        slides.css('transition-duration', config.transitionSpeed + 'ms');
    }

    function goToSlide(index) {
        if (isTransitioning) return;

        // Handle looping
        if (config.loop) {
            if (index >= totalSlides) {
                index = 0;
            } else if (index < 0) {
                index = totalSlides - 1;
            }
        } else {
            if (index >= totalSlides || index < 0) {
                return;
            }
        }

        isTransitioning = true;
        currentIndex = index;

        if (config.transition === 'fade') {
            slides.removeClass('active');
            slides.eq(currentIndex).addClass('active');
        } else {
            track.css('transform', 'translateX(-' + (currentIndex * 100) + '%)');
        }

        // Update dots
        dots.removeClass('active');
        dots.eq(currentIndex).addClass('active');

        setTimeout(function() {
            isTransitioning = false;
        }, config.transitionSpeed);
    }

    function nextSlide() {
        goToSlide(currentIndex + 1);
    }

    function prevSlide() {
        goToSlide(currentIndex - 1);
    }

    function startAutoplay() {
        if (config.autoplay && !autoplayInterval) {
            autoplayInterval = setInterval(nextSlide, config.autoplaySpeed);
        }
    }

    function stopAutoplay() {
        if (autoplayInterval) {
            clearInterval(autoplayInterval);
            autoplayInterval = null;
        }
    }

    // Navigation button handlers
    nextBtn.on('click', function(e) {
        e.preventDefault();
        nextSlide();
    });

    prevBtn.on('click', function(e) {
        e.preventDefault();
        prevSlide();
    });

    // Dots click handler
    dots.on('click', function(e) {
        e.preventDefault();
        var index = $(this).data('index');
        goToSlide(index);
    });

    // Pause on hover
    if (config.pauseOnHover) {
        slider.on('mouseenter', stopAutoplay);
        slider.on('mouseleave', startAutoplay);
    }

    // Touch/swipe support
    var touchStartX = 0;
    var touchEndX = 0;

    slider.on('touchstart', function(e) {
        touchStartX = e.originalEvent.touches[0].clientX;
    });

    slider.on('touchend', function(e) {
        touchEndX = e.originalEvent.changedTouches[0].clientX;
        var diff = touchStartX - touchEndX;

        if (Math.abs(diff) > 50) {
            if (diff > 0) {
                nextSlide();
            } else {
                prevSlide();
            }
        }
    });

    // Lightbox support for slider
    var enableLightbox = slider.data('lightbox') === true || slider.data('lightbox') === 'true';

    if (enableLightbox) {
        var lightbox = $scope.find('.ggm-gallery-lightbox');
        var lightboxImage = $scope.find('.ggm-lightbox-image');
        var lightboxCounter = $scope.find('.ggm-lightbox-counter .current');
        var lightboxClose = $scope.find('.ggm-lightbox-close');
        var lightboxPrev = $scope.find('.ggm-lightbox-prev');
        var lightboxNext = $scope.find('.ggm-lightbox-next');
        var lightboxOverlay = $scope.find('.ggm-lightbox-overlay');
        var currentLightboxIndex = 0;

        var lightboxImages = [];
        slides.each(function() {
            var img = $(this).find('img');
            lightboxImages.push({
                url: img.data('lightbox-url'),
                index: img.data('image-index')
            });
        });

        slides.on('click', function(e) {
            e.preventDefault();
            currentLightboxIndex = $(this).data('index');
            openLightbox();
        });

        function openLightbox() {
            if (lightboxImages[currentLightboxIndex]) {
                lightboxImage.attr('src', lightboxImages[currentLightboxIndex].url);
                lightboxCounter.text(currentLightboxIndex + 1);
                lightbox.fadeIn(300);
                $('body').addClass('ggm-lightbox-open').css('overflow', 'hidden');
            }
        }

        function closeLightbox() {
            lightbox.fadeOut(300);
            $('body').removeClass('ggm-lightbox-open').css('overflow', '');
        }

        function navigateLightbox(direction) {
            if (direction === 'next') {
                currentLightboxIndex = (currentLightboxIndex + 1) % totalSlides;
            } else {
                currentLightboxIndex = (currentLightboxIndex - 1 + totalSlides) % totalSlides;
            }

            if (lightboxImages[currentLightboxIndex]) {
                lightboxImage.attr('src', lightboxImages[currentLightboxIndex].url);
                lightboxCounter.text(currentLightboxIndex + 1);
            }
        }

        lightboxClose.on('click', closeLightbox);
        lightboxPrev.on('click', function() { navigateLightbox('prev'); });
        lightboxNext.on('click', function() { navigateLightbox('next'); });
        lightboxOverlay.on('click', function(e) {
            if (e.target === this) {
                closeLightbox();
            }
        });

        $(document).on('keydown.ggmc-slider-lightbox', function(e) {
            if (lightbox.is(':visible')) {
                switch(e.keyCode) {
                    case 27: closeLightbox(); break;
                    case 37: navigateLightbox('prev'); break;
                    case 39: navigateLightbox('next'); break;
                }
            }
        });
    }

    // Start autoplay
    startAutoplay();
};

/**
 * Grid Gallery Handler
 */
var GgmCommerceGridHandler = function($scope, $) {
    var grid = $scope.find('.ggm-gallery-grid');

    if (!grid.length) {
        return;
    }

    var items = grid.find('.ggm-grid-item');
    var enableLightbox = grid.data('lightbox') === true || grid.data('lightbox') === 'true';

    if (enableLightbox) {
        var lightbox = $scope.find('.ggm-gallery-lightbox');
        var lightboxImage = $scope.find('.ggm-lightbox-image');
        var lightboxCounter = $scope.find('.ggm-lightbox-counter .current');
        var lightboxClose = $scope.find('.ggm-lightbox-close');
        var lightboxPrev = $scope.find('.ggm-lightbox-prev');
        var lightboxNext = $scope.find('.ggm-lightbox-next');
        var lightboxOverlay = $scope.find('.ggm-lightbox-overlay');
        var currentLightboxIndex = 0;
        var totalImages = items.length;

        var lightboxImages = [];
        items.each(function() {
            var img = $(this).find('img');
            lightboxImages.push({
                url: img.data('lightbox-url'),
                index: img.data('image-index')
            });
        });

        items.on('click', function(e) {
            e.preventDefault();
            currentLightboxIndex = $(this).data('index');
            openLightbox();
        });

        function openLightbox() {
            if (lightboxImages[currentLightboxIndex]) {
                lightboxImage.attr('src', lightboxImages[currentLightboxIndex].url);
                lightboxCounter.text(currentLightboxIndex + 1);
                lightbox.fadeIn(300);
                $('body').addClass('ggm-lightbox-open').css('overflow', 'hidden');
            }
        }

        function closeLightbox() {
            lightbox.fadeOut(300);
            $('body').removeClass('ggm-lightbox-open').css('overflow', '');
        }

        function navigateLightbox(direction) {
            if (direction === 'next') {
                currentLightboxIndex = (currentLightboxIndex + 1) % totalImages;
            } else {
                currentLightboxIndex = (currentLightboxIndex - 1 + totalImages) % totalImages;
            }

            if (lightboxImages[currentLightboxIndex]) {
                lightboxImage.attr('src', lightboxImages[currentLightboxIndex].url);
                lightboxCounter.text(currentLightboxIndex + 1);
            }
        }

        lightboxClose.on('click', closeLightbox);
        lightboxPrev.on('click', function() { navigateLightbox('prev'); });
        lightboxNext.on('click', function() { navigateLightbox('next'); });
        lightboxOverlay.on('click', function(e) {
            if (e.target === this) {
                closeLightbox();
            }
        });

        $(document).on('keydown.ggmc-grid-lightbox', function(e) {
            if (lightbox.is(':visible')) {
                switch(e.keyCode) {
                    case 27: closeLightbox(); break;
                    case 37: navigateLightbox('prev'); break;
                    case 39: navigateLightbox('next'); break;
                }
            }
        });
    }
};

/**
 * Main handler that routes to the appropriate layout handler
 */
var GgmCommerceGalleryMainHandler = function($scope, $) {
    // Check which layout is present and call the appropriate handler
    if ($scope.find('.ggm-gallery-slider').length) {
        GgmCommerceSliderHandler($scope, $);
    } else if ($scope.find('.ggm-gallery-grid').length) {
        GgmCommerceGridHandler($scope, $);
    } else if ($scope.find('.ggm-product-gallery-container').length) {
        GgmCommerceGalleryWidgetHandler($scope, $);
    }
};

jQuery(window).on('elementor/frontend/init', function() {
    elementorFrontend.hooks.addAction('frontend/element_ready/ggmc-product-gallery.default', GgmCommerceGalleryMainHandler);

    // Also try without the .default suffix in case that's the issue
    elementorFrontend.hooks.addAction('frontend/element_ready/ggmc-product-gallery', function($scope, $) {
        GgmCommerceGalleryMainHandler($scope, $);
    });
});
