/**
 * AYSA SEO Integration Utility Class
 * Helper class for integrating AysaSeoGenerator with existing WordPress forms and UI
 */

class AysaSeoIntegration {
    constructor(generator = null) {
        this.generator = generator || new AysaSeoGenerator();
        this.activeIntegrations = new Map();
    }
    
    /**
     * Initialize SEO generation for a metabox context
     * @param {Object} config - Configuration object
     * @param {string} config.buttonSelector - CSS selector for the generate button
     * @param {string} config.entityType - Entity type (Product, Category, Page, etc.)
     * @param {Object} config.fieldMapping - Custom field mapping
     * @param {Object} config.callbacks - Custom callbacks
     * @returns {string} Integration ID for later reference
     */
    initializeMetaboxIntegration(config) {
        const {
            buttonSelector = '.aysa-generate-suggestions',
            entityType = 'Page',
            fieldMapping = {},
            callbacks = {}
        } = config;
        
        const integrationId = `metabox_${Date.now()}`;
        
        // Find the button element
        const button = document.querySelector(buttonSelector);
        if (!button) {
            console.warn(`🚀 AysaSeoIntegration: Button not found: ${buttonSelector}`);
            return null;
        }
        
        // Set up the generator with UI elements
        const generator = new AysaSeoGenerator({
            button: button,
            spinner: document.querySelector('.spinner'),
            onProgress: (message) => {
                console.log(`🚀 SEO Progress: ${message}`);
                if (callbacks.onProgress) callbacks.onProgress(message);
            },
            onSuccess: (results) => {
                this._handleMetaboxSuccess(results, fieldMapping, entityType);
                if (callbacks.onSuccess) callbacks.onSuccess(results);
            },
            onError: (error) => {
                this._handleMetaboxError(error);
                if (callbacks.onError) callbacks.onError(error);
            },
            onComplete: () => {
                if (callbacks.onComplete) callbacks.onComplete();
            }
        });
        
        // Set up click handler
        const clickHandler = (event) => {
            event.preventDefault();
            this._handleMetaboxGeneration(generator, entityType);
        };
        
        button.addEventListener('click', clickHandler);
        
        // Store integration for cleanup
        this.activeIntegrations.set(integrationId, {
            button,
            clickHandler,
            generator,
            type: 'metabox'
        });
        
        console.log(`🚀 AysaSeoIntegration: Metabox integration initialized (${integrationId})`);
        return integrationId;
    }
    
    /**
     * Initialize SEO generation for a custom context (like the optimization schedule)
     * @param {Object} config - Configuration object
     * @returns {Function} Function to trigger SEO generation
     */
    createCustomGenerator(config = {}) {
        const generator = new AysaSeoGenerator(config);
        
        return async (generationConfig) => {
            try {
                const results = await generator.generateSuggestions(generationConfig);
                return results;
            } catch (error) {
                console.error('🚀 AysaSeoIntegration: Custom generation failed:', error);
                throw error;
            }
        };
    }
    
    /**
     * Extract current form data from WordPress metabox
     * @param {string} entityType - Entity type
     * @returns {Object} Current form data
     */
    extractMetaboxData(entityType = 'Page') {
        const data = {
            entityType,
            keyword: this._getFieldValue('aysa-entity-keyword'),
            entityName: this._getEntityName(entityType),
            language: this._getLanguage(),
            websiteName: this._getWebsiteName(),
            existingData: {
                metaTitle: this._getFieldValue('aysa-entity-meta-title'),
                metaDescription: this._getFieldValue('aysa-entity-meta-description'),
                metaKeywords: this._getFieldValue('aysa-entity-meta-keywords'),
                secondaryKeywords: this._getFieldValue('aysa-entity-second-keyword')
            }
        };
        
        // Add entity-specific data
        switch (entityType) {
            case 'Product':
                data.existingData.productTitle = this._getFieldValue('title');
                data.existingData.productDescription = this._getTinyMCEContent('content');
                data.existingData.shortDescription = this._getTinyMCEContent('excerpt');
                break;
                
            case 'Category':
                data.existingData.categoryTitle = this._getFieldValue('name');
                data.existingData.categoryDescription = this._getTinyMCEContent('description');
                break;
                
            default:
                data.existingData.pageTitle = this._getFieldValue('title');
                data.existingData.pageContent = this._getTinyMCEContent('content');
                break;
        }
        
        return data;
    }
    
