(function ($) {
    "use strict";

    const initTextCycle = ($scope) => {
        const wrapper = $scope.find('.sifency-cycle-wrapper')[0];
        if (!wrapper) return;

        if (typeof gsap === 'undefined') {
            console.error('Sifency Error: GSAP is not loaded.');
            return;
        }

        const words = wrapper.querySelectorAll('.sifency-cycle-word');
        if (words.length <= 1) return;

        const config = JSON.parse(wrapper.dataset.config || '{}');
        const pauseDuration = parseFloat(config.pause || 2);
        const animSpeed = parseFloat(config.speed || 0.8);
        const useBlur = config.blur === 'true';

        gsap.set(words, {
            yPercent: 100,
            opacity: 0,
            filter: useBlur ? "blur(10px)" : "blur(0px)",
            force3D: true
        });

        gsap.set(words[0], {
            yPercent: 0,
            opacity: 1,
            filter: "blur(0px)"
        });

        let currentIndex = 0;

        const animateNextWord = () => {
            const currentWord = words[currentIndex];

            currentIndex = (currentIndex + 1) % words.length;
            const nextWord = words[currentIndex];

            const tl = gsap.timeline();

            tl.to(currentWord, {
                yPercent: -100,
                opacity: 0,
                filter: useBlur ? "blur(10px)" : "blur(0px)",
                duration: animSpeed,
                ease: "power3.inOut"
            }, 0);

            tl.fromTo(nextWord,
                {
                    yPercent: 100,
                    opacity: 0,
                    filter: useBlur ? "blur(10px)" : "blur(0px)"
                },
                {
                    yPercent: 0,
                    opacity: 1,
                    filter: "blur(0px)",
                    duration: animSpeed,
                    ease: "power3.inOut"
                },
                0
            );
        };

        if (wrapper.cycleInterval) {
            clearInterval(wrapper.cycleInterval);
        }

        wrapper.cycleInterval = setInterval(animateNextWord, (pauseDuration + animSpeed) * 1000);
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/sifency-text-cycle.default',
            initTextCycle
        );
    });

})(jQuery);