/**
 * AYSA SEO Generator Class
 * Reusable class for generating SEO suggestions across different contexts
 * Extracted from aysa-metabox functionality while preserving original implementation
 */

class AysaSeoGenerator {
    constructor(options = {}) {
        this.options = {
            // Default API timeout settings
            defaultTimeout: 30000, // 30 seconds
            contentTimeout: 120000, // 2 minutes for content generation
            totalTimeout: 180000, // 3 minutes total timeout
            
            // API endpoints
            apiBaseUrl: 'https://api.aysa.ai/api',
            
            // Default language and settings
            defaultLanguage: 'en',
            
            // Callbacks
            onProgress: null,
            onSuccess: null,
            onError: null,
            onComplete: null,
            
            // UI elements (optional)
            button: null,
            spinner: null,
            
            ...options
        };
        
        // Store pre-generation data for versioning
        this.preGenerationData = {};
        this.progressTimers = [];
        
        // Helper functions for content processing
        this._sanitizeContent = this._sanitizeContent || this._defaultSanitizeContent;
        this._removeH1Tags = this._removeH1Tags || this._defaultRemoveH1Tags;

        
        // Set global keyword for On-Page Optimization context
        if (window.location.href.includes('aysa-on-page-optimization')) {
            setTimeout(() => {
                this._setGlobalKeyword();
            }, 1000); // Wait for table to load
        }
    }

    _getApiBaseUrl() {
        let baseUrl = this.options.apiBaseUrl
            || window?.aysa_params?.api_base_url
            || window?.aysaParams?.api_base_url
            || 'https://api.aysa.ai/api';

        baseUrl = String(baseUrl || '').trim().replace(/\/+$/, '');
        if (!/\/api$/i.test(baseUrl)) {
            baseUrl += '/api';
        }

        return baseUrl;
    }

    _buildApiUrl(path) {
        return `${this._getApiBaseUrl()}/${String(path || '').replace(/^\/+/, '')}`;
    }

    _isOptionalSuggestionType(type) {
        return type === 'second-keyword';
    }
    
