// Content Carousel with Video, Vertical Mode, and Multi-Slide Support
document.addEventListener("DOMContentLoaded", function () {
    initContentCarousels();
});

// Also initialize when Elementor frontend is ready (for dynamic content)
(function($){
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/okthemes-content-carousel.default', function($element) {
            initContentCarousels();
        });
    });
})(jQuery);

/**
 * Initialize all content carousels
 */
function initContentCarousels() {
    document.querySelectorAll(".okthemes-content-carousel").forEach(function (carousel, index) {
        // Skip if already initialized
        if (carousel.classList.contains('okt-initialized')) {
            return;
        }
        
        // Namespace Swiper classes to avoid conflicts with Elementor
        carousel.querySelectorAll('.swiper-wrapper').forEach(el => {
            el.classList.add('okt-swiper-wrapper');
        });
        
        carousel.querySelectorAll('.swiper-slide').forEach(el => {
            el.classList.add('okt-swiper-slide');
        });
        
        carousel.querySelectorAll('.swiper-pagination').forEach(el => {
            el.classList.add('okt-swiper-pagination');
        });
        
        carousel.querySelectorAll('.swiper-button-next').forEach(el => {
            el.classList.add('okt-swiper-button-next');
        });
        
        carousel.querySelectorAll('.swiper-button-prev').forEach(el => {
            el.classList.add('okt-swiper-button-prev');
        });
        
        let settings = {
            navigation: carousel.dataset.navigation || 'both',
            autoplay: carousel.dataset.autoplay === 'yes',
            autoplaySpeed: parseInt(carousel.dataset.autoplaySpeed) || 5000,
            loop: carousel.dataset.loop === 'yes',
            transition: carousel.dataset.transition || 'slide',
            transitionSpeed: parseInt(carousel.dataset.transitionSpeed) || 500,
            pauseOnHover: carousel.dataset.pauseOnHover === 'true',
            stopOnVideo: carousel.dataset.stopOnVideo === 'true',
            direction: carousel.dataset.direction || 'horizontal',
            slidesPerView: carousel.dataset.slidesPerView || 1,
            slidesPerViewTablet: carousel.dataset.slidesPerViewTablet || '',
            slidesPerViewMobile: carousel.dataset.slidesPerViewMobile || '',
            spaceBetween: parseInt(carousel.dataset.spaceBetween) || 30,
            centeredSlides: carousel.dataset.centeredSlides === 'true'
        };

        // Convert 'auto' to the string 'auto' for slidesPerView
        if (settings.slidesPerView === 'auto') {
            settings.slidesPerView = 'auto';
        } else {
            settings.slidesPerView = parseInt(settings.slidesPerView);
        }

        // Configure breakpoints for responsive behavior
        const breakpoints = {};
        
        // Mobile breakpoint (up to 767px)
        if (settings.slidesPerViewMobile) {
            breakpoints[767] = {
                slidesPerView: settings.slidesPerViewMobile === 'auto' ? 'auto' : parseInt(settings.slidesPerViewMobile)
            };
        }
        
        // Tablet breakpoint (768px to 991px)
        if (settings.slidesPerViewTablet) {
            breakpoints[991] = {
                slidesPerView: settings.slidesPerViewTablet === 'auto' ? 'auto' : parseInt(settings.slidesPerViewTablet)
            };
        }

        let swiperOptions = {
            direction: settings.direction,
            slidesPerView: settings.slidesPerView,
            spaceBetween: settings.spaceBetween,
            centeredSlides: settings.centeredSlides,
            loop: settings.loop,
            speed: settings.transitionSpeed,
            autoplay: settings.autoplay ? {
                delay: settings.autoplaySpeed,
                disableOnInteraction: settings.pauseOnHover,
            } : false,
            effect: settings.transition,
            breakpoints: Object.keys(breakpoints).length ? breakpoints : undefined,
            
            // Use custom class names to avoid conflicts with Elementor
            wrapperClass: 'okt-swiper-wrapper',
            slideClass: 'okt-swiper-slide',
            containerModifierClass: 'okt-swiper-container-',
            
            navigation: (settings.navigation === 'arrows' || settings.navigation === 'both') ? {
                nextEl: carousel.querySelector(".okt-swiper-button-next"),
                prevEl: carousel.querySelector(".okt-swiper-button-prev"),
            } : false,
            pagination: (settings.navigation === 'dots' || settings.navigation === 'both') ? {
                el: carousel.querySelector(".okt-swiper-pagination"),
                clickable: true,
                bulletClass: 'okt-swiper-pagination-bullet',
                bulletActiveClass: 'okt-swiper-pagination-bullet-active',
                renderBullet: function (index, className) {
                    let slides = carousel.querySelectorAll(".okt-swiper-slide .pagination-title");
                    let slideName = slides[index] ? slides[index].textContent : 'Slide ' + (index + 1);
                    return '<span class="' + className + '"><span class="bullet"></span><span class="slide-name">' + slideName + '</span></span>';
                }
            } : false,
            on: {
                init: function() {
                    // Mark as initialized
                    carousel.classList.add('okt-initialized');
                },
                slideChange: function() {
                    // Pause all videos when changing slides
                    pauseAllVideos(carousel);
                }
            }
        };

        // Initialize Swiper
        let swiperInstance = new Swiper(carousel, swiperOptions);
        
        // Store swiper instance for later use
        carousel.swiperInstance = swiperInstance;
        
        // Setup videos if any in this carousel
        setupVideos(carousel, swiperInstance, settings.stopOnVideo);
    });
}

