/**
 * Elementor调试工具
 * 用于诊断Elementor与GSAP动画的兼容性问题
 */

(function() {
    'use strict';
    
    // Elementor调试器
    const ElementorDebugger = {
        // 初始化调试器
        init: function() {
            
            // 检查Elementor是否加载
            this.checkElementorStatus();
            
            // 监听Elementor事件
            this.setupEventListeners();
            
            // 创建调试面板
            this.createDebugPanel();
        },
        
        // 检查Elementor状态
        checkElementorStatus: function() {
            
            // 检查Elementor元素
            const elementorElements = document.querySelectorAll('.elementor-element');
            
            // 检查动画元素
            const animatedElements = document.querySelectorAll('.elementor-invisible, [data-settings*="animation"]');
            
        },
        
        // 设置事件监听器
        setupEventListeners: function() {
            // 监听DOM变化
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (mutation.type === 'childList') {
                        mutation.addedNodes.forEach((node) => {
                            if (node.nodeType === Node.ELEMENT_NODE && 
                                node.classList && 
                                node.classList.contains('elementor-element')) {
                                this.analyzeElement(node);
                            }
                        });
                    }
                    
                    if (mutation.type === 'attributes' && 
                        mutation.attributeName === 'class' &&
                        mutation.target.classList.contains('elementor-element')) {
                        this.analyzeElement(mutation.target);
                    }
                });
            });
            
            observer.observe(document.body, {
                childList: true,
                subtree: true,
                attributes: true,
                attributeFilter: ['class']
            });
            
            // 监听Elementor钩子（如果可用）
            if (typeof elementorFrontend !== 'undefined' && elementorFrontend.hooks) {
                try {
                    elementorFrontend.hooks.addAction('frontend/element_ready/global', (scope) => {
                        console.log('Elementor全局元素准备就绪:', scope[0]);
                        this.analyzeElement(scope[0]);
                    });
                    
                    elementorFrontend.hooks.addAction('frontend/element_ready/widget', (scope) => {
                        console.log('Elementor小部件准备就绪:', scope[0]);
                        this.analyzeElement(scope[0]);
                    });
                } catch (error) {
                    console.error('绑定Elementor钩子失败:', error);
                }
            }
        },
        
        // 分析元素
        analyzeElement: function(element) {
            console.group('分析Elementor元素:', element);
            
            // 检查动画设置
            const hasInvisibleClass = element.classList.contains('elementor-invisible');
            const hasDataSettings = element.hasAttribute('data-settings');
            const dataSettings = element.getAttribute('data-settings');
            
            console.log('有elementor-invisible类:', hasInvisibleClass);
            console.log('有data-settings属性:', hasDataSettings);
            
            if (dataSettings) {
                try {
                    const settings = JSON.parse(dataSettings);
                    console.log('动画设置:', settings);
                    
                    if (settings._animation || settings.animation) {
                        console.log('检测到Elementor动画配置');
                    }
                } catch (error) {
                    console.warn('解析data-settings失败:', error);
                }
            }
            
            // 检查GSAP相关属性
            const hasGSAPPaused = element.hasAttribute('data-gsap-paused');
            const hasGSAPReady = element.hasAttribute('data-gsap-ready');
            const hasGSAPInitialized = element.hasAttribute('data-gsap-initialized');
            
            console.log('GSAP暂停状态:', hasGSAPPaused);
            console.log('GSAP准备状态:', hasGSAPReady);
            console.log('GSAP初始化状态:', hasGSAPInitialized);
            
            // 检查子元素
            const childElements = element.querySelectorAll('.elementor-element');
            if (childElements.length > 0) {
                console.log('子Elementor元素数量:', childElements.length);
            }
            
            console.groupEnd();
        },
        
        // 创建调试面板
        createDebugPanel: function() {
            // 只在开发环境或有调试参数时显示
            if (!window.location.search.includes('debug=elementor')) {
                return;
            }
            
            const panel = document.createElement('div');
            panel.id = 'elementor-debug-panel';
            panel.style.cssText = `
                position: fixed;
                top: 10px;
                right: 10px;
                width: 300px;
                background: rgba(0, 0, 0, 0.9);
                color: white;
                padding: 15px;
                border-radius: 5px;
                font-family: monospace;
                font-size: 12px;
                z-index: 999999;
                max-height: 400px;
                overflow-y: auto;
            `;
            
            panel.innerHTML = `
                <h3 style="margin: 0 0 10px 0;">Elementor调试面板</h3>
                <div id="debug-info"></div>
                <button onclick="ElementorDebugger.refreshInfo()" style="margin-top: 10px; padding: 5px 10px;">刷新信息</button>
                <button onclick="ElementorDebugger.testAnimations()" style="margin-top: 10px; padding: 5px 10px;">测试动画</button>
            `;
            
            document.body.appendChild(panel);
            
            // 暴露到全局作用域
            window.ElementorDebugger = this;
            
            this.refreshInfo();
        },
        
        // 刷新调试信息
        refreshInfo: function() {
            const infoDiv = document.getElementById('debug-info');
            if (!infoDiv) return;
            
            const elementorElements = document.querySelectorAll('.elementor-element');
            const animatedElements = document.querySelectorAll('.elementor-invisible');
            const gsapPausedElements = document.querySelectorAll('[data-gsap-paused]');
            const gsapReadyElements = document.querySelectorAll('[data-gsap-ready]');
            
            infoDiv.innerHTML = `
                <div>Elementor元素: ${elementorElements.length}</div>
                <div>动画元素: ${animatedElements.length}</div>
                <div>GSAP暂停: ${gsapPausedElements.length}</div>
                <div>GSAP准备: ${gsapReadyElements.length}</div>
                <div>GSAP加载: ${typeof gsap !== 'undefined' ? '是' : '否'}</div>
                <div>Elementor前端: ${typeof elementorFrontend !== 'undefined' ? '是' : '否'}</div>
            `;
        },
        
        // 测试动画
        testAnimations: function() {
            
            // 查找所有Elementor元素
            const elements = document.querySelectorAll('.elementor-element');
            
            elements.forEach((element, index) => {
                setTimeout(() => {
                    
                    // 触发兼容性检查
                    if (window.GSAPElementorCompatibility) {
                        window.GSAPElementorCompatibility.handleElementorElement(element);
                    }
                }, index * 100);
            });
        }
    };
    
    // 等待DOM加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            ElementorDebugger.init();
        });
    } else {
        ElementorDebugger.init();
    }
    
    // 暴露到全局作用域
    window.ElementorDebugger = ElementorDebugger;
    
})();