    /**
     * Apply SEO suggestions to WordPress metabox fields
     * @param {Object} suggestions - Generated suggestions
     * @param {string} entityType - Entity type
     * @param {Object} options - Application options
     */
    applyToMetabox(suggestions, entityType = 'Page', options = {}) {
        const fieldMapping = this._getMetaboxFieldMapping(entityType);
        
        if (this.generator) {
            this.generator.applySuggestionsToFields(suggestions, fieldMapping, {
                preserveExisting: true,
                mergeSecondaryKeywords: true,
                showToasts: true,
                ...options
            });
        }
        
        // Trigger WordPress events for field updates
        this._triggerWordPressEvents(suggestions, entityType);
    }
    
    /**
     * Save pre-generation values for versioning
     * @param {string} entityType - Entity type
     * @returns {Object} Pre-generation data
     */
    savePreGenerationValues(entityType = 'Page') {
        const data = this.extractMetaboxData(entityType);
        
        // Store in session storage for recovery
        try {
            sessionStorage.setItem('aysa_pre_generation_data', JSON.stringify({
                timestamp: new Date().toISOString(),
                entityType,
                data
            }));
        } catch (error) {
            console.warn('🚀 AysaSeoIntegration: Could not save to session storage:', error);
        }
        
        return data;
    }
    
    /**
     * Restore pre-generation values
     * @param {string} entityType - Entity type
     * @returns {boolean} Success status
     */
    restorePreGenerationValues(entityType = 'Page') {
        try {
            const stored = sessionStorage.getItem('aysa_pre_generation_data');
            if (!stored) return false;
            
            const { data } = JSON.parse(stored);
            if (data.entityType !== entityType) return false;
            
            // Apply the stored data back to fields
            this.applyToMetabox(data.existingData, entityType, {
                preserveExisting: false // Force overwrite
            });
            
            // Clear stored data
            sessionStorage.removeItem('aysa_pre_generation_data');
            
            if (typeof showToast === 'function') {
                showToast('Pre-generation values restored successfully.', 'success');
            }
            
            return true;
        } catch (error) {
            console.error('🚀 AysaSeoIntegration: Error restoring values:', error);
            return false;
        }
    }
    
    /**
     * Add revert buttons to description fields
     * @param {string} fieldId - Field ID to add buttons to
     * @param {string} entityType - Entity type
     */
    addRevertButtons(fieldId, entityType = 'Page') {
        const field = document.getElementById(fieldId);
        if (!field) return;
        
        // Check if buttons already exist
        const existingContainer = field.parentNode.querySelector('.aysa-revert-buttons');
        if (existingContainer) return;
        
        // Create button container
        const buttonContainer = document.createElement('div');
        buttonContainer.className = 'aysa-revert-buttons';
        buttonContainer.style.cssText = 'margin-top: 5px; display: flex; gap: 10px;';
        
        // Create revert to pre-generation button
        const revertPreButton = document.createElement('button');
        revertPreButton.type = 'button';
        revertPreButton.className = 'button button-small';
        revertPreButton.textContent = 'Revert to Pre-Generation';
        revertPreButton.onclick = () => {
            this.restorePreGenerationValues(entityType);
        };
        
        // Create revert to original button
        const revertOriginalButton = document.createElement('button');
        revertOriginalButton.type = 'button';
        revertOriginalButton.className = 'button button-small';
        revertOriginalButton.textContent = 'Revert to Original';
        revertOriginalButton.onclick = () => {
            this._revertToOriginal(fieldId);
        };
        
        buttonContainer.appendChild(revertPreButton);
        buttonContainer.appendChild(revertOriginalButton);
        
        // Insert after the field
        field.parentNode.insertBefore(buttonContainer, field.nextSibling);
    }
    
