/**
 * Social Activities Carousel JavaScript
 * 社会活动轮播功能脚本
 * 
 * @package Nenghui Energy Theme
 * @since 1.0.0
 */

(function($) {
    'use strict';

    class SocialActivitiesCarousel {
        constructor() {
            this.carousels = [];
            this.init();
        }

        init() {
            // 等待DOM加载完成
            $(document).ready(() => {
                this.initCarousels();
            });
        }

        initCarousels() {
            $('.social-activities-carousel').each((index, element) => {
                const $carousel = $(element);
                const slidesPerView = parseInt($carousel.data('slides-per-view')) || 3;
                
                // 检查是否已经初始化
                if ($carousel.data('carousel-initialized')) {
                    return;
                }
                
                // 标记为已初始化
                $carousel.data('carousel-initialized', true);
                
                // 创建轮播实例
                const carousel = new SimpleCarousel(element, {
                    autoplay: true,
                    autoplayDelay: 5000,
                    loop: true,
                    navigation: true,
                    pagination: true,
                    touchEnabled: true,
                    slidesPerView: slidesPerView,
                    spaceBetween: 30,
                    onSlideChange: (activeIndex) => {
                        this.onSlideChange($carousel, activeIndex);
                    },
                    onInit: () => {
                        this.onCarouselInit($carousel);
                    }
                });
                
                this.carousels.push({
                    element: $carousel,
                    instance: carousel
                });
                
                // 绑定自定义事件
                this.bindEvents($carousel, carousel);
                
                console.log('Social Activities Carousel initialized:', {
                    slidesPerView: slidesPerView,
                    totalSlides: $carousel.find('.carousel-slide').length
                });
            });
        }

        bindEvents($carousel, carouselInstance) {
            // 鼠标悬停暂停自动播放
            $carousel.on('mouseenter', () => {
                carouselInstance.pauseAutoplay();
            });

            $carousel.on('mouseleave', () => {
                carouselInstance.resumeAutoplay();
            });

            // 分页器点击事件已在SimpleCarousel中处理，这里不需要重复绑定

            // 卡片点击统计（可选）
            $carousel.find('.social-activity-card').on('click', function(e) {
                // 如果点击的不是链接，则跳转到文章页面
                if (!$(e.target).closest('a').length) {
                    const $link = $(this).find('h3 a, .view-details-btn').first();
                    if ($link.length) {
                        window.location.href = $link.attr('href');
                    }
                }
            });

            // 键盘导航支持
            $carousel.on('keydown', (e) => {
                switch(e.keyCode) {
                    case 37: // 左箭头
                        e.preventDefault();
                        carouselInstance.prev();
                        break;
                    case 39: // 右箭头
                        e.preventDefault();
                        carouselInstance.next();
                        break;
                }
            });

            // 使轮播容器可聚焦以支持键盘导航
            $carousel.attr('tabindex', '0');
        }

        onSlideChange($carousel, activeIndex) {
            // 更新分页器状态
            $carousel.find('.carousel-pagination-bullet').removeClass('active');
            $carousel.find('.carousel-pagination-bullet').eq(activeIndex).addClass('active');
            
            // 添加切换动画效果
            $carousel.find('.carousel-slide').removeClass('slide-active');
            $carousel.find('.carousel-slide').eq(activeIndex).addClass('slide-active');
            
            // 触发自定义事件
            $carousel.trigger('socialActivitiesSlideChange', [activeIndex]);
        }

        onCarouselInit($carousel) {
            // 轮播初始化完成后的处理
            $carousel.addClass('carousel-ready');
            
            // 设置初始活动状态
            $carousel.find('.carousel-slide').first().addClass('slide-active');
            
            // 触发自定义事件
            $carousel.trigger('socialActivitiesCarouselReady');
        }

        // 公共方法：获取轮播实例
        getCarouselInstance(selector) {
            const carousel = this.carousels.find(item => 
                item.element.is(selector) || item.element.find(selector).length
            );
            return carousel ? carousel.instance : null;
        }

        // 公共方法：销毁所有轮播
        destroy() {
            this.carousels.forEach(carousel => {
                if (carousel.instance && typeof carousel.instance.destroy === 'function') {
                    carousel.instance.destroy();
                }
                carousel.element.removeData('carousel-initialized');
            });
            this.carousels = [];
        }

        // 公共方法：重新初始化
        reinit() {
            this.destroy();
            this.initCarousels();
        }
    }

    // 创建全局实例
    window.SocialActivitiesCarousel = SocialActivitiesCarousel;

    // 自动初始化
    const socialActivitiesCarousel = new SocialActivitiesCarousel();

    // 暴露到全局作用域以便外部调用
    window.socialActivitiesCarouselInstance = socialActivitiesCarousel;

    // 支持动态内容加载后重新初始化
    $(document).on('contentUpdated socialActivitiesContentLoaded', function() {
        socialActivitiesCarousel.reinit();
    });

    // 窗口大小改变时重新计算
    let resizeTimer;
    $(window).on('resize', function() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(() => {
            socialActivitiesCarousel.carousels.forEach(carousel => {
                if (carousel.instance && typeof carousel.instance.updateSlides === 'function') {
                    carousel.instance.updateSlides();
                }
            });
        }, 250);
    });

    // 页面可见性变化时处理自动播放
    document.addEventListener('visibilitychange', function() {
        socialActivitiesCarousel.carousels.forEach(carousel => {
            if (carousel.instance) {
                if (document.hidden) {
                    carousel.instance.pauseAutoplay();
                } else {
                    carousel.instance.resumeAutoplay();
                }
            }
        });
    });

})(jQuery);