(function ($) {
    'use strict';

    const initSwiperInScope = function ($scope) {
        $scope.find('.swiper, .swiper-container').each(function () {
            const $container = $(this);
            let settings = $container.data('swiper-options');

            if (!settings) {
                const $parent = $container.closest('[data-swiper-options]');
                settings = $parent.length ? $parent.data('swiper-options') : null;
            }

            if (!settings || !$container.length || !window.Swiper) return;

            if ($container.data('swiper-instance')) {
                $container.data('swiper-instance').destroy(true, true);
                $container.removeData('swiper-instance');
            }

            // Initialize Swiper
            const swiperInstance = new Swiper($container[0], settings);
            $container.data('swiper-instance', swiperInstance);

            if (elementorFrontend.isEditMode()) {
                const updateSwiper = () => {
                    swiperInstance.update();
                    swiperInstance.updateSlides();
                    swiperInstance.updateSize();
                };
                
                setTimeout(updateSwiper, 300);
                setTimeout(updateSwiper, 600);
                setTimeout(updateSwiper, 1000);
            }
        });
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/global', initSwiperInScope);
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-widget-products.default', initSwiperInScope);
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-widget-slider.default', initSwiperInScope);
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-widget-carousel.default', initSwiperInScope);

        if (elementorFrontend.isEditMode()) {
            elementor.channels.editor.on('change', function (view) {
                const $editedWidget = view.$el.closest('.elementor-widget');
                if ($editedWidget.find('.swiper, .swiper-container').length) {
                    initSwiperInScope($editedWidget);
                }
            });

            elementorFrontend.hooks.addAction('frontend/element_ready/widget', initSwiperInScope);
        }
    });
})(jQuery);