    /**
     * Clean up an integration
     * @param {string} integrationId - Integration ID to clean up
     */
    cleanup(integrationId) {
        const integration = this.activeIntegrations.get(integrationId);
        if (!integration) return;
        
        // Remove event listeners
        if (integration.button && integration.clickHandler) {
            integration.button.removeEventListener('click', integration.clickHandler);
        }
        
        // Clean up generator
        if (integration.generator && typeof integration.generator.cleanup === 'function') {
            integration.generator.cleanup();
        }
        
        this.activeIntegrations.delete(integrationId);
        console.log(`🚀 AysaSeoIntegration: Integration ${integrationId} cleaned up`);
    }
    
    /**
     * Clean up all integrations
     */
    cleanupAll() {
        for (const integrationId of this.activeIntegrations.keys()) {
            this.cleanup(integrationId);
        }
    }
    
    // Private methods
    
    async _handleMetaboxGeneration(generator, entityType) {
        try {
            // Save pre-generation values
            this.savePreGenerationValues(entityType);
            
            // Extract current form data
            const config = this.extractMetaboxData(entityType);
            
            // Validate required fields
            if (!config.keyword || config.keyword.trim() === '') {
                if (typeof showToast === 'function') {
                    showToast('Please enter a keyword before generating SEO suggestions.', 'error');
                }
                return;
            }
            
            // Generate suggestions
            const results = await generator.generateSuggestions(config);
            
            // Create history entry after successful generation
            await this._createHistoryEntry(results, config, entityType);
            
        } catch (error) {
            console.error('🚀 AysaSeoIntegration: Metabox generation failed:', error);
            this._handleMetaboxError(error);
        }
    }
    
    _handleMetaboxSuccess(results, customFieldMapping, entityType) {
        // Apply suggestions to fields
        this.applyToMetabox(results, entityType);
        
        // Add revert buttons to description fields
        if (entityType === 'Product') {
            this.addRevertButtons('content', entityType);
            this.addRevertButtons('excerpt', entityType);
        } else if (entityType === 'Category') {
            this.addRevertButtons('description', entityType);
        } else {
            this.addRevertButtons('content', entityType);
        }
        
        // Trigger versioning if available
        this._triggerVersioning(results, entityType);
    }
    
    _handleMetaboxError(error) {
        if (typeof showToast === 'function') {
            showToast(`SEO generation failed: ${error.message}`, 'error');
        }
    }
    
