(function ($) {
    "use strict";

    const initReelsSystem = ($scope) => {
        const container = $scope.find('.sifency-reels-container');
        const items = $scope.find('.sifency-reel-item');
        const isMuted = container.data('mute') === 'yes';

        // 1. Setup Intersection Observer
        const observerOptions = {
            root: null,
            threshold: 0.7 // Trigger when 70% of reel is visible
        };

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                const video = entry.target.querySelector('video');
                
                if (entry.isIntersecting) {
                    video.muted = isMuted;
                    video.play().catch(e => console.log("Autoplay blocked"));
                    entry.target.classList.add('is-playing');
                } else {
                    video.pause();
                    video.currentTime = 0; // Reset video
                    entry.target.classList.remove('is-playing');
                }
            });
        }, observerOptions);

        items.each(function() {
            observer.observe(this);
            
            // Progress Bar Logic
            const video = this.querySelector('video');
            const progressFill = this.querySelector('.progress-fill');
            
            video.addEventListener('timeupdate', () => {
                const pct = (video.currentTime / video.duration) * 100;
                $(progressFill).css('width', pct + '%');
            });

            // Click to Pause/Play
            $(this).on('click', function() {
                if (video.paused) video.play();
                else video.pause();
            });

            // Mute Toggle
            $(this).find('.sifency-reel-mute-toggle').on('click', (e) => {
                e.stopPropagation();
                video.muted = !video.muted;
                $(this).toggleClass('is-muted', video.muted);
            });
        });
    };

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