/**
 * 恒辉核心页面 - Accordion 交互功能 + GSAP 动画
 */

(function($) {
    'use strict';
    
    // 等待DOM加载完成
    $(document).ready(function() {
        initAccordion();
        initGSAPAnimations();
        initProfessionalCarousel();
    });
    
    /**
     * 初始化专业领域轮播
     */
    function initProfessionalCarousel() {
        const carouselContainer = $('#professionalCarousel');
        if (carouselContainer.length === 0) {
            return;
        }

        // 检查SimpleCarousel是否可用
        if (typeof SimpleCarousel === 'undefined') {
            return;
        }

        // 轮播配置
         const carouselOptions = {
             autoplay: true,
             autoplayDelay: 4000,
             loop: true,
             navigation: true,
             pagination: false,
             touchEnabled: true,
             slidesPerView: 5, // 一行显示5个卡片
             onSlideChange: function(currentIndex, previousIndex) {
                 // 添加GSAP动画效果
                 animateProfessionalCards(currentIndex);
             }
         };

        // 初始化轮播
        try {
            const carousel = new SimpleCarousel(carouselContainer[0], carouselOptions);
            
            // 添加鼠标悬停暂停功能
            carouselContainer.on('mouseenter', function() {
                carousel.pauseAutoplay();
            }).on('mouseleave', function() {
                carousel.resumeAutoplay();
            });
            
            // 初始动画
            setTimeout(() => {
                animateProfessionalCards(0);
            }, 500);
            
        } catch (error) {
        }
    }
    
    /**
     * 专业领域卡片动画
     */
    function animateProfessionalCards(currentIndex) {
        if (typeof gsap === 'undefined') {
            return;
        }
        
        const cards = $('.professional-card');
        
        // 重置所有卡片
        gsap.set(cards, {
            opacity: 0,
            y: 30,
            scale: 0.9
        });
        
        // 计算当前显示的卡片（一行5个）
        const startIndex = Math.floor(currentIndex / 5) * 5;
        const visibleCards = cards.slice(startIndex, startIndex + 5);
        
        // 动画显示当前卡片
        gsap.to(visibleCards, {
            opacity: 1,
            y: 0,
            scale: 1,
            duration: 0.6,
            stagger: 0.1,
            ease: 'back.out(1.7)'
        });
        
        // 为卡片添加悬停动画
        visibleCards.each(function() {
            const card = $(this);
            const icon = card.find('.card-icon');
            const number = card.find('.card-number');
            
            card.off('mouseenter mouseleave').on('mouseenter', function() {
                gsap.to(card, {
                    y: -10,
                    scale: 1.05,
                    duration: 0.3,
                    ease: 'power2.out'
                });
                
                gsap.to(icon, {
                    rotation: 10,
                    scale: 1.1,
                    duration: 0.3,
                    ease: 'power2.out'
                });
                
                gsap.to(number, {
                    scale: 1.2,
                    duration: 0.3,
                    ease: 'power2.out'
                });
            }).on('mouseleave', function() {
                gsap.to(card, {
                    y: 0,
                    scale: 1,
                    duration: 0.3,
                    ease: 'power2.out'
                });
                
                gsap.to(icon, {
                    rotation: 0,
                    scale: 1,
                    duration: 0.3,
                    ease: 'power2.out'
                });
                
                gsap.to(number, {
                    scale: 1,
                    duration: 0.3,
                    ease: 'power2.out'
                });
            });
        });
    }
    
    /**
     * 初始化Accordion功能
     */
    function initAccordion() {
        const accordionButtons = $('.accordion-button');
        
        if (accordionButtons.length === 0) {
            return;
        }
        
        // 为每个accordion按钮添加点击事件
        accordionButtons.on('click', function(e) {
            e.preventDefault();
            
            const button = $(this);
            const targetId = button.data('target');
            const targetCollapse = $('#' + targetId);
            const isActive = button.hasClass('active');
            
            // 检查目标元素是否存在
            if (targetCollapse.length === 0) {
                return;
            }
            
            // 如果当前项已经是激活状态，则关闭它
            if (isActive) {
                closeAccordionItem(button, targetCollapse);
            } else {
                // 关闭其他所有项
                closeAllAccordionItems();
                // 打开当前项
                openAccordionItem(button, targetCollapse);
            }
        });
        
        // 确保默认打开的项正确显示
        setTimeout(function() {
            const activeButton = $('.accordion-button.active');
            if (activeButton.length > 0) {
                const targetId = activeButton.data('target');
                const targetCollapse = $('#' + targetId);
                if (targetCollapse.length > 0 && !targetCollapse.hasClass('show')) {
                    targetCollapse.addClass('show');
                }
            }
        }, 100);
    }
    
    /**
     * 打开accordion项
     */
    function openAccordionItem(button, collapse) {
        // 检查是否有GSAP增强动画
        if (typeof window.openAccordionItemWithGSAP === 'function') {
            window.openAccordionItemWithGSAP(button, collapse);
        } else {
            // 纯CSS动画版本 - 不设置内联样式
            button.addClass('active').attr('aria-expanded', 'true');
            collapse.addClass('show');
        }
    }
    
    /**
     * 关闭accordion项
     */
    function closeAccordionItem(button, collapse) {
        // 检查是否有GSAP增强动画
        if (typeof window.closeAccordionItemWithGSAP === 'function') {
            window.closeAccordionItemWithGSAP(button, collapse);
        } else {
            // 纯CSS动画版本 - 不设置内联样式
            button.removeClass('active').attr('aria-expanded', 'false');
            collapse.removeClass('show');
        }
    }
    
    /**
     * 关闭所有accordion项
     */
    function closeAllAccordionItems() {
        $('.accordion-button').each(function() {
            const button = $(this);
            const targetId = button.data('target');
            const targetCollapse = $('#' + targetId);
            
            if (button.hasClass('active')) {
                closeAccordionItem(button, targetCollapse);
            }
        });
    }
    
    /**
     * 响应式处理
     */
    function handleResponsive() {
        const windowWidth = $(window).width();
        
        // 移除可能干扰CSS动画的内联样式
        $('.accordion-collapse').each(function() {
            $(this).css('max-height', '');
        });
    }
    
    // 窗口大小改变时重新处理响应式
    $(window).on('resize', function() {
        handleResponsive();
    });
    
    // 初始化时处理响应式
    handleResponsive();
    
    /**
     * 初始化GSAP动画
     */
    function initGSAPAnimations() {
        // 检查GSAP是否已加载
        if (typeof gsap === 'undefined') {
            return;
        }
        
        // 等待兼容性管理器初始化
        if (window.GSAPElementorAPI) {
            
            // 使用兼容性API初始化动画
            initPageLoadAnimationsWithAPI();
            initScrollAnimationsWithAPI();
        } else {
            
            // 页面加载动画
            initPageLoadAnimations();
            
            // 滚动触发动画
            initScrollAnimations();
        }
        
        // Accordion动画增强
        enhanceAccordionAnimations();
    }
    
    /**
     * 使用兼容性API的页面加载动画
     */
    function initPageLoadAnimationsWithAPI() {
        // 设置初始状态
        gsap.set('.section-title', { opacity: 0, y: 50 });
        gsap.set('.section-description', { opacity: 0, y: 30 });
        gsap.set('.accordion-item', { opacity: 0, x: -30 });
        gsap.set('.system-image img', { opacity: 0, scale: 0.8 });
        
        // 创建时间线动画
        const tl = gsap.timeline({ delay: 0.3 });
        
        tl.to('.section-title', {
            opacity: 1,
            y: 0,
            duration: 0.8,
            ease: 'power2.out',
            onComplete: function() {
                $('.section-title').addClass('animated');
            }
        })
        .to('.section-description', {
            opacity: 1,
            y: 0,
            duration: 0.6,
            ease: 'power2.out'
        }, '-=0.4')
        .to('.accordion-item', {
            opacity: 1,
            x: 0,
            duration: 0.6,
            stagger: 0.1,
            ease: 'power2.out'
        }, '-=0.3')
        .to('.system-image img', {
            opacity: 1,
            scale: 1,
            duration: 0.8,
            ease: 'back.out(1.7)'
        }, '-=0.5');
        
        // 注册动画到管理器
        if (window.GSAPAnimationManager) {
            window.GSAPAnimationManager.register('pageLoad', tl);
        }
    }
    
    /**
     * 使用兼容性API的滚动触发动画
     */
    function initScrollAnimationsWithAPI() {
        // 检查ScrollTrigger是否已加载
        if (typeof ScrollTrigger === 'undefined') {
            return;
        }
        
        // 使用兼容性API创建ScrollTrigger
        const floatingAnimation = window.GSAPElementorAPI.createScrollTrigger({
            trigger: '.system-image img',
            start: 'top bottom',
            end: 'bottom top',
            onEnter: function() {
                // 图片悬浮动画 - 延迟启动，避免与页面加载动画冲突
                setTimeout(function() {
                    const floatTween = gsap.to('.system-image img', {
                        y: -10,
                        duration: 2,
                        ease: 'power1.inOut',
                        yoyo: true,
                        repeat: -1
                    });
                    
                    if (window.GSAPAnimationManager) {
                        window.GSAPAnimationManager.register('imageFloat', floatTween);
                    }
                }, 2000);
            }
        });
        
        // 滚动时的视差效果
        const parallaxTrigger = window.GSAPElementorAPI.createScrollTrigger({
            trigger: '.about-content',
            start: 'top bottom',
            end: 'bottom top',
            scrub: true,
            animation: gsap.to('.about-content', {
                backgroundPosition: '50% 100px',
                ease: 'none'
            })
        });
    }
    
    /**
     * 页面加载动画
     */
    function initPageLoadAnimations() {
        // 等待GSAP兼容性就绪
        if (!document.body.classList.contains('gsap-ready')) {
            document.addEventListener('gsapCompatibilityReady', initPageLoadAnimations);
            return;
        }
        
        // 设置初始状态
        gsap.set('.section-title', { opacity: 0, y: 50 });
        gsap.set('.section-description', { opacity: 0, y: 30 });
        gsap.set('.accordion-item', { opacity: 0, x: -30 });
        gsap.set('.system-image img', { opacity: 0, scale: 0.8 });
        
        // 创建时间线动画
        const tl = gsap.timeline({ delay: 0.3 });
        
        tl.to('.section-title', {
            opacity: 1,
            y: 0,
            duration: 0.8,
            ease: 'power2.out',
            onComplete: function() {
                $('.section-title').addClass('animated');
            }
        })
        .to('.section-description', {
            opacity: 1,
            y: 0,
            duration: 0.6,
            ease: 'power2.out'
        }, '-=0.4')
        .to('.accordion-item', {
            opacity: 1,
            x: 0,
            duration: 0.6,
            stagger: 0.1,
            ease: 'power2.out'
        }, '-=0.3')
        .to('.system-image img', {
            opacity: 1,
            scale: 1,
            duration: 0.8,
            ease: 'back.out(1.7)'
        }, '-=0.5');
    }
    
    /**
     * 滚动触发动画
     */
    function initScrollAnimations() {
        // 检查ScrollTrigger是否已加载
        if (typeof ScrollTrigger === 'undefined') {
            console.warn('ScrollTrigger plugin not loaded');
            return;
        }
        
        // 注册ScrollTrigger插件
        gsap.registerPlugin(ScrollTrigger);
        
        // 图片悬浮动画 - 延迟启动，避免与页面加载动画冲突
        setTimeout(function() {
            gsap.to('.system-image img', {
                y: -10,
                duration: 2,
                ease: 'power1.inOut',
                yoyo: true,
                repeat: -1
            });
        }, 2000);
        
        // 滚动时的视差效果
        gsap.to('.about-content', {
            backgroundPosition: '50% 100px',
            ease: 'none',
            scrollTrigger: {
                trigger: '.about-content',
                start: 'top bottom',
                end: 'bottom top',
                scrub: true
            }
        });
    }
    
    /**
     * 增强Accordion动画
     */
    function enhanceAccordionAnimations() {
        // 为accordion按钮添加悬停动画
        $('.accordion-button').hover(
            function() {
                gsap.to($(this), {
                    scale: 1.02,
                    duration: 0.3,
                    ease: 'power2.out'
                });
            },
            function() {
                gsap.to($(this), {
                    scale: 1,
                    duration: 0.3,
                    ease: 'power2.out'
                });
            }
        );
        
        // 纯CSS动画版本 - 避免JavaScript动画冲突
        window.openAccordionItemWithGSAP = function(button, collapse) {
            button.addClass('active').attr('aria-expanded', 'true');
            collapse.addClass('show');
        };
        
        // 纯CSS动画版本 - 避免JavaScript动画冲突
        window.closeAccordionItemWithGSAP = function(button, collapse) {
            button.removeClass('active').attr('aria-expanded', 'false');
            collapse.removeClass('show');
        };
    }
    
})(jQuery);