    /**
     * Create SEO history entry for metabox generation
     * @param {Object} results - Generated SEO results
     * @param {Object} config - Generation configuration
     * @param {string} entityType - Entity type
     */
    async _createHistoryEntry(results, config, entityType) {
        try {
            // Check if history AJAX is available
            if (typeof aysaSeoHistoryAjax === 'undefined') {
                console.warn('🚀 AysaSeoIntegration: SEO history AJAX not available');
                return;
            }
            
            // Get entity ID from the current page
            let entityId = null;
            
            // Try to get entity ID from various sources
            if (entityType === 'Product' || entityType === 'Page' || entityType === 'Post') {
                // For post/page/product edit screens
                const postIdInput = document.querySelector('#post_ID');
                if (postIdInput) {
                    entityId = postIdInput.value;
                }
            } else if (entityType === 'Category') {
                // For category edit screens
                const tagIdInput = document.querySelector('#tag_ID');
                if (tagIdInput) {
                    entityId = tagIdInput.value;
                }
                // For new category creation
                if (!entityId) {
                    const urlParams = new URLSearchParams(window.location.search);
                    entityId = urlParams.get('tag_ID');
                }
            }
            
            if (!entityId) {
                console.warn('🚀 AysaSeoIntegration: Could not determine entity ID for history entry');
                return;
            }
            
            // Prepare history data
            const historyData = {
                action: 'aysa_seo_history_add_entry',
                nonce: aysaSeoHistoryAjax.nonce,
                entity_id: entityId,
                entity_type: entityType.toLowerCase(),
                generator_type: 'metabox',
                keyword: config.keyword || '',
                generated_data: JSON.stringify({
                    metaTitle: results.metaTitle || '',
                    metaDescription: results.metaDescription || '',
                    metaKeywords: results.metaKeywords || '',
                    secondaryKeywords: results.secondaryKeywords || [],
                    suggestions: results.suggestions || [],
                    content: results.content || ''
                }),
                context_data: JSON.stringify({
                    source: 'metabox',
                    entityType: entityType,
                    entityName: config.entityName || config.keyword,
                    language: config.language || 'en',
                    timestamp: new Date().toISOString(),
                    url: window.location.href
                })
            };
            
            // Send AJAX request to create history entry
            const response = await fetch(aysaSeoHistoryAjax.ajax_url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(historyData)
            });
            
            const result = await response.json();
            
            if (result.success) {
                console.log('🚀 AysaSeoIntegration: SEO history entry created:', result.data);
            } else {
                console.warn('🚀 AysaSeoIntegration: Failed to create history entry:', result.data);
            }
            
        } catch (error) {
            console.error('🚀 AysaSeoIntegration: Error creating history entry:', error);
            // Don't throw error to avoid breaking the main generation flow
        }
    }
    
    _getFieldValue(fieldId) {
        const element = document.getElementById(fieldId);
        return element ? element.value : '';
    }
    
    _getTinyMCEContent(fieldId) {
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get(fieldId)) {
            return tinyMCE.get(fieldId).getContent();
        }
        return this._getFieldValue(fieldId);
    }
    
    _getEntityName(entityType) {
        switch (entityType) {
            case 'Product':
                return this._getFieldValue('title');
            case 'Category':
                return this._getFieldValue('name');
            default:
                return this._getFieldValue('title');
        }
    }
    
    _getLanguage() {
        // Try to get language from WordPress locale
        const locale = document.documentElement.lang || 'en';
        return locale.split('-')[0]; // Convert 'en-US' to 'en'
    }
    
    _getWebsiteName() {
        // Try to get site name from WordPress
        const titleElement = document.querySelector('title');
        if (titleElement) {
            const title = titleElement.textContent;
            const parts = title.split(' — ');
            if (parts.length > 1) {
                return parts[parts.length - 1]; // Last part is usually site name
            }
        }
        return 'WordPress';
    }
    
    _getMetaboxFieldMapping(entityType) {
        const baseMapping = {
            metaTitle: 'aysa-entity-meta-title',
            metaDescription: 'aysa-entity-meta-description',
            metaKeywords: 'aysa-entity-meta-keywords',
            secondKeyword: 'aysa-entity-second-keyword'
        };
        
        switch (entityType) {
            case 'Product':
                return {
                    ...baseMapping,
                    entityTitle: 'title',
                    entityContent: 'content',
                    shortDescription: 'excerpt'
                };
                
            case 'Category':
                return {
                    ...baseMapping,
                    entityTitle: 'name',
                    entityContent: 'description'
                };
                
            default:
                return {
                    ...baseMapping,
                    entityTitle: 'title',
                    entityContent: 'content'
                };
        }
    }
    
    _triggerWordPressEvents(suggestions, entityType) {
        // Trigger WordPress events for updated fields
        Object.keys(suggestions).forEach(key => {
            const fieldMapping = this._getMetaboxFieldMapping(entityType);
            const fieldId = fieldMapping[key];
            
            if (fieldId) {
                const element = document.getElementById(fieldId);
                if (element) {
                    // Trigger change event
                    const event = new Event('change', { bubbles: true });
                    element.dispatchEvent(event);
                    
                    // Trigger input event for real-time validation
                    const inputEvent = new Event('input', { bubbles: true });
                    element.dispatchEvent(inputEvent);
                }
            }
        });
    }
    
    _triggerVersioning(results, entityType) {
        // Trigger versioning service if available
        if (typeof window.aysaVersioningService !== 'undefined') {
            try {
                window.aysaVersioningService.logSuggestions({
                    entityType,
                    suggestions: results,
                    timestamp: new Date().toISOString()
                });
            } catch (error) {
                console.warn('🚀 AysaSeoIntegration: Versioning failed:', error);
            }
        }
    }
    
    _revertToOriginal(fieldId) {
        // This would need to be implemented based on how original values are stored
        // For now, just clear the field
        const element = document.getElementById(fieldId);
        if (element) {
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get(fieldId)) {
                tinyMCE.get(fieldId).setContent('');
            } else {
                element.value = '';
            }
            
            if (typeof showToast === 'function') {
                showToast('Field cleared. Original value restoration requires additional implementation.', 'info');
            }
        }
    }
}

// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AysaSeoIntegration;
} else {
    window.AysaSeoIntegration = AysaSeoIntegration;
}