class SlideshowClass extends elementorModules.frontend.handlers.Base {
    getDefaultSettings() {
        return {
            selectors: {
                swiperContainer: '.twae-slideshow.swiper-container',
            },
        };
    }

    bindEvents() {

        this.medisSliderInitialize();

        // Reinitialize on custom hook
        elementorFrontend.hooks.addAction('frontend/twaeWidget/horizontalSliderInitialize', () => {
            this.medisSliderInitialize();
        });

        // Restart autoplay on tab click
        jQuery(document).on('click', '.twae-modern-vertical-timeline-tab-btn', () => {
            setTimeout(() => {
                this.fixAutoplayOnTabSwitch();
            }, 300);
        });
    }
    fixAutoplayOnTabSwitch() {
        const swiperContainers = this.$element[0].querySelectorAll('.twae-slideshow.swiper-container');

        swiperContainers.forEach((el) => {
            const isModernLayout = el.closest('.twae-modern-vertical-timeline');
            const autoplayAttr = el.getAttribute('data-slideshow_autoplay');
            const autoplay = autoplayAttr === 'true';
            const swiperInstance = el.swiper;


            if (!isModernLayout || !swiperInstance || !swiperInstance.autoplay) return;

            swiperInstance.autoplay.stop(); // Stop all first

            if (el.offsetParent !== null && autoplay) {
                swiperInstance.update();
                swiperInstance.autoplay.start(); // ✅ Only runs if autoplay is actually true
            }
        });
    }

    medisSliderInitialize() {
        const selectors = this.getSettings('selectors');
        const selector = this.$element.find(selectors.swiperContainer);

        if (selector.length <= 0) return;

        selector.each((_, ele) => {
            const $swiper = jQuery(ele);

            if ($swiper.is(':visible')) {
                this.mediaSwiper($swiper);
            } else {
                const tabContent = $swiper.closest('.twae-modern-vertical-timeline-tab-content');

                // ✅ Fix: Check if tabContent is found and valid before observing
                if (tabContent.length > 0) {
                    const observer = new MutationObserver(() => {
                        if (tabContent.is(':visible')) {
                            observer.disconnect();
                            this.mediaSwiper($swiper);
                        }
                    });

                    if (tabContent.hasClass('active')) {
                        this.mediaSwiper($swiper);
                    }

                    observer.observe(tabContent[0], {
                        attributes: true,
                        attributeFilter: ['style', 'class']
                    });
                }
            }
        });

        this.verticalLayout = selector.closest('.twae-wrapper.twae-vertical');
    }


    async mediaSwiper(ele) {
        const selectorID = ".twae-slideshow#" + ele.attr('id');
        let swiperElement = jQuery(selectorID);
        let elementExists = false;

        for (let i = 0; i < swiperElement.length; i++) {
            if (swiperElement[i].swiper === undefined) {
                swiperElement = swiperElement[i];
                elementExists = true;
                break;
            }
        }

        if (!elementExists) return;

        const $swiperEl = jQuery(swiperElement);
        const nextButton = $swiperEl.find('.twae-icon-right-open')[0];
        const prevButton = $swiperEl.find('.twae-icon-left-open')[0];
        const lang_dir = $swiperEl.attr("dir");
        const autoplayAttr = $swiperEl.attr("data-slideshow_autoplay");
        const autoplay = autoplayAttr === "true";
        const auto_height = true;

        const Navigation = {
            nextEl: lang_dir === 'rtl' ? prevButton : nextButton,
            prevEl: lang_dir === 'rtl' ? nextButton : prevButton,
        };

        const swiperConfig = {
            autoplay: autoplay,
            delay: 5000,
            slidesPerView: 1,
            direction: 'horizontal',
            navigation: Navigation,
            autoHeight: auto_height,
            allowSlideNext: true,
            allowSlidePrev: true,

            on: {
                slideChange: () => {
                    const vr_layout = jQuery('.twae-vertical.twae-wrapper');
                    if (vr_layout.length > 0) {
                        const animation = vr_layout.find('.twae-content.aos-init').data('aos');
                        if (animation !== 'none' && typeof AOS === 'object') {
                            setTimeout(() => {
                                AOS.refresh();
                            }, 500);
                        }
                    }
                },
                slideChangeTransitionEnd: () => {
                    elementorFrontend.hooks.doAction('frontend/twaeWidget/mediaSlideChange', 'custom hook');
                },
            },
        };

        const swiperInstance = await this.swiperInitialize($swiperEl, swiperConfig);

        if (
            autoplay === true &&
            ele[0].offsetParent !== null &&
            ele[0].closest('.twae-modern-vertical-timeline') &&
            swiperInstance &&
            swiperInstance.params &&
            swiperInstance.params.autoplay &&
            swiperInstance.autoplay &&
            typeof swiperInstance.autoplay.start === 'function'
        ) {
            swiperInstance.autoplay.running = true;
            swiperInstance.autoplay.start();
        }



        // Stop/start autoplay based on scroll
        if (autoplay && this.verticalLayout.length > 0) {
            let debounceTimeout;
            this.swiperStopAutoPlay($swiperEl);
            jQuery(window).on('scroll', () => {
                clearTimeout(debounceTimeout);
                debounceTimeout = setTimeout(() => {
                    this.swiperStopAutoPlay($swiperEl);
                }, 200);
            });
        }
    }

    swiperStopAutoPlay(ele) {
        const swiperWrp = jQuery(ele);
        const swiperContainer = swiperWrp.find('.swiper-wrapper');
        const height = swiperWrp[0].offsetHeight / 2;
        const top = swiperContainer[0].getBoundingClientRect().top + height;
        const autoplayAttr = swiperWrp.attr("data-slideshow_autoplay");
        const autoplay = autoplayAttr === "true";

        // ❗ Prevent start/stop if autoplay is off
        if (!autoplay) return;
        if (top < 0) {
            if (swiperWrp[0].swiper && swiperWrp[0].swiper.autoplay) {
                swiperWrp[0].swiper.autoplay.stop();
            }
        } else {
            if (swiperWrp[0].swiper && swiperWrp[0].swiper.autoplay) {
                swiperWrp[0].swiper.autoplay.start();
            }
        }
    }

    async swiperInitialize(ele, config) {
        if (typeof Swiper === 'undefined') {
            const asyncSwiper = elementorFrontend.utils.swiper;
            return new Promise((resolve, reject) => {
                new asyncSwiper(ele, config).then(resolve).catch(reject);
            });
        } else {
            return new Promise(resolve => {
                resolve(new Swiper(ele[0], config));
            });
        }
    }
}

jQuery(window).on('elementor/frontend/init', () => {
    const addHandler = ($element) => {
        elementorFrontend.elementsHandler.addHandler(SlideshowClass, { $element });
    };

    elementorFrontend.hooks.addAction('frontend/element_ready/timeline-widget-addon.default', addHandler);
});