/**
 * AYSA SEO Generator - Example Implementation
 * This file demonstrates how to use the new AysaSeoGenerator and AysaSeoIntegration classes
 * alongside the existing metabox functionality without replacing it.
 */

// Example 1: Initialize SEO generation for product metabox
function initializeProductSeoGeneration() {
    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializeProductSeoGeneration);
        return;
    }
    
    // Check if we're on a product edit page
    if (!document.querySelector('#product-type') && !document.querySelector('.post-type-product')) {
        return;
    }
    
    console.log('🚀 Initializing Product SEO Generation');
    
    // Create integration instance
    const seoIntegration = new AysaSeoIntegration();
    
    // Initialize metabox integration
    const integrationId = seoIntegration.initializeMetaboxIntegration({
        buttonSelector: '.aysa-generate-suggestions', // Existing button
        entityType: 'Product',
        callbacks: {
            onProgress: (message) => {
                console.log(`Product SEO Progress: ${message}`);
            },
            onSuccess: (results) => {
                console.log('Product SEO generation completed:', results);
                
                // Custom post-processing for products
                if (results.shortDescription) {
                    // Add custom styling or validation
                    const excerptField = document.getElementById('excerpt');
                    if (excerptField) {
                        excerptField.style.borderColor = '#00a32a'; // Green border for updated field
                        setTimeout(() => {
                            excerptField.style.borderColor = '';
                        }, 3000);
                    }
                }
            },
            onError: (error) => {
                console.error('Product SEO generation failed:', error);
            }
        }
    });
    
    // Store integration ID for cleanup if needed
    window.productSeoIntegrationId = integrationId;
}

// Example 2: Initialize SEO generation for category metabox
function initializeCategorySeoGeneration() {
    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializeCategorySeoGeneration);
        return;
    }
    
    // Check if we're on a category edit page
    if (!document.querySelector('#edittag') && !document.querySelector('.taxonomy-product_cat')) {
        return;
    }
    
    console.log('🚀 Initializing Category SEO Generation');
    
    // Create integration instance
    const seoIntegration = new AysaSeoIntegration();
    
    // Initialize metabox integration
    const integrationId = seoIntegration.initializeMetaboxIntegration({
        buttonSelector: '.aysa-generate-suggestions',
        entityType: 'Category',
        callbacks: {
            onSuccess: (results) => {
                console.log('Category SEO generation completed:', results);
                
                // Add revert buttons specifically for category description
                seoIntegration.addRevertButtons('description', 'Category');
            }
        }
    });
    
    window.categorySeoIntegrationId = integrationId;
}

// Example 3: Initialize SEO generation for page/post metabox
function initializePageSeoGeneration() {
    // Wait for DOM to be ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializePageSeoGeneration);
        return;
    }
    
    // Check if we're on a page or post edit screen
    const isPage = document.querySelector('.post-type-page');
    const isPost = document.querySelector('.post-type-post');
    
    if (!isPage && !isPost) {
        return;
    }
    
    const entityType = isPage ? 'Page' : 'Post';
    console.log(`🚀 Initializing ${entityType} SEO Generation`);
    
    // Create integration instance
    const seoIntegration = new AysaSeoIntegration();
    
    // Initialize metabox integration
    const integrationId = seoIntegration.initializeMetaboxIntegration({
        buttonSelector: '.aysa-generate-suggestions',
        entityType: entityType,
        callbacks: {
            onSuccess: (results) => {
                console.log(`${entityType} SEO generation completed:`, results);
                
                // Add revert buttons for content
                seoIntegration.addRevertButtons('content', entityType);
            }
        }
    });
    
    window.pageSeoIntegrationId = integrationId;
}