function setupVideos(carousel, swiper, stopOnVideo) {
    // Setup video overlay click handlers
    setupVideoOverlays(carousel, swiper, stopOnVideo);
    
    // Setup video event listeners for HTML5 videos
    setupVideoEventListeners(carousel, swiper, stopOnVideo);
    
    // Load YouTube API if needed
    if (carousel.querySelectorAll('iframe[src*="youtube.com"]').length > 0) {
        loadYouTubeAPI();
    }
    
    // Load Vimeo API if needed
    if (carousel.querySelectorAll('iframe[src*="vimeo.com"]').length > 0) {
        loadVimeoAPI();
    }
}

function setupVideoOverlays(carousel, swiper, stopOnVideo) {
    carousel.querySelectorAll('.elementor-custom-embed-play').forEach(function(playButton) {
        playButton.addEventListener('click', function() {
            const overlay = this.closest('.elementor-custom-embed-image-overlay');
            const videoId = overlay.getAttribute('data-video-id');
            
            if (videoId) {
                // Handle iframe videos (YouTube, Vimeo)
                const iframe = document.getElementById(videoId);
                
                if (iframe) {
                    // Show the iframe
                    iframe.style.display = 'block';
                    
                    // Hide the overlay
                    overlay.style.display = 'none';
                    
                    // Add autoplay parameter to iframe src
                    let src = iframe.getAttribute('src');
                    if (src.indexOf('autoplay=1') === -1) {
                        src += src.indexOf('?') !== -1 ? '&autoplay=1' : '?autoplay=1';
                        iframe.setAttribute('src', src);
                    }
                    
                    // Stop carousel autoplay if needed
                    if (stopOnVideo && swiper.autoplay.running) {
                        swiper.autoplay.stop();
                    }
                }
                
                // Handle self-hosted videos
                const videoContainer = document.getElementById(videoId + '.video-container');
                
                if (videoContainer) {
                    // Show the video container
                    videoContainer.style.display = 'block';
                    
                    // Hide the overlay
                    overlay.style.display = 'none';
                    
                    // Play the video
                    const video = videoContainer.querySelector('video');
                    if (video) {
                        video.play();
                        
                        // Stop carousel autoplay if needed
                        if (stopOnVideo && swiper.autoplay.running) {
                            swiper.autoplay.stop();
                        }
                    }
                }
            }
        });
    });
}

