/**
 * AYSA Elementor Integration Handler
 * Extends existing AYSA functions to work with Elementor
 */

// Global Elementor handler object
window.aysaElementorHandler = {
    isElementorActive: false,
    
    /**
     * Initialize the Elementor handler
     */
    init: function() {
        console.log('🚀 AYSA Elementor Handler: Initializing...');
        
        // Check if AYSA Elementor AJAX data is available
        if (typeof aysaElementorAjax !== 'undefined') {
            this.isElementorActive = aysaElementorAjax.is_elementor_active;
            console.log('✅ AYSA Elementor: AJAX data found', {
                isElementorActive: this.isElementorActive,
                ajaxUrl: aysaElementorAjax.ajax_url,
                hasNonce: !!aysaElementorAjax.nonce
            });
        } else {
            console.warn('⚠️ AYSA Elementor: AJAX data not found - checking for Elementor manually');
            
            // Fallback: Try to detect Elementor manually
            this.isElementorActive = this.detectElementorManually();
        }
        
        // Add Elementor support to existing AYSA functions
        this.extendExistingFunctions();
        
        console.log('✅ AYSA Elementor Handler initialized successfully', {
            isElementorActive: this.isElementorActive,
            currentPostId: this.getCurrentPostId(),
            location: window.location.href
        });
    },
    
    /**
     * Manual Elementor detection fallback
     */
    detectElementorManually: function() {
        // Check for Elementor editor
        if (window.elementor || window.elementorFrontend) {
            console.log('✅ AYSA Elementor: Detected via window.elementor');
            return true;
        }
        
        // Check for Elementor body class
        if (document.body.classList.contains('elementor-default') || 
            document.body.classList.contains('elementor-kit')) {
            console.log('✅ AYSA Elementor: Detected via body class');
            return true;
        }
        
        // Check for Elementor meta elements
        const elementorMeta = document.querySelector('meta[name="generator"][content*="Elementor"]');
        if (elementorMeta) {
            console.log('✅ AYSA Elementor: Detected via meta tag');
            return true;
        }
        
        console.log('❌ AYSA Elementor: Not detected manually');
        return false;
    },
    
    /**
     * Extend existing AYSA update functions to include Elementor support
     */
    extendExistingFunctions: function() {
        // Wait for AYSA functions to be available
        const waitForFunctions = () => {
            // Check if functions are available
            const originalUpdateWooCommerceDescription = window.updateWooCommerceDescription;
            const originalUpdateWooCommerceShortDescription = window.updateWooCommerceShortDescription;
            
            console.log('AYSA Elementor: Checking for functions...', {
                updateWooCommerceDescription: typeof originalUpdateWooCommerceDescription,
                updateWooCommerceShortDescription: typeof originalUpdateWooCommerceShortDescription
            });
            
            if (typeof originalUpdateWooCommerceDescription === 'function' || 
                typeof originalUpdateWooCommerceShortDescription === 'function') {
                
                // Extend updateWooCommerceDescription
                if (typeof originalUpdateWooCommerceDescription === 'function') {
                    window.updateWooCommerceDescription = (content) => {
                        console.log('AYSA Elementor: Extending updateWooCommerceDescription with content length:', content?.length);
                        
                        // Call original function first
                        originalUpdateWooCommerceDescription(content);
                        
                        // Add Elementor support
                        this.updateElementorContent(content, 'description');
                    };
                    console.log('✅ Extended updateWooCommerceDescription with Elementor support');
                }
                
                // Extend updateWooCommerceShortDescription
                if (typeof originalUpdateWooCommerceShortDescription === 'function') {
                    window.updateWooCommerceShortDescription = (content) => {
                        console.log('AYSA Elementor: Extending updateWooCommerceShortDescription with content length:', content?.length);
                        
                        // Call original function first
                        originalUpdateWooCommerceShortDescription(content);
                        
                        // Add Elementor support
                        this.updateElementorContent(content, 'short_description');
                    };
                    console.log('✅ Extended updateWooCommerceShortDescription with Elementor support');
                }
                
                console.log('✅ Extended existing AYSA functions with Elementor support');
                return true;
            }
            
            return false;
        };
        
        // Try immediately
        if (waitForFunctions.call(this)) {
            return;
        }
        
        // If functions not available, wait and retry
        let attempts = 0;
        const maxAttempts = 50; // 5 seconds max
        
        const retry = () => {
            attempts++;
            console.log(`AYSA Elementor: Attempt ${attempts}/${maxAttempts} to find AYSA functions...`);
            
            if (waitForFunctions.call(this)) {
                console.log('✅ AYSA Elementor: Functions found and extended after', attempts, 'attempts');
                return;
            }
            
            if (attempts < maxAttempts) {
                setTimeout(retry, 100);
            } else {
                console.warn('⚠️ AYSA Elementor: Could not find AYSA functions after', maxAttempts, 'attempts');
                // Create fallback functions
                this.createFallbackFunctions();
            }
        };
        
        setTimeout(retry, 100);
    },
    
    /**
     * Create fallback functions if originals are not found
     */
    createFallbackFunctions: function() {
        console.log('AYSA Elementor: Creating fallback functions...');
        
        if (typeof window.updateWooCommerceDescription !== 'function') {
            window.updateWooCommerceDescription = (content) => {
                console.log('AYSA Elementor: Fallback updateWooCommerceDescription called');
                this.updateElementorContent(content, 'description');
            };
        }
        
        if (typeof window.updateWooCommerceShortDescription !== 'function') {
            window.updateWooCommerceShortDescription = (content) => {
                console.log('AYSA Elementor: Fallback updateWooCommerceShortDescription called');
                this.updateElementorContent(content, 'short_description');
            };
        }
        
        console.log('✅ AYSA Elementor: Fallback functions created');
    },
    
    /**
     * Update Elementor content
     */
    updateElementorContent: function(content, contentType) {
        console.log('🔥 AYSA Elementor: updateElementorContent called', {
            isElementorActive: this.isElementorActive,
            contentType: contentType,
            contentLength: content ? content.length : 0,
            contentPreview: content ? content.substring(0, 100) + '...' : 'empty'
        });
        
        if (!this.isElementorActive) {
            console.log('❌ AYSA Elementor: Elementor not active, skipping update');
            return;
        }
        
        const postId = this.getCurrentPostId();
        if (!postId) {
            console.log('❌ AYSA Elementor: No post ID found for Elementor update');
            return;
        }
        
        console.log('🚀 AYSA Elementor: Updating Elementor content:', {
            postId: postId,
            contentType: contentType,
            contentLength: content ? content.length : 0,
            ajaxUrl: aysaElementorAjax?.ajax_url,
            hasNonce: !!aysaElementorAjax?.nonce
        });
        
        // Check if we have the required AJAX data
        if (typeof aysaElementorAjax === 'undefined') {
            console.error('❌ AYSA Elementor: aysaElementorAjax is not defined');
            return;
        }
        
        // Update Elementor via AJAX
        jQuery.ajax({
            url: aysaElementorAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_update_elementor_content',
                nonce: aysaElementorAjax.nonce,
                post_id: postId,
                content_type: contentType,
                new_content: content
            },
            beforeSend: function() {
                console.log('🔄 AYSA Elementor: Sending AJAX request to update content...');
            },
            success: function(response) {
                if (response.success) {
                    console.log('✅ AYSA Elementor: Content updated successfully:', response.data);
                    
                    // Show success toast if available
                    if (typeof showToast === 'function') {
                        showToast('Elementor content updated successfully!', 'success');
                    }
                } else {
                    console.error('❌ AYSA Elementor: Failed to update content:', response.data);
                    
                    // Show error toast if available
                    if (typeof showToast === 'function') {
                        showToast('Failed to update Elementor content: ' + (response.data?.message || 'Unknown error'), 'error');
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('❌ AYSA Elementor: AJAX error updating content:', {
                    status: status,
                    error: error,
                    responseText: xhr.responseText
                });
                
                // Show error toast if available
                if (typeof showToast === 'function') {
                    showToast('Network error updating Elementor content', 'error');
                }
            }
        });
    },
    
    /**
     * Get Elementor content
     */
    getElementorContent: function(contentType, callback) {
        if (!this.isElementorActive) {
            if (callback) callback(false);
            return;
        }
        
        const postId = this.getCurrentPostId();
        if (!postId) {
            console.log('No post ID found for Elementor get content');
            if (callback) callback(false);
            return;
        }
        
        jQuery.ajax({
            url: aysaElementorAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_get_elementor_content',
                nonce: aysaElementorAjax.nonce,
                post_id: postId,
                content_type: contentType
            },
            success: function(response) {
                if (response.success) {
                    console.log('Retrieved Elementor content:', response.data);
                    if (callback) callback(response.data);
                } else {
                    console.error('Failed to get Elementor content:', response.data);
                    if (callback) callback(false);
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error getting Elementor content:', error);
                if (callback) callback(false);
            }
        });
    },
    
    /**
     * Get current post ID from various sources
     */
    getCurrentPostId: function() {
        let postId = null;
        
        // Try to get from URL parameters
        const urlParams = new URLSearchParams(window.location.search);
        postId = urlParams.get('post') || urlParams.get('tag_ID');
        
        // Try to get from global variables
        if (!postId && typeof pagenow !== 'undefined' && pagenow === 'post') {
            if (typeof typenow !== 'undefined' && typenow === 'product') {
                postId = urlParams.get('post');
            }
        }
        
        // Try to get from form fields
        if (!postId) {
            const postIdField = document.getElementById('post_ID') || 
                               document.querySelector('input[name="post_ID"]') ||
                               document.querySelector('input[name="tag_ID"]');
            if (postIdField) {
                postId = postIdField.value;
            }
        }
        
        // Try to get from AYSA functions if available
        if (!postId && typeof getEntityId === 'function') {
            postId = getEntityId();
        }
        
        return postId ? parseInt(postId) : null;
    },
    
    /**
     * Check if Elementor is active on current post
     */
    isElementorActiveOnCurrentPost: function(callback) {
        const postId = this.getCurrentPostId();
        if (!postId) {
            if (callback) callback(false);
            return;
        }
        
        this.getElementorContent('description', function(data) {
            const isActive = data && data.is_elementor_active;
            if (callback) callback(isActive);
        });
    },
    
    /**
     * Helper function to update both WordPress and Elementor content
     */
    updateAllContent: function(content, contentType) {
        console.log('Updating all content (WordPress + Elementor):', {
            contentType: contentType,
            contentLength: content ? content.length : 0
        });
        
        // Update based on content type
        if (contentType === 'description') {
            if (typeof updateWooCommerceDescription === 'function') {
                updateWooCommerceDescription(content);
            }
            if (typeof updateClassicEditorContent === 'function') {
                updateClassicEditorContent(content);
            }
            if (typeof updateGutenbergContent === 'function') {
                updateGutenbergContent(content);
            }
        } else if (contentType === 'short_description') {
            if (typeof updateWooCommerceShortDescription === 'function') {
                updateWooCommerceShortDescription(content);
            }
            if (typeof updateClassicEditorExcerpt === 'function') {
                updateClassicEditorExcerpt(content);
            }
            if (typeof updateGutenbergExcerpt === 'function') {
                updateGutenbergExcerpt(content);
            }
        }
        
        // The Elementor update will be handled by the extended functions
    },
    
    /**
     * Get all content from all sources (WordPress + Elementor)
     */
    getAllContent: function(contentType, callback) {
        const content = {
            wordpress: null,
            elementor: null
        };
        
        // Get WordPress content
        if (contentType === 'description') {
            const contentField = document.getElementById('content');
            if (contentField) {
                content.wordpress = contentField.value;
            } else if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                content.wordpress = tinyMCE.get('content').getContent();
            }
        } else if (contentType === 'short_description') {
            const excerptField = document.getElementById('excerpt') || 
                                document.getElementById('post_excerpt') || 
                                document.querySelector('#postexcerpt textarea');
            if (excerptField) {
                content.wordpress = excerptField.value;
            } else if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
                content.wordpress = tinyMCE.get('excerpt').getContent();
            }
        }
        
        // Get Elementor content
        this.getElementorContent(contentType, function(elementorData) {
            if (elementorData) {
                content.elementor = elementorData.elementor;
            }
            
            if (callback) callback(content);
        });
    },
    
    /**
     * Test the integration to make sure everything works
     */
    testIntegration: function() {
        console.log('🧪 AYSA Elementor: Testing integration...');
        
        const tests = {
            handlerLoaded: !!window.aysaElementorHandler,
            isElementorActive: this.isElementorActive,
            hasAjaxData: typeof aysaElementorAjax !== 'undefined',
            postId: this.getCurrentPostId(),
            updateFunctionExists: typeof window.updateWooCommerceDescription === 'function',
            shortUpdateFunctionExists: typeof window.updateWooCommerceShortDescription === 'function'
        };
        
        console.log('🧪 AYSA Elementor: Integration test results:', tests);
        
        // Check for common issues
        if (!tests.handlerLoaded) {
            console.error('❌ AYSA Elementor: Handler not loaded');
        }
        
        if (!tests.hasAjaxData) {
            console.warn('⚠️ AYSA Elementor: AJAX data not available - some features may not work');
        }
        
        if (!tests.postId) {
            console.warn('⚠️ AYSA Elementor: Could not detect post ID');
        }
        
        if (!tests.updateFunctionExists) {
            console.warn('⚠️ AYSA Elementor: updateWooCommerceDescription function not found');
        }
        
        if (!tests.shortUpdateFunctionExists) {
            console.warn('⚠️ AYSA Elementor: updateWooCommerceShortDescription function not found');
        }
        
        // If on a product page and Elementor is active, try to get content
        if (tests.postId && this.isElementorActive) {
            this.getElementorContent('description', (data) => {
                if (data) {
                    console.log('✅ AYSA Elementor: Successfully retrieved Elementor content preview:', 
                        data.substring ? data.substring(0, 100) + '...' : data);
                } else {
                    console.log('ℹ️ AYSA Elementor: No Elementor content found (this may be normal)');
                }
            });
        }
        
        const overallSuccess = tests.handlerLoaded && 
                              (tests.updateFunctionExists || tests.shortUpdateFunctionExists);
        
        if (overallSuccess) {
            console.log('✅ AYSA Elementor: Integration test PASSED');
        } else {
            console.error('❌ AYSA Elementor: Integration test FAILED');
        }
        
        return tests;
    },
    
    /**
     * Manual test function for debugging
     */
    debugTest: function(content = 'Test content from AYSA Elementor') {
        console.log('🔧 AYSA Elementor: Running manual debug test...');
        
        if (!this.isElementorActive) {
            console.log('❌ Debug test: Elementor not active');
            return false;
        }
        
        const postId = this.getCurrentPostId();
        if (!postId) {
            console.log('❌ Debug test: No post ID');
            return false;
        }
        
        console.log('🚀 Debug test: Attempting to update Elementor content...');
        this.updateElementorContent(content, 'description');
        
        return true;
    }
};

