(function ($) {
    "use strict";

    /**
     * Sifency Multi-Scroll Columns
     * Uses GSAP ScrollTrigger for professional pinning and multi-directional scrolling.
     */
    const initMultiScroll = ($scope) => {
        const track = $scope.find('.sifency-scroll-track')[0];
        if (!track) return;

        const sticky   = track.querySelector('.sifency-scroll-sticky');
        const columns  = track.querySelectorAll('.sifency-scroll-column');
        const speed    = parseFloat(track.dataset.speed || 1.5);
        const isLoop   = track.dataset.loop === 'yes';

        // Register GSAP Plugin
        if (typeof gsap !== 'undefined' && typeof ScrollTrigger !== 'undefined') {
            gsap.registerPlugin(ScrollTrigger);
        } else {
            console.warn('Sifency Multi-Scroll: GSAP or ScrollTrigger not found.');
            return;
        }

        // Setup Infinite Loop Clones
        if (isLoop) {
            columns.forEach(col => {
                const part = col.querySelector('.sifency-scroll-col-part');
                if (part && !col.querySelector('.sifency-scroll-col-clone')) {
                    const clone = part.cloneNode(true);
                    clone.classList.add('sifency-scroll-col-clone');
                    col.appendChild(clone);
                }
            });
        }

        const mm = gsap.matchMedia();

        // Desktop Only Animation (matches CSS @media 768px)
        mm.add("(min-width: 768px)", () => {
            
            const ST = ScrollTrigger.create({
                trigger: track,
                start: "top top",
                end: "bottom bottom",
                pin: sticky,
                pinSpacing: false, 
                scrub: 1, // Smooth catch-up
                onUpdate: (self) => {
                    const progress = self.progress;
                    const totalMove = track.offsetHeight * speed;

                    columns.forEach(col => {
                        const dir    = col.dataset.direction === 'reverse' ? 1 : -1;
                        const offset = parseFloat(col.dataset.offset || 0);
                        const part   = col.querySelector('.sifency-scroll-col-part');
                        if (!part) return;

                        const partHeight = part.offsetHeight;
                        let yMove = 0;

                        if (isLoop && partHeight > 0) {
                            // Infinite Loop Logic
                            const moveDistance = (progress * totalMove) + (offset * partHeight);
                            const loopOffset   = moveDistance % partHeight;

                            if (dir === -1) {
                                yMove = -loopOffset;
                            } else {
                                yMove = -partHeight + loopOffset;
                            }
                        } else {
                            // Standard Non-Looping Scroll
                            const stickyHeight = sticky.offsetHeight;
                            const scrollableContent = col.scrollHeight - stickyHeight;
                            const travel = scrollableContent * speed * progress;

                            if (dir === -1) {
                                yMove = -travel;
                            } else {
                                yMove = -scrollableContent + travel;
                            }
                        }

                        gsap.set(col, { y: yMove, force3D: true });
                    });
                }
            });

            return () => {
                // Cleanup on resize/destroy
                ST.kill();
                columns.forEach(col => gsap.set(col, { clearProps: "all" }));
            };
        });
    };

    $(window).on('elementor/frontend/init', () => {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-multi-scroll.default', initMultiScroll);
    });

})(jQuery);