// Example 4: Custom SEO generation for optimization schedule
function createOptimizationScheduleGenerator() {
    const seoIntegration = new AysaSeoIntegration();
    
    // Create a custom generator function
    const customGenerator = seoIntegration.createCustomGenerator({
        defaultTimeout: 15000, // Shorter timeout for schedule
        onProgress: (message) => {
            console.log(`Schedule SEO Progress: ${message}`);
        }
    });
    
    // Return a function that can be used by the optimization schedule
    return async function generateForSchedule(keyword, entityType, associationId) {
        try {
            console.log(`🚀 Generating SEO for schedule: ${keyword} (${entityType})`);
            
            const results = await customGenerator({
                entityId: associationId,
                entityType: entityType,
                keyword: keyword,
                entityName: keyword, // Use keyword as entity name for schedule
                language: 'en',
                websiteName: 'WordPress'
            });
            
            // Return formatted results for the schedule table
            return {
                keyword: keyword,
                entityType: entityType,
                metaTitle: results.metaTitle || `${keyword} | WordPress`,
                metaDescription: results.metaDescription || `Discover ${keyword} and related content.`,
                status: 'Generated',
                timestamp: new Date().toLocaleString()
            };
            
        } catch (error) {
            console.error('🚀 Schedule SEO generation failed:', error);
            
            // Return fallback data
            return {
                keyword: keyword,
                entityType: entityType,
                metaTitle: `${keyword} | WordPress`,
                metaDescription: `Discover ${keyword} and related content.`,
                status: 'Failed',
                timestamp: new Date().toLocaleString()
            };
        }
    };
}

// Example 5: Standalone SEO generator usage
function demonstrateStandaloneSeoGenerator() {
    // Create a standalone generator instance
    const generator = new AysaSeoGenerator({
        defaultTimeout: 20000,
        onProgress: (message) => console.log(`Standalone Progress: ${message}`),
        onSuccess: (results) => console.log('Standalone Success:', results),
        onError: (error) => console.error('Standalone Error:', error)
    });
    
    // Example usage
    async function generateSeoForKeyword(keyword) {
        try {
            const results = await generator.generateSuggestions({
                entityType: 'Product',
                keyword: keyword,
                entityName: `Sample ${keyword} Product`,
                language: 'en',
                websiteName: 'My Store',
                existingData: {
                    metaTitle: '',
                    metaDescription: '',
                    metaKeywords: ''
                }
            });
            
            return results;
        } catch (error) {
            console.error('Failed to generate SEO:', error);
            return null;
        }
    }
    
    // Return the function for external use
    return generateSeoForKeyword;
}

// Example 6: Integration with existing aysa-metabox.js functionality
function enhanceExistingMetabox() {
    // Wait for the original metabox to be loaded
    if (typeof window.handleGenerateSuggestions === 'undefined') {
        setTimeout(enhanceExistingMetabox, 1000);
        return;
    }
    
    console.log('🚀 Enhancing existing metabox with new SEO generator');
    
    // Store reference to original function
    const originalHandleGenerateSuggestions = window.handleGenerateSuggestions;
    
    // Create new SEO integration
    const seoIntegration = new AysaSeoIntegration();
    
    // Create enhanced version that can use either implementation
    window.handleGenerateSuggestionsEnhanced = async function(useNewGenerator = false) {
        if (useNewGenerator) {
            // Use new generator
            const entityType = getEntityTypeGood(); // Assume this function exists
            const config = seoIntegration.extractMetaboxData(entityType);
            
            const generator = new AysaSeoGenerator({
                button: document.querySelector('.aysa-generate-suggestions'),
                spinner: document.querySelector('.spinner')
            });
            
            try {
                const results = await generator.generateSuggestions(config);
                seoIntegration.applyToMetabox(results, entityType);
                return results;
            } catch (error) {
                console.error('Enhanced generator failed, falling back to original:', error);
                return originalHandleGenerateSuggestions();
            }
        } else {
            // Use original implementation
            return originalHandleGenerateSuggestions();
        }
    };
    
    // Add toggle button to switch between implementations (for testing)
    const toggleButton = document.createElement('button');
    toggleButton.type = 'button';
    toggleButton.className = 'button button-secondary';
    toggleButton.textContent = 'Use New Generator';
    toggleButton.style.marginLeft = '10px';
    
    let useNewGenerator = false;
    toggleButton.onclick = () => {
        useNewGenerator = !useNewGenerator;
        toggleButton.textContent = useNewGenerator ? 'Use Original Generator' : 'Use New Generator';
        toggleButton.style.backgroundColor = useNewGenerator ? '#00a32a' : '';
    };
    
    // Add toggle button next to existing generate button
    const generateButton = document.querySelector('.aysa-generate-suggestions');
    if (generateButton && generateButton.parentNode) {
        generateButton.parentNode.insertBefore(toggleButton, generateButton.nextSibling);
        
        // Override the existing button's click handler
        const originalClickHandler = generateButton.onclick;
        generateButton.onclick = (event) => {
            event.preventDefault();
            window.handleGenerateSuggestionsEnhanced(useNewGenerator);
        };
    }
}