// Initialize when DOM is ready
jQuery(document).ready(function() {
    console.log('🔄 AYSA Elementor: DOM ready, initializing handler...');
    
    // Initialize with a delay to ensure all AYSA scripts are loaded
    let initAttempts = 0;
    const maxInitAttempts = 30; // 3 seconds max
    
    const tryInit = () => {
        initAttempts++;
        console.log(`🔄 AYSA Elementor: Init attempt ${initAttempts}/${maxInitAttempts}`);
        
        // Check if AYSA scripts are loaded (look for key functions or objects)
        const aysaScriptsLoaded = typeof aysaParams !== 'undefined' || 
                                typeof window.loadDataFromAPI === 'function' ||
                                typeof window.getEntityId === 'function';
        
        if (aysaScriptsLoaded || initAttempts >= maxInitAttempts) {
            if (aysaScriptsLoaded) {
                console.log('✅ AYSA Elementor: AYSA scripts detected, initializing...');
            } else {
                console.log('⚠️ AYSA Elementor: AYSA scripts not detected, initializing anyway...');
            }
            
            window.aysaElementorHandler.init();
            
            // Test the integration
            setTimeout(() => window.aysaElementorHandler.testIntegration(), 500);
        } else {
            setTimeout(tryInit, 100);
        }
    };
    
    tryInit();
});

// Also provide a direct function that can be called from existing AYSA code
window.updateElementorContent = function(content, contentType) {
    console.log('🔄 AYSA Elementor: Direct updateElementorContent called', {
        hasHandler: !!window.aysaElementorHandler,
        contentType: contentType,
        contentLength: content?.length
    });
    
    if (window.aysaElementorHandler) {
        window.aysaElementorHandler.updateElementorContent(content, contentType);
    } else {
        console.error('❌ AYSA Elementor: Handler not available');
    }
};

// Add to window for external access
window.aysaElementorHandler = window.aysaElementorHandler; 