    // Default content sanitization function
    _defaultSanitizeContent(content, preserveAllHtml = true) {
        if (!content || typeof content !== 'string') {
            return '';
        }
        
        // Remove markdown code markers while preserving HTML
        let sanitized = content.replace(/```[\s\S]*?```/g, '');
        sanitized = sanitized.replace(/`([^`]+)`/g, '$1');
        
        if (!preserveAllHtml) {
            // Strip HTML tags except basic formatting
            sanitized = sanitized.replace(/<[^>]*>/g, '');
        }
        
        return sanitized.trim();
    }
    
    // Default H1 tag removal function
    _defaultRemoveH1Tags(content) {
        if (!content || typeof content !== 'string') {
            return '';
        }
        
        // Remove H1 tags and their content
        let cleaned = content.replace(/<h1[^>]*>[\s\S]*?<\/h1>/gi, '');
        
        // Also remove standalone H1 tags
        cleaned = cleaned.replace(/<h1[^>]*\/>/gi, '');
        
        return cleaned.trim();
    }
    
    /**
     * Main method to generate SEO suggestions
     * @param {Object} config - Configuration object
     * @param {string} config.entityId - Entity ID
     * @param {string} config.entityType - Entity type (Product, Category, Page, etc.)
     * @param {string} config.keyword - Main keyword
     * @param {string} config.entityName - Entity name
     * @param {string} config.language - Language code
     * @param {string} config.websiteName - Website name for context
     * @param {Object} config.existingData - Existing SEO data to preserve
     * @returns {Promise<Object>} Generated SEO suggestions
     */
    async generateSuggestions(config) {
        const {
            entityId,
            entityType,
            keyword,
            entityName,
            language = this.options.defaultLanguage,
            websiteName = 'WordPress',
            existingData = {}
        } = config;
        
        // Store the provided keyword, entity type, and entity ID globally for this generation session
        if (keyword) {
            this.currentSessionKeyword = keyword;
            console.log('🚀 [DEBUG] Stored session keyword:', keyword);
        }
        if (entityType) {
            this.currentSessionEntityType = entityType;
            console.log('🚀 [DEBUG] Stored session entity type:', entityType);
        }
        if (entityId) {
            this.currentSessionEntityId = entityId;
            console.log('🚀 [DEBUG] Stored session entity ID:', entityId);
        }
        
        try {
            // Validate required parameters
            this._validateConfig(config);
            
            // Store pre-generation data for versioning
            this._capturePreGenerationData(existingData);
            
            // Show progress if UI elements are provided
            this._showProgress('Preparing APIs...');
            
            // Pre-fetch SEO settings and secondary keywords ONCE
            const projectId = this._getProjectId();
            const seoSettings = await this._getSeoSettings(projectId);
            const association = this._getCurrentAssociation();
            let secondKeywords = association?.SecondKeyword || '';
            
            // Keep on-page generation resilient even if enrichment endpoints are unavailable.
            if (!secondKeywords) {
                secondKeywords = this._buildStaticSecondaryKeywords(keyword);
            }
            
            // Store pre-fetched data for use in API calls
            this._prefetchedData = {
                seoSettings,
                secondKeywords,
                projectId
            };
            
            console.log('🚀 [DEBUG] Pre-fetched data stored:', {
                hasSeoSettings: !!seoSettings,
                hasSecondKeywords: !!secondKeywords,
                projectId: projectId
            });
            
            // Determine which API calls to make based on entity type
            const apiCalls = this._prepareApiCalls(entityType, keyword, language, websiteName);
            
            console.log('🚀 [DEBUG] API calls to execute:', apiCalls.length, 'calls:', apiCalls.map(call => call.type));
            
            // Execute API calls with timeout handling
            const results = await this._executeApiCalls(apiCalls);
            
            console.log('🚀 [DEBUG] API execution completed:', {
                successCount: results.successCount,
                failureCount: results.failureCount,
                totalCalls: results.apiCalls.length
            });
            
            // Process and format results
            const processedResults = await this._processResults(results, entityType, existingData);
            
            // Call success callback
            if (this.options.onSuccess) {
                this.options.onSuccess(processedResults);
            }
            
            return processedResults;
            
        } catch (error) {
            console.error('🚀 AysaSeoGenerator: Error during SEO generation', error);
            
            // Call error callback
            if (this.options.onError) {
                this.options.onError(error);
            }
            
            throw error;
        } finally {
            // Clean up and call complete callback
            this._cleanup();
            
            if (this.options.onComplete) {
                this.options.onComplete();
            }
        }
    }
    
    /**
     * Generate SEO suggestions for a specific field type
     * @param {string} fieldType - Type of field (meta-title, meta-description, etc.)
     * @param {string} keyword - Main keyword
     * @param {string} language - Language code
     * @param {string} context - Additional context (websiteName, entityType, etc.)
     * @returns {Promise<string>} Generated suggestion
     */
    async generateSingleSuggestion(fieldType, keyword, language, context) {
        try {
            return await this._fetchSuggestionWithTimeout(fieldType, keyword, language, context, this.options.defaultTimeout);
        } catch (error) {
            console.warn(`🚀 AysaSeoGenerator: Failed to generate ${fieldType}:`, error);
            return await this._generateFallback(fieldType, keyword, context);
        }
    }
    
    /**
     * Apply generated suggestions to form fields
     * @param {Object} suggestions - Generated suggestions
     * @param {Object} fieldMapping - Mapping of suggestion keys to field IDs
     * @param {Object} options - Application options
     */
    applySuggestionsToFields(suggestions, fieldMapping = {}, options = {}) {
        const {
            preserveExisting = true,
            mergeSecondaryKeywords = true,
            showToasts = true
        } = options;
        
        
        
        // Default field mapping
        const defaultMapping = {
            metaTitle: 'aysa-entity-meta-title',
            metaDescription: 'aysa-entity-meta-description',
            metaKeywords: 'aysa-entity-meta-keywords',
            secondKeyword: 'aysa-entity-second-keyword',
            entityTitle: 'title',
            productTitle: 'title',
            productDescription: 'content',
            shortProductDescription: 'excerpt',
            categoryTitle: 'name',
            categoryDescription: 'description'
        };
        
        const mapping = { ...defaultMapping, ...fieldMapping };
        
        // Apply each suggestion to its corresponding field
        Object.keys(suggestions).forEach(key => {
            const fieldId = mapping[key];
            const value = suggestions[key];
            
            if (fieldId && value && typeof value === 'string' && value.trim() !== '') {
                this._updateField(fieldId, value, {
                    preserveExisting,
                    mergeSecondaryKeywords: key === 'secondKeyword' && mergeSecondaryKeywords,
                    showToasts
                });
                
                // Special handling for product title - use proper WooCommerce functions
                if (key === 'entityTitle' || key === 'productTitle') {
                    console.log('🚀 AysaSeoGenerator: Applying product title update');
                    
                    // Try to use existing product title functions if available
                    if (typeof window.updateProductTitle === 'function') {
                        console.log('🚀 AysaSeoGenerator: Using updateProductTitle function');
                        window.updateProductTitle(value);
                    } else {
                        // Fallback: update title field directly
                        this._updateField('title', value, {
                            preserveExisting: false,
                            mergeSecondaryKeywords: false,
                            showToasts: false
                        });
                    }
                    
                    // Update multiple possible title fields
                    const titleFields = [
                        'title',
                        'post_title',
                        'product_title',
                        'input[name="title"]',
                        'input[name="post_title"]',
                        'input[name="product_title"]'
                    ];
                    
                    titleFields.forEach(fieldName => {
                        const element = document.getElementById(fieldName) || document.querySelector(fieldName);
                        if (element) {
                            console.log(`🚀 AysaSeoGenerator: Found title field: ${fieldName}`);
                            this._updateField(fieldName, value, {
                                preserveExisting: false,
                                mergeSecondaryKeywords: false,
                                showToasts: false
                            });
                        }
                    });
                }
                
                // Special handling for WooCommerce short description - try multiple fields
                if (key === 'shortProductDescription') {
                    console.log('🚀 AysaSeoGenerator: Applying short product description to multiple fields');
                    
                    // Try WooCommerce specific fields
                    const wooCommerceFields = [
                        'product_short_description',
                        'woocommerce-product-short-description',
                        'excerpt',
                        'post_excerpt'
                    ];
                    
                    wooCommerceFields.forEach(fieldName => {
                        const element = document.getElementById(fieldName) || document.querySelector(`[name="${fieldName}"]`);
                        if (element) {
                            console.log(`🚀 AysaSeoGenerator: Found WooCommerce short description field: ${fieldName}`);
                            this._updateField(fieldName, value, {
                                preserveExisting: false,
                                mergeSecondaryKeywords: false,
                                showToasts: false
                            });
                        }
                    });
                    
                    // Try TinyMCE editor for excerpt
                    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
                        console.log('🚀 AysaSeoGenerator: Updating TinyMCE excerpt editor');
                        tinyMCE.get('excerpt').setContent(value, { format: 'raw' });
                    }
                }
                
                // Special handling for product description - use proper WooCommerce functions
                if (key === 'entityContent' || key === 'productDescription') {
                    console.log('🚀 AysaSeoGenerator: Applying product description to multiple editors');
                    
                    // Sanitize content and remove H1 tags for description fields
                    const sanitizedContent = this._sanitizeContent ? this._sanitizeContent(value) : value;
                    const contentWithoutH1 = this._removeH1Tags ? this._removeH1Tags(sanitizedContent) : sanitizedContent;
                    
                    // Try to use existing WooCommerce functions if available
                    if (typeof window.updateWooCommerceDescription === 'function') {
                        console.log('🚀 AysaSeoGenerator: Using updateWooCommerceDescription function');
                        window.updateWooCommerceDescription(contentWithoutH1);
                    } else {
                        // Fallback: update content field directly
                        this._updateField('content', contentWithoutH1, {
                            preserveExisting: false,
                            mergeSecondaryKeywords: false,
                            showToasts: false
                        });
                    }
                    
                    // Update TinyMCE editor for content if it exists
                    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                        console.log('🚀 AysaSeoGenerator: Updating TinyMCE content editor');
                        tinyMCE.get('content').setContent(contentWithoutH1, { format: 'raw' });
                    }
                }
                
                // Special handling for permalink - use proper permalink functions
                if (key === 'permalink') {
                    console.log('🚀 AysaSeoGenerator: Applying permalink update');
                    
                    // Try to use existing permalink functions if available
                    if (typeof window.updateProductPermalink === 'function') {
                        console.log('🚀 AysaSeoGenerator: Using updateProductPermalink function');
                        window.updateProductPermalink(value);
                    } else {
                        // Fallback: update permalink fields directly
                        const permalinkFields = [
                            'post_name',
                            'slug',
                            'editable-post-name'
                        ];
                        
                        permalinkFields.forEach(fieldName => {
                            const element = document.getElementById(fieldName) || document.querySelector(`[name="${fieldName}"]`);
                            if (element) {
                                console.log(`🚀 AysaSeoGenerator: Found permalink field: ${fieldName}`);
                                this._updateField(fieldName, value, {
                                    preserveExisting: false,
                                    mergeSecondaryKeywords: false,
                                    showToasts: false
                                });
                            }
                        });
                    }
                }
            }
        });
        
        // Log to history if available
        this._logToHistory(suggestions, options);
    }
    
    /**
     * Get current form data for versioning
     * @param {Array} fieldIds - Array of field IDs to capture
     * @returns {Object} Current form data
     */
    getCurrentFormData(fieldIds = []) {
        const defaultFields = [
            'aysa-entity-meta-title',
            'aysa-entity-meta-description',
            'aysa-entity-meta-keywords',
            'aysa-entity-second-keyword',
            'title',
            'content',
            'excerpt',
            'name',
            'description'
        ];
        
        const fields = fieldIds.length > 0 ? fieldIds : defaultFields;
        const data = {};
        
        fields.forEach(fieldId => {
            const element = document.getElementById(fieldId);
            if (element) {
                // Handle TinyMCE editors
                if (typeof tinyMCE !== 'undefined' && tinyMCE.get(fieldId)) {
                    data[fieldId] = tinyMCE.get(fieldId).getContent();
                } else {
                    data[fieldId] = element.value || element.textContent || '';
                }
            }
        });
        
        return data;
    }
    
    // Private methods
    
    _validateConfig(config) {
        const required = ['entityType', 'keyword'];
        const missing = required.filter(key => !config[key]);
        
        if (missing.length > 0) {
            throw new Error(`Missing required configuration: ${missing.join(', ')}`);
        }
        
        // Validate entity type
        const validTypes = ['Product', 'Category', 'Page', 'Post'];
        if (!validTypes.includes(config.entityType)) {
            console.warn(`🚀 AysaSeoGenerator: Unknown entity type: ${config.entityType}`);
        }
    }
    
    _capturePreGenerationData(existingData) {
        this.preGenerationData = {
            timestamp: new Date().toISOString(),
            ...existingData,
            ...this.getCurrentFormData()
        };
        
        
    }
    
    _showProgress(message) {
        if (this.options.onProgress) {
            this.options.onProgress(message);
        }
        
        if (this.options.button) {
            this._updateButtonProgress(message);
        }
    }
    
    _updateButtonProgress(message) {
        if (this.options.button) {
            this.options.button.disabled = true;
            this.options.button.innerHTML = `
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle; animation: spin 1s linear infinite;">
                    <path d="M12,4V2A10,10 0 0,0 2,12H4A8,8 0 0,1 12,4Z"/>
                </svg>
                ${message}
            `;
        }
        
        if (this.options.spinner) {
            this.options.spinner.classList.add('is-active');
        }
    }
    
    _prepareApiCalls(entityType, keyword, language, websiteName) {
        const calls = [];
        
        // Common API calls for all entity types
        calls.push(
            { type: 'meta-title', keyword, language, context: websiteName, timeout: this.options.defaultTimeout },
            { type: 'meta-keywords', keyword, language, context: websiteName, timeout: this.options.defaultTimeout },
            { type: 'meta-description', keyword, language, context: websiteName, timeout: this.options.defaultTimeout }
        );
        
        // Entity-specific API calls
        switch (entityType) {
            case 'Product':
                calls.push(
                    { type: 'product-or-category-title', keyword, language, context: 'product', timeout: this.options.defaultTimeout },
                    { type: 'seo-optimized-content', keyword, language, context: websiteName, timeout: this.options.contentTimeout },
                    { type: 'product-short-description', keyword, language, context: websiteName, timeout: this.options.defaultTimeout },
                    { type: 'product-permalink', keyword, language, context: websiteName, timeout: this.options.defaultTimeout }
                );
                break;
                
            case 'Category':
                calls.push(
                    { type: 'product-or-category-title', keyword, language, context: 'category', timeout: this.options.defaultTimeout },
                    { type: 'seo-optimized-content', keyword, language, context: websiteName, timeout: this.options.contentTimeout },
                    { type: 'category-permalink', keyword, language, context: websiteName, timeout: this.options.defaultTimeout }
                );
                break;
                
            default:
                calls.push(
                    { type: 'seo-optimized-content', keyword, language, context: websiteName, timeout: this.options.contentTimeout }
                );
                break;
        }
        
        return calls;
    }
    
    async _executeApiCalls(apiCalls) {
        
        
        // Set up progress indicators
        this._setupProgressIndicators();
        
        // Execute all API calls with Promise.allSettled for partial failure handling
        const promises = apiCalls.map(call => 
            this._fetchSuggestionWithTimeout(call.type, call.keyword, call.language, call.context, call.timeout)
        );
        
        const settledResults = await Promise.allSettled(promises);
        
        // Process results and track success/failure
        const results = [];
        let successCount = 0;
        let failureCount = 0;
        
        settledResults.forEach((result, index) => {
            if (result.status === 'fulfilled') {
                results.push(result.value);
                successCount++;
                
            } else {
                results.push('');
                failureCount++;
                console.warn(`🚀 AysaSeoGenerator: API call ${index} (${apiCalls[index].type}) failed:`, result.reason);
            }
        });
        
        
        
        // Show appropriate feedback
        this._showApiResultsFeedback(successCount, failureCount);
        
        return { results, apiCalls, successCount, failureCount };
    }
    
    _setupProgressIndicators() {
        // Clear any existing timers
        this.progressTimers.forEach(timer => clearTimeout(timer));
        this.progressTimers = [];
        
        // Set up progress messages
        this.progressTimers.push(
            setTimeout(() => this._showProgress('Generating meta title...'), 2000),
            setTimeout(() => this._showProgress('Generating meta description...'), 8000),
            setTimeout(() => this._showProgress('Generating SEO content (may take 1-2 min)...'), 15000),
            setTimeout(() => this._showProgress('Slower APIs in progress... please wait...'), 30000),
            setTimeout(() => this._showProgress('Finalizing processing...'), 60000),
            setTimeout(() => this._showProgress('Last APIs... almost done...'), 90000)
        );
    }
    
    _showApiResultsFeedback(successCount, failureCount) {
        if (typeof showToast === 'function') {
            if (failureCount === 0) {
                showToast('SEO suggestions generated successfully!', 'success');
            } else if (successCount > 0) {
                showToast('SEO suggestions generated. Some optional enrichments were unavailable, so AYSA used safe fallbacks where needed.', 'warning');
            } else {
                showToast('All APIs failed. Using local fallbacks.', 'info');
            }
        }
    }
    
    async _processResults(apiResults, entityType, existingData) {
        const { results, apiCalls } = apiResults;
        const processed = {};
        
        // Map results back to their types
        results.forEach((result, index) => {
            const callType = apiCalls[index].type;
            processed[this._mapApiTypeToKey(callType)] = result || '';
        });
        
        // Generate fallbacks for empty results
        for (const key of Object.keys(processed)) {
            if (!processed[key] || processed[key].trim() === '') {
                processed[key] = await this._generateFallback(key, apiCalls[0].keyword, entityType);
            }
        }
        
        if (!processed.secondKeyword || String(processed.secondKeyword).trim() === '') {
            processed.secondKeyword = this._prefetchedData?.secondKeywords || this._buildStaticSecondaryKeywords(apiCalls[0].keyword);
        }

        return processed;
    }
    
    _mapApiTypeToKey(apiType) {
        const mapping = {
            'meta-title': 'metaTitle',
            'meta-description': 'metaDescription',
            'meta-keywords': 'metaKeywords',
            'second-keyword': 'secondKeyword',
            'product-or-category-title': 'entityTitle',
            'seo-optimized-content': 'entityContent',
            'product-short-description': 'shortProductDescription',
            'product-permalink': 'permalink',
            'category-permalink': 'permalink'
        };
        
        return mapping[apiType] || apiType;
    }
    
    async _fetchSuggestionWithTimeout(type, keyword, language, context, timeoutMs) {
        
        
        return Promise.race([
            this._fetchSuggestion(type, keyword, language, context),
            new Promise((_, reject) => {
                setTimeout(() => {
                    reject(new Error(`Timeout after ${timeoutMs}ms for ${type}`));
                }, timeoutMs);
            })
        ]).catch(error => {
            console.warn(`🚀 AysaSeoGenerator: API call for ${type} failed:`, error.message);
            return '';
        });
    }
    
    async _fetchSuggestion(type, keyword, language, context) {
        // This method should implement the actual API call logic
        // For now, we'll use the existing fetchSuggestion function if available
        // if (typeof fetchSuggestion === 'function') {
        //     return await fetchSuggestion(type, keyword, language, context);
        // }
        
        // If fetchSuggestion is not available, use our own implementation
        console.log('🚀 AysaSeoGenerator: Using internal fetchSuggestion implementation');
        return await this._internalFetchSuggestion(type, keyword, language, context);
    }
    
    async _internalFetchSuggestion(type, keyword, language, brandName) {
        let url = '';
        let method = 'GET';
        let data = null;
        
        // Use pre-fetched data if available, otherwise fetch individually
        const projectId = this._prefetchedData?.projectId || this._getProjectId();
        const seoSettings = this._prefetchedData?.seoSettings || await this._getSeoSettings(projectId);
        const secondKeywords = this._prefetchedData?.secondKeywords || '';
        
        console.log('🚀 [DEBUG] _internalFetchSuggestion using pre-fetched data:', {
            type: type,
            usingPrefetchedSeoSettings: !!this._prefetchedData?.seoSettings,
            usingPrefetchedSecondKeywords: !!this._prefetchedData?.secondKeywords,
            projectId: projectId
        });
        
        // Get association data if available
        const association = this._getCurrentAssociation();
        const entityUrl = association?.Link || this._getEntityUrl();
        const entityType = association?.AssociatedOn || association?.associatedOn || this.currentSessionEntityType || 'product';
        
        const targetedSearchEngine = association?.TargetedSearchEngine || seoSettings?.targetedSearchEngine || '';
        const targetedCountry = association?.TargetedCountry || seoSettings?.targetedCountry || '';
        const targetedRegion = association?.TargetedRegion || seoSettings?.targetedRegion || '';
        const targetedCity = association?.TargetedCity || seoSettings?.targetedCity || '';
        const updateFrequency = association?.UpdateFrequency || seoSettings?.updateFrequency || '';
        const languageOptimize = association?.LanguageOptimize || seoSettings?.languageOptimize || language || 'en';
        const deviceOptimize = association?.DeviceOptimize || seoSettings?.deviceOptimize || '';
        
        console.log('🚀 [DEBUG] Final settings used:', {
            targetedSearchEngine,
            targetedCity,
            updateFrequency,
            languageOptimize,
            entityUrl,
            entityType
        });
        
        // Build the appropriate URL based on suggestion type
        switch (type) {
            case 'second-keyword':
                const locationName = 'Romania';
                url = `${this._buildApiUrl('SEO/keywords-for-keywords-for-plugin')}?keyword=${encodeURIComponent(keyword)}&locationName=${encodeURIComponent(locationName)}&projectId=${encodeURIComponent(projectId)}`;
                console.log('🔍 AysaSeoGenerator: About to call keywords-for-keywords-for-plugin endpoint:', url);
                break;
            case 'meta-title':
                url = this._buildApiUrl('chatgpt/seo-meta-title');
                method = 'POST';
                data = {
                    language: languageOptimize,
                    pageType: entityType,
                    domain: window.location.origin,
                    primaryKeyword: keyword,
                    secondaryKeywords: secondKeywords ? secondKeywords.split(',').map(k => k.trim()) : [],
                    relatedKeywords: [],
                    targetAudience: targetedSearchEngine,
                    searchIntent: updateFrequency,
                    city: targetedCity,
                    brandName: brandName || this._getBrandName(),
                    projectId: projectId
                };
                break;
            case 'meta-keywords':
                url = this._buildApiUrl('chatgpt/seo-meta-keywords');
                method = 'POST';
                data = {
                    language: languageOptimize,
                    pageType: entityType,
                    domain: window.location.origin,
                    primaryKeyword: keyword,
                    secondaryKeywords: secondKeywords ? secondKeywords.split(',').map(k => k.trim()) : [],
                    relatedKeywords: [],
                    projectId: projectId
                };
                break;
            case 'meta-description':
                url = this._buildApiUrl('chatgpt/seo-meta-description');
                method = 'POST';
                data = {
                    language: languageOptimize,
                    pageType: entityType,
                    domain: window.location.origin,
                    primaryKeyword: keyword,
                    secondaryKeywords: secondKeywords ? secondKeywords.split(',').map(k => k.trim()) : [],
                    relatedKeywords: [],
                    targetAudience: targetedSearchEngine,
                    searchIntent: updateFrequency,
                    city: targetedCity,
                    brandName: brandName || this._getBrandName(),
                    projectId: projectId
                };
                break;
            case 'seo-optimized-content':
                url = this._buildApiUrl('chatgpt/seo-optimized-content');
                method = 'POST';
                data = {
                    language: languageOptimize,
                    pageType: entityType,
                    domain: window.location.origin,
                    primaryKeyword: keyword,
                    secondaryKeywords: secondKeywords ? secondKeywords.split(',').map(k => k.trim()) : [],
                    relatedKeywords: [],
                    minimumWordCount: 300,
                    documentOutline: [],
                    includeTldr: false,
                    numberOfImages: 0,
                    city: targetedCity,
                    paymentMethods: [],
                    deliveryMethods: [],
                    tone: 'professional',
                    targetAudience: targetedSearchEngine,
                    searchIntent: updateFrequency,
                    existingPageContent: false,
                    pageUrl: entityUrl,
                    websiteContext: this._getWebsiteContext(),
                    brandName: brandName || this._getBrandName(),
                    includeFaq: true,
                    includeFaqSchema: false,
                    competitorUrls: [],
                    projectId: projectId
                };
                break;
            case 'product-permalink':
            case 'category-permalink':
                const pageType = type === 'product-permalink' ? 'product' : 'category';
                url = `${this._buildApiUrl('chatgpt/seo-friendly-url')}?target_keyword=${encodeURIComponent(keyword)}&language=${languageOptimize}&page_type=${pageType}&projectId=${projectId}`;
                break;
            case 'product-or-category-title':
                const titlePageType = brandName || 'product';
                url = `${this._buildApiUrl('chatgpt/product-or-category-title')}?target_keyword=${encodeURIComponent(keyword)}&language=${languageOptimize}&page_type=${titlePageType}&projectId=${projectId}`;
                break;
            case 'product-short-description':
                url = `${this._buildApiUrl('chatgpt/product-short-description')}?keyword=${encodeURIComponent(keyword)}&language=${languageOptimize}&projectId=${projectId}`;
                break;
            default:
                console.warn(`DEBUG _internalFetchSuggestion - Unknown suggestion type: ${type}`);
                return '';
        }
        
        // For GET requests
        if (method === 'GET') {
            try {
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json',
                        'Origin': window.location.origin
                    },
                    mode: 'cors'
                });
                
                if (!response.ok) {
                    if (this._isOptionalSuggestionType(type)) {
                        console.warn(`Optional ${type} API unavailable, continuing with fallback.`, {
                            status: response.status,
                            statusText: response.statusText
                        });
                    } else {
                        console.error(`Error response from ${type} API:`, response.statusText);
                    }
                    return '';
                }
                
                const text = await response.text();
                if (!text) {
                    console.warn(`Empty response for ${type}`);
                    return '';
                }
                
                try {
                    const data = JSON.parse(text.trim());
                    
                    // Special handling for second-keyword
                    if (type === 'second-keyword') {
                        console.log('🔍 AysaSeoGenerator: Processing keywords-for-keywords-for-plugin response');
                        console.log('🔍 AysaSeoGenerator: Response data:', data);
                        console.log('🔍 AysaSeoGenerator: Has primary_keyword (clustering format):', !!(data && data.primary_keyword));
                        
                        // First try DataForSEO format
                        if (data && data.tasks && data.tasks.length > 0) {
                            const task = data.tasks[0];
                            if (task.result && Array.isArray(task.result) && task.result.length > 0) {
                                const suggestedKeywords = task.result
                                    .filter(item => item.keyword && item.keyword.toLowerCase() !== keyword.toLowerCase())
                                    .slice(0, 20)
                                    .map(item => item.keyword)
                                    .join(', ');
                                return suggestedKeywords;
                            }
                        }
                        
                        // Try keyword-clustering format
                        if (data && typeof data === 'object' && data.primary_keyword && 
                            (data.short_tail_keywords || data.mid_tail_keywords || data.long_tail_keywords || data.related_keywords || data.lsi_keywords)) {
                            console.log('🔍 AysaSeoGenerator: Detected keyword-clustering format in main API response');
                            
                            // Collect all keyword types into a single list
                            const allKeywords = [];
                            
                            // Add short-tail keywords
                            if (data.short_tail_keywords && Array.isArray(data.short_tail_keywords)) {
                                allKeywords.push(...data.short_tail_keywords);
                            }
                            
                            // Add mid-tail keywords
                            if (data.mid_tail_keywords && Array.isArray(data.mid_tail_keywords)) {
                                allKeywords.push(...data.mid_tail_keywords);
                            }
                            
                            // Add long-tail keywords
                            if (data.long_tail_keywords && Array.isArray(data.long_tail_keywords)) {
                                allKeywords.push(...data.long_tail_keywords);
                            }
                            
                            // Add related keywords
                            if (data.related_keywords && Array.isArray(data.related_keywords)) {
                                allKeywords.push(...data.related_keywords);
                            }
                            
                            // Add LSI keywords
                            if (data.lsi_keywords && Array.isArray(data.lsi_keywords)) {
                                allKeywords.push(...data.lsi_keywords);
                            }
                            
                            // Filter and format keywords
                            console.log('🔍 AysaSeoGenerator MAIN API DEBUG: All collected keywords:', allKeywords);
                            console.log('🔍 AysaSeoGenerator MAIN API DEBUG: Main keyword for comparison:', keyword.toLowerCase());
                            
                            const filteredKeywords = allKeywords
                                .filter(kw => {
                                    const isValid = kw && typeof kw === 'string' && kw.trim() !== '';
                                    const isDifferent = kw.toLowerCase() !== keyword.toLowerCase();
                                    console.log(`🔍 AysaSeoGenerator MAIN API DEBUG: Keyword "${kw}" - valid: ${isValid}, different: ${isDifferent}`);
                                    return isValid && isDifferent;
                                });
                            
                            console.log('🔍 AysaSeoGenerator MAIN API DEBUG: Filtered keywords:', filteredKeywords);
                            
                            const suggestedKeywords = filteredKeywords
                                .slice(0, 10) // Limit to 10 keywords
                                .join(', ');
                            
                            if (suggestedKeywords) {
                                console.log('✅ AysaSeoGenerator: Extracted keywords from clustering format in main API:', suggestedKeywords);
                                return suggestedKeywords;
                            }
                        }
                        
                        return '';
                    }
                    
                    // Special handling for permalinks
                    if (type === 'product-permalink' || type === 'category-permalink') {
                        if (data && data.seoFriendlyUrl) {
                            return data.seoFriendlyUrl;
                        } else if (data && typeof data === 'string') {
                            return data;
                        }
                        return '';
                    }
                    
                    // For other types, return the content directly
                    return data.content || data.suggestion || data || '';
                    
                } catch (e) {
                    console.error(`Error parsing JSON for ${type}:`, e);
                    if (type === 'product-permalink' && text) {
                        return text;
                    }
                    return '';
                }
            } catch (error) {
                if (this._isOptionalSuggestionType(type)) {
                    console.warn(`Optional ${type} request failed, continuing with fallback.`, error);
                } else {
                    console.error(`Error fetching ${type}:`, error);
                }
                if (type === 'second-keyword') {
                    console.log('🔍 AysaSeoGenerator: keywords-for-keywords-for-plugin call failed, will use fallback');
                }
                return '';
            }
        }
        
        // For POST requests
        else {
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'Origin': window.location.origin
                    },
                    body: JSON.stringify(data),
                    mode: 'cors'
                });
                
                if (!response.ok) {
                    console.error(`Error response from ${type} API:`, response.statusText);
                    return '';
                }
                
                const responseData = await response.json();
                if (!responseData) {
                    console.warn(`Empty response for ${type}`);
                    return '';
                }
                
                return responseData.content || responseData.suggestion || responseData || '';
                
            } catch (error) {
                console.error(`Error fetching ${type}:`, error);
                return '';
            }
        }
    }
    
    _getProjectId() {
        // Try to get project ID from various sources
        if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
            return aysaParams.project_id;
        }
        
        if (typeof aysa_ajax !== 'undefined' && aysa_ajax.project_id) {
            return aysa_ajax.project_id;
        }
        
        // Try to get from localStorage
        return localStorage.getItem('aysa_project_id') || '0';
    }
    
    async _fetchSecondaryKeywordsFromApi(keyword, projectId, seoSettings = null) {
        try {
            // Use location from SEO settings if available, otherwise default to Romania
            const locationName = seoSettings?.targetedCountry || seoSettings?.targetedCity || 'Romania';
            console.log('🚀 [DEBUG] Using location for secondary keywords:', locationName);
            
            const url = `${this._buildApiUrl('SEO/keywords-for-keywords-for-plugin')}?keyword=${encodeURIComponent(keyword)}&locationName=${encodeURIComponent(locationName)}&projectId=${encodeURIComponent(projectId)}`;
            
            console.log('🚀 [DEBUG] Fetching secondary keywords from API:', url);
            
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Origin': window.location.origin
                },
                mode: 'cors'
            });
            
            if (!response.ok) {
                console.warn('Optional secondary keyword API unavailable, using fallback keywords.', {
                    status: response.status,
                    statusText: response.statusText
                });
                return null;
            }
            
            const text = await response.text();
            if (!text) {
                console.warn('Empty response from keywords-for-keywords API');
                return null;
            }
            
            const data = JSON.parse(text);
            
            // Extract keywords from the response
            if (data && data.tasks && data.tasks.length > 0) {
                const task = data.tasks[0];
                if (task.result && Array.isArray(task.result) && task.result.length > 0) {
                    const suggestedKeywords = task.result
                        .filter(item => item.keyword && item.keyword.toLowerCase() !== keyword.toLowerCase())
                        .slice(0, 10) // Limit to 10 keywords
                        .map(item => item.keyword)
                        .join(', ');
                    
                    console.log('🚀 [DEBUG] Secondary keywords fetched for:', keyword);
                    return suggestedKeywords;
                }
            }
            
            return null;
        } catch (error) {
            console.warn('🚀 [DEBUG] Secondary keyword API failed, using fallback keywords:', error);
            return null;
        }
    }
    

    
    _getSecondaryKeywords() {
        const secondKeywordInput = document.getElementById('aysa-entity-second-keyword');
        if (secondKeywordInput && secondKeywordInput.value) {
            return secondKeywordInput.value.split(',').map(k => k.trim()).filter(k => k);
        }
        return [];
    }
    
    _getCurrentAssociation() {
        // Try to get current association from global variable
        console.log('🚀 [DEBUG] Getting current association. Available associations:', window.aysaAssociations);
        
        if (typeof window.aysaAssociations !== 'undefined' && window.aysaAssociations.length > 0) {
            // In On-Page Optimization context, we need to get the association from the table
            if (window.location.href.includes('aysa-on-page-optimization')) {
                // Look for selected row in the table
                const selectedRow = document.querySelector('tr.selected') || document.querySelector('.aysa-association-row.selected');
                if (selectedRow) {
                    const rowId = selectedRow.getAttribute('data-id') || selectedRow.getAttribute('data-association-id');
                    console.log('🚀 [DEBUG] Found selected row with ID:', rowId);
                    
                    // Find association by ID from selected row
                    let association = window.aysaAssociations.find(assoc => assoc.id == rowId || assoc.Id == rowId);
                    if (association) {
                        console.log('🚀 [DEBUG] Found association from selected row:', association);
                        return association;
                    }
                }
                
                // If no selected row, try to get from current context
                const currentKeyword = this._getCurrentKeyword();
                
                // Get entity type from URL or other sources to avoid recursion
                let currentEntityType = 'product'; // Default
                if (typeof aysaParams !== 'undefined' && aysaParams.entityType) {
                    currentEntityType = aysaParams.entityType.toLowerCase();
                } else if (window.location.href.includes('aysa-on-page-optimization')) {
                    // Try to get from table row
                    const currentRow = document.querySelector('.aysa-association-row.selected') || document.querySelector('.aysa-association-row');
                    if (currentRow) {
                        const dataEntityType = currentRow.getAttribute('data-entity-type');
                        if (dataEntityType) {
                            currentEntityType = dataEntityType.toLowerCase();
                        }
                    }
                }
                
                console.log('🚀 [DEBUG] Looking for association with keyword:', currentKeyword, 'and entity type:', currentEntityType);
                
                // Try to find by exact keyword match first
                if (currentKeyword) {
                    let association = window.aysaAssociations.find(assoc => 
                        assoc.keyword === currentKeyword || assoc.Keyword === currentKeyword
                    );
                    if (association) {
                        console.log('🚀 [DEBUG] Found association by exact keyword match:', association);
                        return association;
                    }
                }
                
                // Try to find by entity type and keyword similarity
                if (currentKeyword && currentEntityType) {
                    let association = window.aysaAssociations.find(assoc => {
                        const assocType = assoc.associatedOn || assoc.AssociatedOn;
                        const assocKeyword = assoc.keyword || assoc.Keyword;
                        
                        return assocType === currentEntityType && 
                               assocKeyword && 
                               (assocKeyword.toLowerCase().includes(currentKeyword.toLowerCase()) || 
                                currentKeyword.toLowerCase().includes(assocKeyword.toLowerCase()));
                    });
                    if (association) {
                        console.log('🚀 [DEBUG] Found association by entity type and keyword similarity:', association);
                        return association;
                    }
                }
                
                // Try to find by entity type only
                if (currentEntityType) {
                    let association = window.aysaAssociations.find(assoc => {
                        const assocType = assoc.associatedOn || assoc.AssociatedOn;
                        return assocType === currentEntityType;
                    });
                    if (association) {
                        console.log('🚀 [DEBUG] Found association by entity type only:', association);
                        return association;
                    }
                }
                
                // Try to find by partial keyword match
                if (currentKeyword) {
                    let association = window.aysaAssociations.find(assoc => {
                        const assocKeyword = assoc.keyword || assoc.Keyword;
                        return assocKeyword && assocKeyword.toLowerCase().includes(currentKeyword.toLowerCase());
                    });
                    if (association) {
                        console.log('🚀 [DEBUG] Found association by partial keyword match:', association);
                        return association;
                    }
                }
            }
            
            // Fallback to first association
            const association = window.aysaAssociations[0];
            console.log('🚀 [DEBUG] Using first available association as fallback:', association);
            return association;
        }
        
        console.log('🚀 [DEBUG] No associations available');
        return null;
    }
    
    _getCurrentKeyword() {
        // First, try to get keyword from current session
        if (this.currentSessionKeyword) {
            console.log('🚀 [DEBUG] Using session keyword:', this.currentSessionKeyword);
            return this.currentSessionKeyword;
        }
        
        // Try to get current keyword from various sources
        const urlParams = new URLSearchParams(window.location.search);
        let keyword = urlParams.get('keyword') || '';
        
        // If no keyword in URL, try to get from page context
        if (!keyword) {
            // Try to get from page title or other elements
            const pageTitle = document.title || '';
            if (pageTitle.includes('floare') || pageTitle.includes('flori')) {
                keyword = 'floare';
            }
        }
        
        // If still no keyword, try to get from On-Page Optimization context
        if (!keyword && window.location.href.includes('aysa-on-page-optimization')) {
            // First, try to get from global associations array
            if (typeof window.aysaAssociations !== 'undefined' && window.aysaAssociations.length > 0) {
                // Look for selected row in the table
                const selectedRow = document.querySelector('tr.selected') || document.querySelector('.aysa-association-row.selected');
                if (selectedRow) {
                    const rowId = selectedRow.getAttribute('data-id') || selectedRow.querySelector('[data-id]')?.getAttribute('data-id');
                    if (rowId) {
                        const association = window.aysaAssociations.find(assoc => assoc.id == rowId || assoc.Id == rowId);
                        if (association && (association.keyword || association.Keyword)) {
                            keyword = association.keyword || association.Keyword;
                            console.log('🚀 [DEBUG] Found keyword from selected row association:', keyword);
                        }
                    }
                }
                
                // If still no keyword, try to get from first association
                if (!keyword) {
                    const firstAssociation = window.aysaAssociations[0];
                    if (firstAssociation && (firstAssociation.keyword || firstAssociation.Keyword)) {
                        keyword = firstAssociation.keyword || firstAssociation.Keyword;
                        console.log('🚀 [DEBUG] Found keyword from first association:', keyword);
                    }
                }
            }
            
            // If still no keyword, try to get from table content
            if (!keyword) {
                const keywordCell = document.querySelector('td:nth-child(4)') || document.querySelector('[data-keyword]');
                if (keywordCell) {
                    const cellText = keywordCell.textContent.trim();
                    if (cellText) {
                        keyword = cellText;
                        console.log('🚀 [DEBUG] Found keyword from table cell:', keyword);
                    }
                }
            }
            
            // Try to get from global context
            if (!keyword && typeof window.currentKeyword !== 'undefined') {
                keyword = window.currentKeyword;
                console.log('🚀 [DEBUG] Found keyword from global context:', keyword);
            }
        }
        
        console.log('🚀 [DEBUG] Current keyword found:', keyword);
        return keyword;
    }
    
    _getEntityUrl() {
        // Get entity ID and type from association or session
        const association = this._getCurrentAssociation();
        console.log('🚀 [DEBUG] Getting entity URL. Association:', association);
        
        // Priority: Use session entity type and ID if available
        const entityId = this.currentSessionEntityId || association?.idIntern || association?.IdIntern || this._getEntityId();
        const entityType = this.currentSessionEntityType || association?.AssociatedOn || association?.associatedOn || 'product';
        
        console.log('🚀 [DEBUG] Building URL for Entity ID:', entityId, 'Entity Type:', entityType);
        
        // Build URL based on entity type and ID
        if (entityId && entityId !== 'unknown' && entityId !== 0) {
            let entityUrl = '';
            
            switch (entityType.toLowerCase()) {
                case 'product':
                    // For WooCommerce products, try to get the actual product URL
                    if (typeof aysaParams !== 'undefined' && aysaParams.site_url) {
                        const siteUrl = aysaParams.site_url.replace(/\/$/, ''); // Remove trailing slash
                        // Try to get product slug from association first
                        if (association?.value && typeof association.value === 'string') {
                            const slug = association.value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
                            entityUrl = `${siteUrl}/product/${slug}/`;
                        } else {
                            entityUrl = `${siteUrl}/product/${entityId}/`;
                        }
                    } else {
                        // Fallback to current domain
                        if (association?.value && typeof association.value === 'string') {
                            const slug = association.value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
                            entityUrl = `${window.location.origin}/product/${slug}/`;
                        } else {
                            entityUrl = `${window.location.origin}/product/${entityId}/`;
                        }
                    }
                    break;
                    
                case 'category':
                    // For WooCommerce categories, try to get the actual category URL
                    if (typeof aysaParams !== 'undefined' && aysaParams.site_url) {
                        const siteUrl = aysaParams.site_url.replace(/\/$/, ''); // Remove trailing slash
                        // Try to get category slug from association first
                        if (association?.value && typeof association.value === 'string') {
                            const slug = association.value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
                            entityUrl = `${siteUrl}/product-category/${slug}/`;
                        } else {
                            entityUrl = `${siteUrl}/product-category/${entityId}/`;
                        }
                    } else {
                        // Fallback to current domain
                        if (association?.value && typeof association.value === 'string') {
                            const slug = association.value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
                            entityUrl = `${window.location.origin}/product-category/${slug}/`;
                        } else {
                            entityUrl = `${window.location.origin}/product-category/${entityId}/`;
                        }
                    }
                    break;
                    
                case 'post':
                case 'page':
                    // For posts/pages, use the post ID
                    if (typeof aysaParams !== 'undefined' && aysaParams.site_url) {
                        const siteUrl = aysaParams.site_url.replace(/\/$/, ''); // Remove trailing slash
                        entityUrl = `${siteUrl}/?p=${entityId}`;
                    } else {
                        entityUrl = `${window.location.origin}/?p=${entityId}`;
                    }
                    break;
                    
                default:
                    // Fallback for unknown types
                    if (typeof aysaParams !== 'undefined' && aysaParams.site_url) {
                        const siteUrl = aysaParams.site_url.replace(/\/$/, ''); // Remove trailing slash
                        entityUrl = `${siteUrl}/?p=${entityId}`;
                    } else {
                        entityUrl = `${window.location.origin}/?p=${entityId}`;
                    }
                    break;
            }
            
            console.log('🚀 [DEBUG] Built entity URL:', entityUrl);
            return entityUrl;
        }
        
        // Fallback to site URL if no valid entity ID
        const fallbackUrl = (typeof aysaParams !== 'undefined' && aysaParams.site_url) ? 
            aysaParams.site_url.replace(/\/$/, '') : window.location.origin;
        console.log('🚀 [DEBUG] No valid entity ID found, using fallback URL:', fallbackUrl);
        return fallbackUrl;
    }
    
    _getWebsiteContext() {
        // Get website context from association or fallback
        const association = this._getCurrentAssociation();
        if (association?.Value) {
            return association.Value;
        }
        
        // Fallback to document title
        return document.title || '';
    }
    
    _getBrandName() {
        // Try to get brand name from various sources
        const title = document.title || '';
        if (title.includes(' | ')) {
            return title.split(' | ')[1];
        }
        
        // Try to get from site name
        if (typeof aysaParams !== 'undefined' && aysaParams.site_url) {
            const url = new URL(aysaParams.site_url);
            return url.hostname;
        }
        
        return window.location.hostname;
    }
    
    async _getSeoSettings(projectId) {
        try {
            console.log('🚀 [DEBUG] Fetching SEO settings for project:', projectId);
            const url = this._buildApiUrl(`SeoSettings/ByProject/${projectId}`);
            
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Origin': window.location.origin
                },
                mode: 'cors'
            });
            
            if (!response.ok) {
                console.warn(`Failed to fetch SEO settings for project ${projectId}:`, response.statusText);
                return null;
            }
            
            const seoSettings = await response.json();
            console.log('🚀 [DEBUG] SEO settings fetched for project:', projectId);
            return seoSettings;
            
        } catch (error) {
            console.warn('🚀 AysaSeoGenerator: Error fetching SEO settings:', error);
            return null;
        }
    }
    
    async _generateFallback(type, keyword, context) {
        // Generate basic fallback content based on type
        switch (type) {
            case 'metaTitle':
            case 'meta-title':
                return `${keyword} | ${context || 'WordPress'}`;
                
            case 'metaDescription':
            case 'meta-description':
                return `Discover ${keyword} and related products. Quality content and services for ${keyword}.`;
                
            case 'metaKeywords':
            case 'meta-keywords':
                return `${keyword}, ${keyword} online, best ${keyword}`;
                
            case 'secondKeyword':
            case 'second-keyword':
                return await this._generateFallbackKeywords(keyword, context);
                
            case 'entityTitle':
            case 'product-or-category-title':
                return keyword;
                
            case 'entityContent':
            case 'seo-optimized-content':
                return `<h2>About ${keyword}</h2><p>Discover everything you need to know about ${keyword}. Our comprehensive guide covers all aspects of ${keyword} to help you make informed decisions.</p>`;
                
            case 'shortDescription':
            case 'product-short-description':
                return `Quality ${keyword} with excellent features and benefits.`;
                
            case 'permalink':
            case 'product-permalink':
            case 'category-permalink':
                return keyword.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
                
            default:
                return '';
        }
    }
    
    _buildStaticSecondaryKeywords(keyword) {
        const base = String(keyword || '').trim();
        if (!base) {
            return '';
        }
        return `${base} online, best ${base}, ${base} guide`;
    }

    async _generateFallbackKeywords(keyword, entityType) {
        console.log('🔄 AysaSeoGenerator: Using keyword-clustering fallback for', keyword, entityType);
        
        try {
            // Try to use the keyword-clustering endpoint as fallback
            // Get project ID and language for the API call
            const projectId = this._getProjectId();
            const seoSettings = await this._getSeoSettings(projectId);
            const association = this._getCurrentAssociation();
            const language = association?.LanguageOptimize || seoSettings?.languageOptimize || this.options.defaultLanguage || 'en';
            
            const url = `${this._buildApiUrl('ChatGPT/keyword-clustering')}?primary_keyword=${encodeURIComponent(keyword)}&language=${encodeURIComponent(language)}&projectId=${encodeURIComponent(projectId)}`;
            console.log('🔄 AysaSeoGenerator Fallback: Fetching from keyword-clustering endpoint:', url);
            console.log('🔄 AysaSeoGenerator Fallback: Parameters - keyword:', keyword, 'language:', language, 'projectId:', projectId);
            
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Origin': window.location.origin
                },
                mode: 'cors'
            });
            
            if (!response.ok) {
                console.warn('🔄 AysaSeoGenerator Fallback: keyword-clustering endpoint failed, using static fallback');
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const text = await response.text();
            if (!text) {
                console.warn('🔄 AysaSeoGenerator Fallback: Empty response from keyword-clustering endpoint');
                throw new Error('Empty response');
            }
            
            console.log('🔄 AysaSeoGenerator DEBUG: Raw text before parsing:', text.substring(0, 100));
            
            const data = JSON.parse(text.trim());
            console.log('🔄 AysaSeoGenerator Fallback: keyword-clustering response:', data);
            console.log('🔄 AysaSeoGenerator DEBUG: Parsed data type:', typeof data);
            
            // If data is still a string, parse it again
            let finalData = data;
            if (typeof data === 'string') {
                console.log('🔄 AysaSeoGenerator DEBUG: Data is string, parsing again...');
                finalData = JSON.parse(data);
                console.log('🔄 AysaSeoGenerator DEBUG: Double-parsed data:', finalData);
            }
            
            // Extract keywords from the new keyword-clustering response format
            if (finalData && typeof finalData === 'object' && finalData.primary_keyword) {
                console.log('✅ AysaSeoGenerator Fallback: Valid keyword clustering format detected');
                
                // Collect all keyword types into a single list
                const allKeywords = [];
                
                // Add short-tail keywords
                if (finalData.short_tail_keywords && Array.isArray(finalData.short_tail_keywords)) {
                    allKeywords.push(...finalData.short_tail_keywords);
                }
                
                // Add mid-tail keywords
                if (finalData.mid_tail_keywords && Array.isArray(finalData.mid_tail_keywords)) {
                    allKeywords.push(...finalData.mid_tail_keywords);
                }
                
                // Add long-tail keywords
                if (finalData.long_tail_keywords && Array.isArray(finalData.long_tail_keywords)) {
                    allKeywords.push(...finalData.long_tail_keywords);
                }
                
                // Add related keywords
                if (finalData.related_keywords && Array.isArray(finalData.related_keywords)) {
                    allKeywords.push(...finalData.related_keywords);
                }
                
                // Add LSI keywords
                if (finalData.lsi_keywords && Array.isArray(finalData.lsi_keywords)) {
                    allKeywords.push(...finalData.lsi_keywords);
                }
                
                // Filter and format keywords
                console.log('🔄 AysaSeoGenerator DEBUG: All collected keywords:', allKeywords);
                console.log('🔄 AysaSeoGenerator DEBUG: Main keyword for comparison:', keyword.toLowerCase());
                
                const filteredKeywords = allKeywords
                    .filter(kw => {
                        const isValid = kw && typeof kw === 'string' && kw.trim() !== '';
                        const isDifferent = kw.toLowerCase() !== keyword.toLowerCase();
                        console.log(`🔄 AysaSeoGenerator DEBUG: Keyword "${kw}" - valid: ${isValid}, different: ${isDifferent}`);
                        return isValid && isDifferent;
                    });
                
                console.log('🔄 AysaSeoGenerator DEBUG: Filtered keywords:', filteredKeywords);
                
                const suggestedKeywords = filteredKeywords
                    .slice(0, 10) // Limit to 10 keywords
                    .join(', ');
                
                if (suggestedKeywords) {
                    console.log('✅ AysaSeoGenerator Fallback: Generated keywords from clustering:', suggestedKeywords);
                    return suggestedKeywords;
                } else {
                    console.warn('🔄 AysaSeoGenerator Fallback: No valid keywords found in clustering response');
                    throw new Error('No valid keywords in response');
                }
            } else {
                console.warn('🔄 AysaSeoGenerator Fallback: Invalid keyword clustering format');
                throw new Error('Invalid response format');
            }
            
        } catch (error) {
            console.warn('🔄 AysaSeoGenerator Fallback: keyword-clustering endpoint failed, using static fallback:', error);
            
            // Static fallback when the API fails
            return `${keyword} online, best ${keyword}, ${keyword} guide`;
        }
    }
    
    _updateField(fieldId, value, options = {}) {
        const {
            preserveExisting = true,
            mergeSecondaryKeywords = false,
            showToasts = true
        } = options;
        
        const element = document.getElementById(fieldId);
        if (!element) {
            console.warn(`🚀 AysaSeoGenerator: Field ${fieldId} not found`);
            return;
        }
        
        // Handle secondary keywords merging
        if (mergeSecondaryKeywords && fieldId === 'aysa-entity-second-keyword') {
            this._mergeSecondaryKeywords(element, value, showToasts);
            return;
        }
        
        // Handle TinyMCE editors
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get(fieldId)) {
            if (!preserveExisting || !tinyMCE.get(fieldId).getContent().trim()) {
                tinyMCE.get(fieldId).setContent(value, { format: 'raw' });
                console.log(`🚀 AysaSeoGenerator: Updated TinyMCE field ${fieldId}`);
            }
        } else {
            // Handle regular input fields
            if (!preserveExisting || !element.value.trim()) {
                element.value = value;
                
                // Trigger events to ensure WordPress/WooCommerce recognizes the change
                element.dispatchEvent(new Event('input', { bubbles: true }));
                element.dispatchEvent(new Event('change', { bubbles: true }));
                
                // For WooCommerce fields, trigger additional events
                if (fieldId.includes('product') || fieldId.includes('excerpt')) {
                    element.dispatchEvent(new Event('blur', { bubbles: true }));
                    console.log(`🚀 AysaSeoGenerator: Updated WooCommerce field ${fieldId} with events triggered`);
                } else {
                    console.log(`🚀 AysaSeoGenerator: Updated field ${fieldId}`);
                }
            }
        }
    }
    
    _mergeSecondaryKeywords(element, newKeywords, showToasts) {
        const existingKeywords = element.value.trim() ? 
            element.value.split(',').map(k => k.trim()).filter(k => k !== '') : 
            [];
        
        const suggestedKeywords = newKeywords.split(',')
            .map(k => k.trim())
            .filter(k => k !== '');
        
        const mainKeyword = document.getElementById('aysa-entity-keyword')?.value.trim() || '';
        
        // Filter out duplicates and main keyword
        const newUniqueKeywords = suggestedKeywords.filter(k => 
            k !== mainKeyword && !existingKeywords.includes(k)
        );
        
        // Merge keywords
        const allKeywords = [...existingKeywords, ...newUniqueKeywords];
        element.value = allKeywords.join(', ');
        
        // Show feedback
        if (showToasts && typeof showToast === 'function') {
            if (newUniqueKeywords.length > 0) {
                showToast(`Added ${newUniqueKeywords.length} new secondary keywords. Existing keywords preserved.`, 'success');
            } else {
                showToast('All suggested secondary keywords already exist.', 'info');
            }
        }
    }
    
    _cleanup() {
        // Clear progress timers
        this.progressTimers.forEach(timer => clearTimeout(timer));
        this.progressTimers = [];
        
        // Reset button state
        if (this.options.button) {
            this.options.button.disabled = false;
            this.options.button.innerHTML = `
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle;">
                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                </svg>
                Generate SEO Suggestions
            `;
        }
        
        // Hide spinner
        if (this.options.spinner) {
            this.options.spinner.classList.remove('is-active');
        }
        
        // Reset session data
        this.currentSessionKeyword = null;
        this.currentSessionEntityType = null;
        this.currentSessionEntityId = null;
        
        // Clear pre-fetched data
        this._prefetchedData = null;
        
        console.log('🚀 [DEBUG] Cleanup completed, session data reset');
    }
    
    /**
     * Log SEO generation to history
     * @param {Object} suggestions - The generated suggestions
     * @param {Object} options - Generation options
     * @private
     */
    _logToHistory(suggestions, options = {}) {
        try {
            // Check if history logging is available
            if (typeof window.aysaSeoHistory === 'undefined' || 
                typeof window.aysaSeoHistory.logGeneration !== 'function') {
                
                return;
            }
            
            // Prepare history data
            const historyData = {
                entity_id: this._getEntityId(),
                entity_type: this._getEntityType(),
                entity_name: this._getEntityName(),
                keyword: this.options.keyword || '',
                language: this.options.defaultLanguage || 'en',
                generator_type: 'new',
                generation_method: 'api',
                
                // Generated content
                meta_title: suggestions.metaTitle || '',
                meta_description: suggestions.metaDescription || '',
                meta_keywords: suggestions.metaKeywords || '',
                secondary_keywords: suggestions.secondKeyword || '',
                product_title: suggestions.entityTitle || '',
                product_description: suggestions.entityContent || '',
                permalink: suggestions.permalink || '',
                
                // Metadata
                generation_metadata: {
                    timestamp: new Date().toISOString(),
                    user_agent: navigator.userAgent,
                    generator_version: '1.0.0',
                    options: this.options,
                    applied_fields: options.appliedFields || [],
                    confidence_score: suggestions.confidenceScore || null
                },
                
                // Previous values (if available)
                previous_data: this._getPreviousValues(),
                
                // API response data (if available)
                api_response_data: suggestions._apiResponse || null,
                api_response_time: suggestions._responseTime || null,
                
                // Status
                status: 'generated',
                partial_failure: suggestions._partialFailure || false,
                failed_fields: suggestions._failedFields ? suggestions._failedFields.join(', ') : null
            };
            
            // Log to history
            window.aysaSeoHistory.logGeneration(historyData);
            
            
            
        } catch (error) {
            console.warn('🚀 AysaSeoGenerator: Failed to log to history:', error);
        }
    }
    
    /**
     * Get current entity ID
     * @returns {number|string}
     * @private
     */
    _getEntityId() {
        // Try various methods to get entity ID
        if (this.options.entityId) {
            return this.options.entityId;
        }
        
        // WordPress post/page ID
        if (typeof window.pagenow !== 'undefined' && window.pagenow === 'post') {
            const postId = document.getElementById('post_ID');
            if (postId) return postId.value;
        }
        
        // WooCommerce product ID
        if (typeof window.woocommerce_admin_meta_boxes !== 'undefined') {
            const postId = document.getElementById('post_ID');
            if (postId) return postId.value;
        }
        
        // URL parameter
        const urlParams = new URLSearchParams(window.location.search);
        let entityId = urlParams.get('post') || urlParams.get('tag_ID') || urlParams.get('cat_ID') || '';
        
        if (entityId) {
            return entityId;
        }
        
        // Try to get from current page context in On-Page Optimization
        if (window.location.href.includes('aysa-on-page-optimization')) {
            // Look for entity ID in the current context
            const currentRow = document.querySelector('.aysa-association-row.selected') || document.querySelector('.aysa-association-row');
            if (currentRow) {
                const dataEntityId = currentRow.getAttribute('data-entity-id');
                if (dataEntityId) {
                    return dataEntityId;
                }
            }
            
            // Try to get from global context
            if (typeof window.currentEntityId !== 'undefined') {
                return window.currentEntityId;
            }
        }
        
        return 'unknown';
    }
    
    /**
     * Get current entity type
     * @returns {string}
     * @private
     */
    _getEntityType() {
        if (this.options.entityType) {
            return this.options.entityType;
        }
        
        // Detect from current page
        if (typeof window.pagenow !== 'undefined') {
            if (window.pagenow === 'product') return 'Product';
            if (window.pagenow === 'edit-product_cat') return 'Category';
            if (window.pagenow === 'post') return 'Post';
            if (window.pagenow === 'page') return 'Page';
        }
        
        // Check URL patterns
        const url = window.location.href;
        if (url.includes('post_type=product')) return 'Product';
        if (url.includes('taxonomy=product_cat')) return 'Category';
        if (url.includes('post.php')) return 'Post';
        if (url.includes('page.php')) return 'Page';
        
        return 'Unknown';
    }
    
    /**
     * Get current entity name
     * @returns {string}
     * @private
     */
    _getEntityName() {
        if (this.options.entityName) {
            return this.options.entityName;
        }
        
        // Try to get title from various sources
        const titleField = document.getElementById('title') || 
                          document.querySelector('input[name="post_title"]') || 
                          document.querySelector('input[name="name"]');
        
        if (titleField && titleField.value) {
            return titleField.value;
        }
        
        // Fallback to page title
        return document.title.replace(' ‹ ', ' - ').split(' - ')[0] || 'Untitled';
    }
    
    /**
     * Get previous field values for comparison
     * @returns {Object}
     * @private
     */
    _getPreviousValues() {
        const previous = {};
        
        try {
            // Get values from common SEO fields
            const fields = {
                meta_title: ['_yoast_wpseo_title', 'meta_title', 'seo_title'],
                meta_description: ['_yoast_wpseo_metadesc', 'meta_description', 'seo_description'],
                meta_keywords: ['_yoast_wpseo_metakeywords', 'meta_keywords', 'seo_keywords'],
                product_title: ['post_title', 'title', 'name'],
                product_description: ['post_content', 'content', 'description']
            };
            
            Object.keys(fields).forEach(key => {
                for (const fieldName of fields[key]) {
                    const field = document.querySelector(`[name="${fieldName}"], #${fieldName}`);
                    if (field && field.value) {
                        previous[key] = field.value;
                        break;
                    }
                }
            });
            
        } catch (error) {
            console.warn('🚀 AysaSeoGenerator: Failed to get previous values:', error);
        }
        
        return previous;
    }
    
    _setGlobalKeyword() {
        // Set global keyword from associations for On-Page Optimization context
        if (typeof window.aysaAssociations !== 'undefined' && window.aysaAssociations.length > 0) {
            const firstAssociation = window.aysaAssociations[0];
            if (firstAssociation && (firstAssociation.keyword || firstAssociation.Keyword)) {
                const keyword = firstAssociation.keyword || firstAssociation.Keyword;
                window.currentKeyword = keyword;
                console.log('🚀 [DEBUG] Set global keyword from first association:', keyword);
            }
        }
    }
    
}

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