// Example 7: Utility functions for integration
function getEntityTypeGood() {
    // Default value
    let entityType = 'Page';
    
    // Try to determine by URL
    const url = window.location.href;
    console.log('🚀 DEBUG getEntityType - URL being checked:', url);
    
    // Check URL parameters first
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('tag_ID') || urlParams.get('taxonomy')) {
        entityType = 'Category';
        console.log('🚀 DEBUG: Detected Category from URL params');
        return entityType;
    }
    
    // Check for product in URL params
    if (urlParams.get('post_type') === 'product') {
        entityType = 'Product';
        console.log('🚀 DEBUG: Detected Product from URL params');
        return entityType;
    }
    
    // Try to get from global aysaParams if available
    if (typeof aysaParams !== 'undefined') {
        if (aysaParams.entityType === 'term') {
            entityType = 'Category';
            console.log('🚀 DEBUG: Detected Category from aysaParams');
            return entityType;
        } else if (aysaParams.entityType === 'product') {
            entityType = 'Product';
            console.log('🚀 DEBUG: Detected Product from aysaParams');
            return entityType;
        }
    }

    // Check for WooCommerce product
    const isWooCommerceProduct = url.includes('post-new.php?post_type=product') || 
                               (url.includes('post.php?post=') && url.includes('&action=edit') && 
                                document.getElementById('woocommerce-product-data'));

    // Advanced detection - check for more product indicators
    const hasProductMetabox = document.getElementById('woocommerce-product-data') !== null;
    const hasProductTitle = document.getElementById('title') && 
                          document.getElementById('title').closest('.postbox') && 
                          document.getElementById('title').closest('.postbox').querySelector('h2') && 
                          document.getElementById('title').closest('.postbox').querySelector('h2').textContent.includes('Product');
    const hasProductType = document.getElementById('product-type') !== null;
    
    console.log('DEBUG getEntityType - Product indicators:', {
        'url.includes(post-new.php?post_type=product)': url.includes('post-new.php?post_type=product'),
        'url.includes(post.php?post=)': url.includes('post.php?post='),
        'url.includes(&action=edit)': url.includes('&action=edit'),
        'hasWooCommerceProductData': hasProductMetabox,
        'hasProductTitle': hasProductTitle,
        'hasProductType': hasProductType,
        'isWooCommerceProduct': isWooCommerceProduct
    });

    // Check if WordPress admin params specify entity type
    let aysaEntityType = '';
    if (typeof aysaParams !== 'undefined' && aysaParams.entityType) {
        aysaEntityType = aysaParams.entityType;
        console.log('DEBUG getEntityType - Found aysaParams.entityType:', aysaEntityType);
    }
    
    // Determine entity type with multiple methods
    if (isWooCommerceProduct || hasProductMetabox || hasProductType || aysaEntityType === 'product') {
        entityType = 'Product';
    } else if (url.includes('term.php?taxonomy=product_cat') || 
               url.includes('edit-tags.php?taxonomy=product_cat') || 
               aysaEntityType === 'category' || 
               aysaEntityType === 'term') {
        entityType = 'Category';
    }
    
    console.log('🚀 DEBUG getEntityType - Final detected entity type:', entityType);
    return entityType;
}

function initializeAllSeoGenerators() {
    console.log('🚀 Initializing all SEO generators');
    
    // Initialize based on current page context
    initializeProductSeoGeneration();
    initializeCategorySeoGeneration();
    initializePageSeoGeneration();
    
    // Enhance existing metabox if available
    enhanceExistingMetabox();
    
    // Make optimization schedule generator available globally
    window.createOptimizationScheduleGenerator = createOptimizationScheduleGenerator;
    window.demonstrateStandaloneSeoGenerator = demonstrateStandaloneSeoGenerator;
}

// Auto-initialize when script loads
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeAllSeoGenerators);
} else {
    initializeAllSeoGenerators();
}

// Export functions for external use
if (typeof window !== 'undefined') {
    window.AysaSeoGeneratorExamples = {
        initializeProductSeoGeneration,
        initializeCategorySeoGeneration,
        initializePageSeoGeneration,
        createOptimizationScheduleGenerator,
        demonstrateStandaloneSeoGenerator,
        enhanceExistingMetabox,
        getEntityType,
        initializeAllSeoGenerators
    };
}