function setupVideoEventListeners(carousel, swiper, stopOnVideo) {
    // Self-hosted videos
    carousel.querySelectorAll('video').forEach(function(video) {
        video.addEventListener('play', function() {
            if (stopOnVideo && swiper.autoplay.running) {
                swiper.autoplay.stop();
            }
        });
        
        video.addEventListener('pause', function() {
            if (stopOnVideo && swiper.autoplay.enabled) {
                swiper.autoplay.start();
            }
        });
        
        video.addEventListener('ended', function() {
            if (stopOnVideo && swiper.autoplay.enabled) {
                swiper.autoplay.start();
            }
        });
    });
}

function pauseAllVideos(carousel) {
    // Pause YouTube videos
    carousel.querySelectorAll('iframe[src*="youtube.com"]').forEach(function(iframe) {
        try {
            // Only try to pause if the iframe is visible (not in an overlay)
            if (iframe.style.display !== 'none') {
                iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
            }
        } catch (e) {
            console.error('Error pausing YouTube video:', e);
        }
    });
    
    // Pause Vimeo videos
    carousel.querySelectorAll('iframe[src*="vimeo.com"]').forEach(function(iframe) {
        try {
            // Only try to pause if the iframe is visible (not in an overlay)
            if (iframe.style.display !== 'none') {
                iframe.contentWindow.postMessage('{"method":"pause"}', '*');
            }
        } catch (e) {
            console.error('Error pausing Vimeo video:', e);
        }
    });
    
    // Pause self-hosted videos
    carousel.querySelectorAll('video').forEach(function(video) {
        try {
            video.pause();
        } catch (e) {
            console.error('Error pausing HTML5 video:', e);
        }
    });
}

function loadYouTubeAPI() {
    if (window.YT || document.querySelector('script[src*="youtube.com/iframe_api"]')) {
        return;
    }
    
    const tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    const firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
    // Setup global callback
    window.onYouTubeIframeAPIReady = function() {
        // API is loaded
    };
}

function loadVimeoAPI() {
    if (window.Vimeo || document.querySelector('script[src*="player.vimeo.com/api/player.js"]')) {
        return;
    }
    
    const tag = document.createElement('script');
    tag.src = 'https://player.vimeo.com/api/player.js';
    const firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}

// Post message event listener for video events
window.addEventListener('message', function(event) {
    if (typeof event.data === 'string') {
        try {
            const data = JSON.parse(event.data);
            const iframe = document.querySelector('iframe[src*="' + event.origin + '"]');
            
            if (!iframe) return;
            
            const carousel = iframe.closest('.okthemes-content-carousel');
            if (!carousel) return;
            
            const swiper = carousel.swiperInstance;
            const stopOnVideo = carousel.dataset.stopOnVideo === 'true';
            
            if (!swiper || !stopOnVideo) return;
            
            // Handle YouTube events
            if (event.origin.includes('youtube.com')) {
                // YT.PlayerState.PLAYING = 1
                if (data.event === 'onStateChange' && data.info === 1) {
                    swiper.autoplay.stop();
                }
                // YT.PlayerState.ENDED = 0, YT.PlayerState.PAUSED = 2
                else if (data.event === 'onStateChange' && (data.info === 0 || data.info === 2) && swiper.params.autoplay.enabled) {
                    swiper.autoplay.start();
                }
            }
            
            // Handle Vimeo events
            if (event.origin.includes('vimeo.com')) {
                if (data.event === 'play') {
                    swiper.autoplay.stop();
                } else if ((data.event === 'pause' || data.event === 'ended') && swiper.params.autoplay.enabled) {
                    swiper.autoplay.start();
                }
            }
        } catch (e) {
            // Not a JSON message, ignore
        }
    }
});