/**
 * AYSA Blog Content Generator JavaScript
 * Handles the generation of blog content through AJAX calls to the backend API
 */

var AysaBlogContent = {
    
    // Initialization flag
    initialized: false,
    
    // Configuration
    config: {
        currentStep: 0,
        totalSteps: 6,
        isGenerating: false,
        generatedData: {}
    },

    getApiBaseUrl: function() {
        if (window.AysaAPI && typeof window.AysaAPI.getConfig === 'function') {
            const cfg = window.AysaAPI.getConfig() || {};
            if (cfg.baseUrl) {
                return String(cfg.baseUrl).replace(/\/$/, '');
            }
        }

        if (typeof aysaParams !== 'undefined' && aysaParams.api_base_url) {
            return String(aysaParams.api_base_url).replace(/\/$/, '');
        }

        return 'https://api.aysa.ai';
    },

    buildApiUrl: function(path) {
        return `${this.getApiBaseUrl()}/${String(path).replace(/^\//, '')}`;
    },

    getAjaxUrl: function() {
        if (typeof aysaBlogContentAjax !== 'undefined' && aysaBlogContentAjax.ajax_url) {
            return aysaBlogContentAjax.ajax_url;
        }
        if (typeof aysa_ajax !== 'undefined' && aysa_ajax.ajax_url) {
            return aysa_ajax.ajax_url;
        }
        if (typeof aysaParams !== 'undefined' && aysaParams.ajax_url) {
            return aysaParams.ajax_url;
        }
        return '/wp-admin/admin-ajax.php';
    },

    getAjaxNonce: function() {
        if (typeof aysaBlogContentAjax !== 'undefined' && aysaBlogContentAjax.nonce) {
            return aysaBlogContentAjax.nonce;
        }
        if (typeof aysa_ajax !== 'undefined' && aysa_ajax.nonce) {
            return aysa_ajax.nonce;
        }
        if (typeof aysaParams !== 'undefined') {
            if (aysaParams.nonce) {
                return aysaParams.nonce;
            }
            if (aysaParams.ajax_nonce) {
                return aysaParams.ajax_nonce;
            }
            if (aysaParams.generic_nonce) {
                return aysaParams.generic_nonce;
            }
        }
        return '';
    },

    fetchLocalAssociationsForEntity: async function(postId, entityType, projectId) {
        const response = await fetch(this.getAjaxUrl(), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                'Accept': 'application/json'
            },
            body: new URLSearchParams({
                action: 'aysa_onpage_get_associations',
                nonce: this.getAjaxNonce(),
                project_id: String(projectId || '')
            }).toString(),
            credentials: 'same-origin'
        });

        if (!response.ok) {
            throw new Error('Local association response status: ' + response.status);
        }

        const payload = await response.json();
        const associations = payload && payload.success && payload.data && Array.isArray(payload.data.associations)
            ? payload.data.associations
            : [];
        const wantedId = parseInt(postId, 10);
        const wantedType = String(entityType || '').toLowerCase();

        return associations.filter((assoc) => {
            const assocId = parseInt(
                assoc.idIntern ?? assoc.IdIntern ?? assoc.entity_id ?? assoc.id_intern ?? 0,
                10
            );
            const assocType = String(
                assoc.AssociatedOn ?? assoc.associatedOn ?? assoc.entity_type ?? assoc.EntityType ?? ''
            ).toLowerCase();

            return assocId === wantedId && assocType === wantedType;
        });
    },

    fetchAssociationsForEntity: async function(postId, entityType, projectId) {
        const apiUrl = this.buildApiUrl(`api/Association/GetAllByAssociatedOnAndIdIntern?associatedOn=${encodeURIComponent(entityType)}&idIntern=${postId}&projectId=${projectId}`);

        try {
            const response = await fetch(apiUrl, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Origin': window.location.origin
                },
                mode: 'cors'
            });

            if (!response.ok) {
                throw new Error('API response status: ' + response.status);
            }

            return await response.json();
        } catch (error) {
            if (!String(error && error.message || '').includes('404')) {
                throw error;
            }

            console.log('Association endpoint unavailable, using local fallback for blog content.');
            return await this.fetchLocalAssociationsForEntity(postId, entityType, projectId);
        }
    },

    getBlogContentBaseUrl: function() {
        return this.getApiBaseUrl().replace(/\/api$/i, '');
    },
    
    // Step names
    steps: ['outline', 'intro', 'content', 'faq', 'conclusion', 'meta'],
    
    // Initialize the blog content functionality
    init: function() {
        // Check if required elements exist
        if (!jQuery('#aysa-generate-all-content').length) {
            console.error('AYSA Blog Content Generator: Generate button not found');
            return;
        }
        
        if (!jQuery('#aysa-article-topic').length) {
            console.error('AYSA Blog Content Generator: Article topic input not found');
            return;
        }
        
        this.bindEvents();
        this.overrideConflictFunctions();
        this.loadExistingContent();
        this.initialized = true;
    },
    
    // Override conflict functions to prevent dialogs in blog content
    overrideConflictFunctions: function() {
        console.log('🚫 Overriding conflict functions for blog content to prevent dialogs...');
        
        // Override global conflict functions to prevent dialogs
        const originalHandleKeywordConflictAndUpsert = window.handleKeywordConflictAndUpsert;
        const originalShowModernConfirmDialog = window.showModernConfirmDialog;
        const originalMakeUpsertCall = window.makeUpsertCall;
        
        // Store originals for restoration if needed
        this._originalConflictFunctions = {
            handleKeywordConflictAndUpsert: originalHandleKeywordConflictAndUpsert,
            showModernConfirmDialog: originalShowModernConfirmDialog,
            makeUpsertCall: originalMakeUpsertCall
        };
        
        // Override to always use ForceOverride=true and skip dialogs
        window.handleKeywordConflictAndUpsert = async function(apiUrl, associationData) {
            console.log('🚫 Blog Content: Bypassing conflict dialog, auto-accepting with ForceOverride=true');
            
            // Force override to true to skip conflicts
            associationData.ForceOverride = true;
            
            try {
                const response = await fetch(apiUrl, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'Origin': window.location.origin
                    },
                    body: JSON.stringify(associationData),
                    mode: 'cors'
                });
                
                console.log('🚫 Blog Content: Conflict-free upsert response:', response.status);
                return response;
                
            } catch (error) {
                console.error('🚫 Blog Content: Error in conflict-free upsert:', error);
                throw error;
            }
        };
        
        // Override to never show dialogs
        window.showModernConfirmDialog = async function(options) {
            console.log('🚫 Blog Content: Bypassing confirmation dialog, auto-accepting');
            return true; // Always confirm
        };
        
        console.log('🚫 Conflict functions overridden for blog content');
    },
    
    // Restore original conflict functions (if needed)
    restoreConflictFunctions: function() {
        if (this._originalConflictFunctions) {
            console.log('🔄 Restoring original conflict functions...');
            
            if (this._originalConflictFunctions.handleKeywordConflictAndUpsert) {
                window.handleKeywordConflictAndUpsert = this._originalConflictFunctions.handleKeywordConflictAndUpsert;
            }
            
            if (this._originalConflictFunctions.showModernConfirmDialog) {
                window.showModernConfirmDialog = this._originalConflictFunctions.showModernConfirmDialog;
            }
            
            if (this._originalConflictFunctions.makeUpsertCall) {
                window.makeUpsertCall = this._originalConflictFunctions.makeUpsertCall;
            }
            
            console.log('🔄 Original conflict functions restored');
        }
    },
    
    // Bind event listeners
    bindEvents: function() {
        const self = this;
        
        // Generate all content button
        jQuery('#aysa-generate-all-content').on('click', function(e) {
            e.preventDefault();
            self.generateAllContent();
        });
        
        // Generate step by step button
        jQuery('#aysa-generate-step-by-step').on('click', function(e) {
            e.preventDefault();
            self.generateStepByStep();
        });
        
        // Copy content button
        jQuery('#aysa-copy-content').on('click', function(e) {
            e.preventDefault();
            self.copyContentToClipboard();
        });
        
        // Regenerate content button
        jQuery('#aysa-regenerate-content').on('click', function(e) {
            e.preventDefault();
            self.regenerateContent();
        });
        
        // Auto-save content when inputs change
        jQuery('#aysa-article-topic, #aysa-primary-keyword, #aysa-local-specifics').on('blur', function() {
            self.autoSaveInputs();
        });
        
        // Sync primary keyword with hidden input only when needed (not on every input to avoid conflict dialogs)
        // This will be done programmatically during content generation instead
        
        // Initialize secondary keywords system
        this.initSecondaryKeywords();
        
        // Load existing keywords from API if this is an existing post
        const postId = (typeof aysaBlogContentAjax !== 'undefined' && aysaBlogContentAjax.post_id) ? 
                       aysaBlogContentAjax.post_id : 
                       (typeof aysaParams !== 'undefined' && aysaParams.postId) ? aysaParams.postId : 0;
        
        if (postId && postId > 0) {
            this.loadKeywordsFromApi();
        }
    },
    
    // Get language from SEO settings
    getLanguageFromSeoSettings: async function(projectId) {
        try {
            const settingsUrl = this.buildApiUrl(`api/SeoSettings/${projectId}`);
            const response = await fetch(settingsUrl, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Origin': window.location.origin
                },
                mode: 'cors'
            });
            
            if (response.ok) {
                const settings = await response.json();
                const language = settings.primaryLanguage || settings.languageOptimize;
                console.log('🌍 Got language from SEO settings:', language);
                
                // Convert full language names to language codes - Enhanced mapping for backend compatibility
                if (language) {
                    const languageMap = {
                        'Albanian': 'sq',
                        'Arabic': 'ar',
                        'Armenian': 'hy',
                        'Azeri': 'az',
                        'Bengali': 'bn',
                        'Bosnian': 'bs',
                        'Bulgarian': 'bg',
                        'Chinese (Traditional)': 'zh-TW',
                        'Chinese (Simplified)': 'zh-CN',
                        'Croatian': 'hr',
                        'Czech': 'cs',
                        'Danish': 'da',
                        'Dutch': 'nl',
                        'English': 'en',
                        'Estonian': 'et',
                        'Finnish': 'fi',
                        'French': 'fr',
                        'German': 'de',
                        'Greek': 'el',
                        'Hebrew': 'he',
                        'Hindi': 'hi',
                        'Hungarian': 'hu',
                        'Indonesian': 'id',
                        'Italian': 'it',
                        'Japanese': 'ja',
                        'Korean': 'ko',
                        'Latvian': 'lv',
                        'Lithuanian': 'lt',
                        'Macedonian': 'mk',
                        'Malay': 'ms',
                        'Norwegian (Bokmål)': 'nb',
                        'Polish': 'pl',
                        'Portuguese': 'pt',
                        'Romanian': 'ro',
                        'Russian': 'ru',
                        'Serbian': 'sr',
                        'Slovak': 'sk',
                        'Slovenian': 'sl',
                        'Spanish': 'es',
                        'Swedish': 'sv',
                        'Tagalog': 'tl',
                        'Thai': 'th',
                        'Turkish': 'tr',
                        'Ukrainian': 'uk',
                        'Urdu': 'ur',
                        'Vietnamese': 'vi'
                    };
                    return languageMap[language] || language.toLowerCase();
                }
            }
        } catch (error) {
            console.error('🌍 Error getting language from SEO settings:', error);
        }
        return null;
    },

    // Get language optimize value (consistent with other parts of the system)
    getLanguageOptimizeValue: function() {
        // Try to get from metabox Language Optimize field
        const languageOptimizeField = document.getElementById('language_optimize');
        if (languageOptimizeField && languageOptimizeField.value.trim()) {
            return languageOptimizeField.value.trim();
        }
        
        // Fallback to HTML lang attribute or browser language
        const htmlLang = document.documentElement.lang;
        if (htmlLang) return htmlLang.substring(0, 2);
        
        const browserLang = navigator.language || navigator.userLanguage;
        return browserLang ? browserLang.substring(0, 2) : 'en';
    },

    // Load existing content if available
    loadExistingContent: function() {
        const outlineContent = jQuery('#aysa-outline-content').val();
        if (outlineContent) {
            this.showGeneratedContent();
            this.updateProgress(100);
            this.markAllStepsCompleted();
        }
    },
    
    // Generate all content at once
    generateAllContent: function() {
        if (this.config.isGenerating) {
            return;
        }
        
        if (!this.validateInputs()) {
            return;
        }
        
        this.config.isGenerating = true;
        this.showLoading('Generating complete article content...');
        this.disableButtons();
        this.resetProgress();
        
        const formData = this.getFormData();
        const apiConfig = this.getApiConfig();
        
        // Call all endpoints in sequence
        this.generateCompleteContentDirect(formData, apiConfig);
    },
    
    // Generate content step by step
    generateStepByStep: function() {
        if (this.config.isGenerating) {
            return;
        }
        
        if (!this.validateInputs()) {
            return;
        }
        
        this.config.currentStep = 0;
        this.config.isGenerating = true;
        this.showLoading('Starting step-by-step generation...');
        this.disableButtons();
        this.resetProgress();
        
        this.generateNextStep();
    },
    
    // Generate next step in sequence
    generateNextStep: function() {
        if (this.config.currentStep >= this.config.totalSteps) {
            this.completeGeneration();
            return;
        }
        
        const stepName = this.steps[this.config.currentStep];
        const stepLabel = this.getStepLabel(stepName);
        
        this.updateLoadingText(`Generating ${stepLabel}...`);
        this.updateStepIndicator(stepName, 'active');
        
        const data = this.getFormData();
        const endpoint = this.getStepEndpoint(stepName);
        
        // Add specific data for certain steps
        if (stepName !== 'outline') {
            data.document_outline = this.config.generatedData.outline || jQuery('#aysa-outline-content').val();
        }
        
        if (stepName === 'intro') {
            data.title_h1 = this.extractH1FromOutline(data.document_outline);
        }
        
        const apiConfig = this.getApiConfig();
        
        // Call API directly
        this.callDirectApi(endpoint.replace('aysa_generate_', ''), data, apiConfig)
            .then(result => {
                this.handleStepSuccess(stepName, { success: true, data: result });
            })
            .catch(error => {
                this.handleStepError(stepName, error.message);
            });
    },
    
    // Handle successful step generation
    handleStepSuccess: function(stepName, response) {
        if (response.success) {
            this.config.generatedData[stepName] = response.data;
            this.updateStepContent(stepName, response.data);
            this.updateStepIndicator(stepName, 'completed');
            this.config.currentStep++;
            this.updateProgress((this.config.currentStep / this.config.totalSteps) * 100);
            
            // Continue to next step
            setTimeout(() => {
                this.generateNextStep();
            }, 1000);
        } else {
            this.handleStepError(stepName, response.data?.message || 'Generation failed');
        }
    },
    
    // Handle step generation error
    handleStepError: function(stepName, error) {
        console.error(`Error generating ${stepName}:`, error);
        this.updateStepIndicator(stepName, 'error');
        this.showError(`Failed to generate ${this.getStepLabel(stepName)}: ${error}`);
        this.completeGeneration();
    },
    
    // Handle successful complete generation
    handleGenerationSuccess: function(response) {
        if (response.success) {
            this.config.generatedData = response.data;
            this.populateAllContent(response.data);
            this.showGeneratedContent();
            this.updateProgress(100);
            this.markAllStepsCompleted();
            this.showSuccess('Blog content generated successfully!');
        } else {
            this.handleGenerationError(response.data?.message || 'Generation failed');
        }
    },
    
    // Handle generation error
    handleGenerationError: function(error) {
        console.error('Blog content generation error:', error);
        this.showError('Failed to generate blog content: ' + error);
    },
    
    // Get secondary keywords from keyword clustering API
    getSecondaryKeywords: async function(primaryKeyword, language, projectId) {
        try {
            const apiUrl = this.buildApiUrl('api/ChatGPT/keyword-clustering');
            const url = `${apiUrl}?primary_keyword=${encodeURIComponent(primaryKeyword)}&language=${encodeURIComponent(language)}&projectId=${encodeURIComponent(projectId)}`;
            
            console.log('Calling keyword clustering API:', url);
            
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });
            
            if (!response.ok) {
                console.warn('Keyword clustering API failed:', response.status);
                return [];
            }
            
            let data = await response.json();
            console.log('Keyword clustering raw response:', data);
            
            // If response is a string, parse it as JSON
            if (typeof data === 'string') {
                try {
                    data = JSON.parse(data);
                    console.log('Parsed keyword clustering data:', data);
                } catch (parseError) {
                    console.error('Failed to parse keyword clustering JSON:', parseError);
                    return [];
                }
            }
            
            if (!data || typeof data !== 'object') {
                console.warn('Invalid keyword clustering response format');
                return [];
            }
            
            // Extract keywords from all categories
            const allKeywords = [];
            const keywordTypes = ['short_tail_keywords', 'mid_tail_keywords', 'long_tail_keywords', 'related_keywords', 'lsi_keywords'];
            
            keywordTypes.forEach(type => {
                if (data[type] && Array.isArray(data[type])) {
                    data[type].forEach(keyword => {
                        if (typeof keyword === 'string' && keyword.trim()) {
                            allKeywords.push(keyword.trim());
                        }
                    });
                }
            });
            
            // Remove duplicates and filter out primary keyword
            const uniqueKeywords = [...new Set(allKeywords)];
            const filteredKeywords = uniqueKeywords.filter(keyword => 
                keyword.toLowerCase() !== primaryKeyword.toLowerCase()
            );
            
            console.log('Extracted secondary keywords:', filteredKeywords);
            return filteredKeywords;
            
        } catch (error) {
            console.error('Error getting secondary keywords:', error);
            return [];
        }
    },

    // Get related keywords from keyword-clustering-related API (NEW - specific for Posts)
    getRelatedKeywords: async function(primaryKeyword, language, projectId) {
        try {
            const apiUrl = this.buildApiUrl('api/ChatGPT/keyword-clustering-related');
            const url = `${apiUrl}?primary_keyword=${encodeURIComponent(primaryKeyword)}&language=${encodeURIComponent(language)}&projectId=${encodeURIComponent(projectId)}`;
            
            console.log('Calling keyword clustering related API:', url);
            
            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Origin': window.location.origin
                },
                mode: 'cors'
            });
            
            if (!response.ok) {
                console.warn('Keyword clustering related API failed:', response.status);
                return [];
            }
            
            let data = await response.json();
            console.log('Keyword clustering related raw response:', data);
            
            // Handle case where response might be a string containing JSON
            if (typeof data === 'string') {
                try {
                    data = JSON.parse(data);
                    console.log('Parsed keyword clustering related data:', data);
                } catch (parseError) {
                    console.error('Failed to parse keyword clustering related JSON:', parseError);
                    return [];
                }
            }
            
            if (!data || typeof data !== 'object') {
                console.warn('Invalid keyword clustering related response format');
                return [];
            }
            
            // Extract related keywords (the API should return related keywords specifically)
            let relatedKeywords = [];
            
            // Check for different possible response formats
            if (Array.isArray(data)) {
                relatedKeywords = data;
            } else if (data.related_keywords && Array.isArray(data.related_keywords)) {
                relatedKeywords = data.related_keywords;
            } else if (data.keywords && Array.isArray(data.keywords)) {
                relatedKeywords = data.keywords;
            } else {
                // Try to extract from any array property
                for (const key in data) {
                    if (Array.isArray(data[key])) {
                        data[key].forEach(keyword => {
                            if (typeof keyword === 'string' && keyword.trim()) {
                                relatedKeywords.push(keyword.trim());
                            }
                        });
                    }
                }
            }
            
            // Remove duplicates and filter out primary keyword
            const uniqueKeywords = [...new Set(relatedKeywords)];
            const filteredKeywords = uniqueKeywords.filter(keyword => 
                keyword && keyword.toLowerCase() !== primaryKeyword.toLowerCase()
            );
            
            console.log('Extracted related keywords:', filteredKeywords);
            return filteredKeywords;
            
        } catch (error) {
            console.error('Error getting related keywords:', error);
            return [];
        }
    },
    
    // Generate complete content with direct API calls
    generateCompleteContentDirect: async function(formData, apiConfig) {
        try {
            const results = {};
            
            // Step 0: Ensure main keyword is set and get secondary keywords from clustering
            this.updateLoadingText('Getting secondary keywords...');
            this.updateProgress(5);
            const primaryKeyword = formData.primary_keyword;
            const language = this.getLanguageOptimizeValue() || aysaBlogContentAjax.language || 'en';
            const projectId = aysaBlogContentAjax.project_id || 0;
            
            // ✅ CRITICAL: Sync main keyword silently to avoid conflict dialogs
            this.syncKeywordSilently(primaryKeyword);
            
            console.log('🔑 Blog Content Keywords Processing:');
            console.log('  - Primary keyword:', primaryKeyword);
            console.log('  - Language:', language);
            console.log('  - Project ID:', projectId);
            console.log('  - Will call 2 endpoints: keyword-clustering + keyword-clustering-related');
            
            const secondaryKeywords = await this.getSecondaryKeywords(primaryKeyword, language, projectId);
            console.log('Got secondary keywords from clustering:', secondaryKeywords);
            
            // Step 0.5: Get related keywords from the new endpoint (specific for Posts)
            this.updateLoadingText('Getting related keywords...');
            this.updateProgress(6);
            const relatedKeywords = await this.getRelatedKeywords(primaryKeyword, language, projectId);
            console.log('Got related keywords from clustering-related:', relatedKeywords);
            
            // Update secondary keywords field using the same logic as other entities
            if (secondaryKeywords && secondaryKeywords.length > 0) {
                await this.updateSecondaryKeywordsWithSmartLogic(secondaryKeywords, primaryKeyword);
            }
            
            // Prepare base data for all requests with keywords from both clustering endpoints
            this.updateLoadingText('Preparing enhanced data...');
            this.updateProgress(8);
            const baseData = await this.prepareApiData(formData, secondaryKeywords, relatedKeywords, projectId);
            console.log('Final payload with enhanced data and keywords:');
            console.log('  - Secondary keywords (from clustering):', baseData.SecondaryKeywords);
            console.log('  - Related keywords (from clustering-related):', baseData.RelatedKeywords);
            console.log('  - Full payload:', baseData);
            
            // Step 1: Generate document outline
            this.updateLoadingText('Generating document outline...');
            this.updateProgress(10);
            const outlineResult = await this.callDirectApi('35-document-outline', baseData, apiConfig);
            console.log('Outline result:', outlineResult);
            results.outline = outlineResult.outline || outlineResult.Outline || '';
            
            // Step 2: Generate TL;DR and introduction
            this.updateLoadingText('Generating TL;DR and introduction...');
            this.updateProgress(25);
            baseData.DocumentOutline = results.outline;
            baseData.TitleH1 = this.extractH1FromOutline(results.outline);
            const tldrResult = await this.callDirectApi('36-tldr-introduction', baseData, apiConfig);
            console.log('TL;DR result:', tldrResult);
            results.tldr_content = tldrResult.tldrContent || tldrResult.TldrContent || tldrResult.tldr_content || '';
            results.introduction_content = tldrResult.introductionContent || tldrResult.IntroductionContent || tldrResult.introduction_content || '';
            
            // Step 3: Generate extended content
            this.updateLoadingText('Generating extended content...');
            this.updateProgress(45);
            // Ensure DocumentOutline is set
            baseData.DocumentOutline = results.outline;
            const extendedResult = await this.callDirectApi('37-extended-content', baseData, apiConfig);
            console.log('Extended result:', extendedResult);
            results.extended_content = extendedResult.extendedContent || extendedResult.ExtendedContent || extendedResult.extended_content || '';
            
            // Step 4: Generate FAQ
            this.updateLoadingText('Generating FAQ section...');
            this.updateProgress(65);
            // Ensure DocumentOutline is set
            baseData.DocumentOutline = results.outline;
            const faqResult = await this.callDirectApi('38-faq-microdata', baseData, apiConfig);
            console.log('FAQ result:', faqResult);
            const rawFaqHtml = faqResult.faqHtml || faqResult.FaqHtml || faqResult.faq_html || '';
            results.faq_html = this.normalizeFaqHtml(rawFaqHtml);
            
            // Step 5: Generate conclusion
            this.updateLoadingText('Generating conclusion...');
            this.updateProgress(80);
            // Ensure DocumentOutline is set
            baseData.DocumentOutline = results.outline;
            const conclusionResult = await this.callDirectApi('39-conclusion-cta', baseData, apiConfig);
            console.log('Conclusion result:', conclusionResult);
            results.conclusion_content = conclusionResult.conclusionContent || conclusionResult.ConclusionContent || conclusionResult.conclusion_content || '';
            
            // Step 5.5: Generate featured image via api.aysa.ai broker
            this.updateLoadingText('Generating featured image...');
            this.updateProgress(90);
            const imageResult = await this.callBrokerImageApi(formData, baseData);
            console.log('Image generation result:', imageResult);
            results.featured_image_url = imageResult.imageUrl || imageResult.ImageUrl || imageResult.featured_image_url || '';
            
            // Step 6: Generate meta elements
            this.updateLoadingText('Generating meta elements...');
            this.updateProgress(95);
            const metaResult = await this.callDirectApi('41-meta-seo-elements', baseData, apiConfig);
            console.log('Meta result:', metaResult);
            results.meta_title = metaResult.metaTitle || metaResult.MetaTitle || metaResult.meta_title || '';
            results.meta_description = metaResult.metaDescription || metaResult.MetaDescription || metaResult.meta_description || '';
            
            // Process URL recomandat to extract only the slug part
            let rawUrl = metaResult.urlRecomandat || metaResult.UrlRecomandat || metaResult.url_recomandat || '';
            results.url_recomandat = this.extractSlugFromUrl(rawUrl);
            
            console.log('🔗 URL processing:', {
                raw: rawUrl,
                processed: results.url_recomandat
            });
            
            // Test URL extraction with some examples (for debugging)
            if (window.location.hostname === 'localhost' && rawUrl) {
                console.log('🧪 URL extraction test examples:');
                console.log('  http://localhost/florarie-victor → ', this.extractSlugFromUrl('http://localhost/florarie-victor'));
                console.log('  domain.com/florarie-bragadiru → ', this.extractSlugFromUrl('domain.com/florarie-bragadiru'));
                console.log('  florarie-simpla → ', this.extractSlugFromUrl('florarie-simpla'));
            }
            
            console.log('Final results object:', results);
            
            // Complete
            this.updateProgress(100);
            this.config.generatedData = results;
            this.insertContentIntoEditor(results);
            this.showGeneratedContent();
            this.showSuccess('Blog content generated!');
            
            // Save keywords and create associations after successful generation
            await this.saveKeywordsAndAssociations(formData, secondaryKeywords);
            
        } catch (error) {
            console.error('Blog content generation error:', error);
            this.showError('Failed to generate blog content: ' + error.message);
        } finally {
            this.config.isGenerating = false;
            this.hideLoading();
            this.enableButtons();
        }
    },

    callBrokerImageApi: function(formData, baseData) {
        return new Promise((resolve, reject) => {
            const nonce = jQuery('#aysa-blog-content-nonce').val();
            const postId = (typeof aysaBlogContentAjax !== 'undefined' ? aysaBlogContentAjax.post_id : jQuery('#post_ID').val()) || 0;
            if (!nonce || !postId) {
                reject(new Error('Missing nonce or post ID for image generation'));
                return;
            }

            const postAjax = function(data) {
                return jQuery.ajax({
                    url: aysaBlogContentAjax.ajaxurl,
                    type: 'POST',
                    dataType: 'json',
                    timeout: 120000,
                    data: data
                });
            };

            const pollAsync = function(runId, triesLeft) {
                const tries = typeof triesLeft === 'number' ? triesLeft : 40;
                return postAjax({
                    action: 'aysa_metabox_async_status',
                    nonce: nonce,
                    task: 'article_image',
                    run_id: runId || ''
                }).then(function(response) {
                    if (!response || !response.success || !response.data) {
                        throw new Error((response && response.data) ? String(response.data) : 'Image async status failed');
                    }
                    const status = response.data;
                    if (status.status === 'completed' && status.result) {
                        return status.result;
                    }
                    if (status.status === 'failed') {
                        throw new Error(String(status.error || 'Image worker failed'));
                    }
                    if (tries <= 0) {
                        throw new Error('Image worker timed out');
                    }
                    return new Promise(function(resolvePoll, rejectPoll) {
                        window.setTimeout(function() {
                            pollAsync(runId, tries - 1).then(resolvePoll).catch(rejectPoll);
                        }, 2000);
                    });
                });
            };

            postAjax({
                action: 'aysa_metabox_async_start',
                nonce: nonce,
                task: 'article_image',
                post_id: postId,
                article_topic: formData.article_topic || '',
                primary_keyword: formData.primary_keyword || '',
                secondary_keywords: (baseData.SecondaryKeywords || []).join(', '),
                language: baseData.Language || 'ro'
            }).then(function(response) {
                if (!response || !response.success || !response.data) {
                    throw new Error((response && response.data) ? String(response.data) : 'Image async start failed');
                }
                const started = response.data;
                if (started.status === 'completed' && started.result) {
                    return started.result;
                }
                return pollAsync(started.run_id || '', 40);
            }).then(function(result) {
                const imageUrl = result && result.image_url ? result.image_url : '';
                resolve({
                    imageUrl: imageUrl,
                    provider: (result && result.provider) || 'api.aysa.ai'
                });
            }).catch(function(error) {
                reject(error instanceof Error ? error : new Error(String(error || 'unknown error')));
            });
        });
    },

    // Complete the generation process
    completeGeneration: function() {
        this.config.isGenerating = false;
        this.hideLoading();
        this.enableButtons();
        this.showGeneratedContent();
        
        if (Object.keys(this.config.generatedData).length > 0) {
            this.showSuccess('Blog content generation completed!');
        }
    },
    
    // Update content for specific step
    updateStepContent: function(stepName, data) {
        switch (stepName) {
            case 'outline':
                jQuery('#aysa-outline-preview').html('<pre>' + this.escapeHtml(data.outline || '') + '</pre>');
                jQuery('#aysa-outline-content').val(data.outline || '');
                break;
                
            case 'intro':
                const introHtml = this.formatContent(data.tldr_content || '') + 
                                this.formatContent(data.introduction_content || '');
                jQuery('#aysa-intro-preview').html(introHtml);
                jQuery('#aysa-tldr-content').val(data.tldr_content || '');
                jQuery('#aysa-introduction-content').val(data.introduction_content || '');
                break;
                
            case 'content':
                jQuery('#aysa-content-preview').html(this.formatContent(data.extended_content || ''));
                jQuery('#aysa-extended-content').val(data.extended_content || '');
                break;
                
            case 'faq':
                const normalizedFaqHtml = this.normalizeFaqHtml(data.faq_html || '');
                jQuery('#aysa-faq-preview').html(normalizedFaqHtml);
                jQuery('#aysa-faq-content').val(normalizedFaqHtml);
                break;
                
            case 'conclusion':
                jQuery('#aysa-conclusion-preview').html(this.formatContent(data.conclusion_content || ''));
                jQuery('#aysa-conclusion-content').val(data.conclusion_content || '');
                break;
                
            case 'meta':
                jQuery('#aysa-generated-meta-title').val(data.meta_title || '');
                jQuery('#aysa-generated-meta-description').val(data.meta_description || '');
                jQuery('#aysa-generated-url').val(data.url_recomandat || '');
                break;
        }
    },
    
    // Populate all content sections
    populateAllContent: function(data) {
        // Outline
        if (data.outline) {
            this.updateStepContent('outline', {outline: data.outline});
        }
        
        // Introduction
        if (data.tldr_content || data.introduction_content) {
            this.updateStepContent('intro', {
                tldr_content: data.tldr_content,
                introduction_content: data.introduction_content
            });
        }
        
        // Extended content
        if (data.extended_content) {
            this.updateStepContent('content', {extended_content: data.extended_content});
        }
        
        // FAQ
        if (data.faq_html) {
            this.updateStepContent('faq', {faq_html: data.faq_html});
        }
        
        // Conclusion
        if (data.conclusion_content) {
            this.updateStepContent('conclusion', {conclusion_content: data.conclusion_content});
        }
        
        // Meta elements
        if (data.meta_title || data.meta_description || data.url_recomandat) {
            this.updateStepContent('meta', {
                meta_title: data.meta_title,
                meta_description: data.meta_description,
                url_recomandat: data.url_recomandat
            });
        }
    },
    
    // Copy generated content to WordPress editor
    copyContentToEditor: function() {
        const fullContent = this.assembleFullContent();
        
        if (!fullContent.trim()) {
            this.showError('No content available to copy');
            return;
        }
        
        // Try to insert into Gutenberg editor
        if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch) {
            try {
                const { dispatch } = wp.data;
                dispatch('core/editor').editPost({ content: fullContent });
                this.showSuccess('Content copied to editor successfully!');
                return;
            } catch (e) {
                console.log('Gutenberg not available, trying classic editor');
            }
        }
        
        // Try classic editor
        if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor) {
            tinyMCE.activeEditor.setContent(fullContent);
            this.showSuccess('Content copied to editor successfully!');
            return;
        }
        
        // Fallback to textarea
        const contentTextarea = jQuery('#content');
        if (contentTextarea.length) {
            contentTextarea.val(fullContent);
            this.showSuccess('Content copied to editor successfully!');
            return;
        }
        
        this.showError('Could not find editor to copy content to');
    },
    
    // Assemble full content from all sections
    assembleFullContent: function() {
        let content = '';
        
        // TL;DR
        const tldr = jQuery('#aysa-tldr-content').val();
        if (tldr) {
            content += tldr + '\n\n';
        }
        
        // Introduction
        const intro = jQuery('#aysa-introduction-content').val();
        if (intro) {
            content += intro + '\n\n';
        }
        
        // Extended content
        const extended = jQuery('#aysa-extended-content').val();
        if (extended) {
            content += extended + '\n\n';
        }
        
        // FAQ
        const faq = jQuery('#aysa-faq-content').val();
        if (faq) {
            content += faq + '\n\n';
        }
        
        // Conclusion
        const conclusion = jQuery('#aysa-conclusion-content').val();
        if (conclusion) {
            content += conclusion + '\n\n';
        }
        
        return content.trim();
    },
    
    // Regenerate all content
    regenerateContent: function() {
        if (confirm('Are you sure you want to regenerate all content? This will overwrite existing content.')) {
            this.clearGeneratedContent();
            this.hideGeneratedContent();
            this.generateAllContent();
        }
    },
    
    // Clear generated content
    clearGeneratedContent: function() {
        this.config.generatedData = {};
        jQuery('#aysa-generated-content textarea, #aysa-generated-content input').val('');
        jQuery('.aysa-content-preview').empty();
        this.resetProgress();
        this.resetStepIndicators();
    },
    
    // Validate required inputs
    validateInputs: function() {
        const topic = jQuery('#aysa-article-topic').val().trim();
        const keyword = jQuery('#aysa-primary-keyword').val().trim();
        
        if (!topic) {
            this.showError('Please enter an article topic');
            jQuery('#aysa-article-topic').focus();
            return false;
        }
        
        if (!keyword) {
            this.showError('Please enter a primary keyword');
            jQuery('#aysa-primary-keyword').focus();
            return false;
        }
        
        return true;
    },
    
    // Get API configuration for direct backend calls
    getApiConfig: function() {
        return {
            base_url: this.getBlogContentBaseUrl(),
            post_id: typeof aysaBlogContentAjax !== 'undefined' ? aysaBlogContentAjax.post_id : jQuery('#aysa-post-id').val()
        };
    },

    // Get form data
    getFormData: function() {
        return {
            article_topic: jQuery('#aysa-article-topic').val().trim(),
            primary_keyword: jQuery('#aysa-primary-keyword').val().trim(),
            local_specifics: jQuery('#aysa-local-specifics').val().trim()
        };
    },
    
    // Extract slug from URL - remove domain and path, keep only the slug part
    extractSlugFromUrl: function(url) {
        if (!url || typeof url !== 'string') {
            return '';
        }
        
        // If it's already a clean slug (no protocol), return as is
        if (!url.includes('://') && !url.includes('/')) {
            return url.trim();
        }
        
        try {
            // Remove protocol and domain, get only path
            let slug = url;
            
            // If it starts with http/https, parse the URL
            if (url.match(/^https?:\/\//)) {
                const urlObj = new URL(url);
                slug = urlObj.pathname;
            }
            
            // Remove leading/trailing slashes and get last segment
            slug = slug.replace(/^\/+|\/+$/g, '');
            
            // If there are multiple segments, get the last one
            const segments = slug.split('/');
            slug = segments[segments.length - 1];
            
            // Clean up any remaining unwanted characters
            slug = slug.replace(/[^a-zA-Z0-9\-_]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
            
            console.log('🔗 Slug extraction:', { original: url, final: slug });
            return slug;
        } catch (error) {
            console.error('Error extracting slug from URL:', error);
            // Fallback: just clean the original string
            return url.replace(/[^a-zA-Z0-9\-_]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
        }
    },
    
    // Get step endpoint action name
    getStepEndpoint: function(stepName) {
        const endpoints = {
            outline: 'aysa_generate_document_outline',
            intro: 'aysa_generate_tldr_introduction',
            content: 'aysa_generate_extended_content',
            faq: 'aysa_generate_faq_microdata',
            conclusion: 'aysa_generate_conclusion_cta',
            meta: 'aysa_generate_meta_seo_elements'
        };
        return endpoints[stepName];
    },
    
    // Get human-readable step label
    getStepLabel: function(stepName) {
        const labels = {
            outline: 'Document Outline',
            intro: 'TL;DR & Introduction',
            content: 'Extended Content',
            faq: 'FAQ Section',
            conclusion: 'Conclusion & CTA',
            meta: 'Meta Elements'
        };
        return labels[stepName];
    },
    
    // Extract H1 title from outline
    extractH1FromOutline: function(outline) {
        if (!outline) return '';
        
        const lines = outline.split('\n');
        for (let line of lines) {
            const trimmed = line.trim();
            if (trimmed.startsWith('H1') || trimmed.startsWith('#')) {
                return trimmed.replace(/^(H1:?|#+)\s*/, '').trim();
            }
        }
        return '';
    },
    
    // Format content for display
    formatContent: function(content) {
        if (!content) return '';
        
        // Convert line breaks to HTML
        return content.replace(/\n/g, '<br>');
    },

    // Normalize FAQ HTML to ensure FAQPage microdata is present
    normalizeFaqHtml: function(rawFaqHtml) {
        if (!rawFaqHtml || typeof rawFaqHtml !== 'string') {
            return '';
        }

        const faqHtml = rawFaqHtml.trim();
        if (!faqHtml) {
            return '';
        }

        // Already in microdata format
        if (/itemtype\s*=\s*["']https:\/\/schema\.org\/FAQPage["']/i.test(faqHtml)) {
            return faqHtml;
        }

        // Try JSON-LD FAQ -> convert to microdata HTML
        const jsonLdMatch = faqHtml.match(/<script[^>]*type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/i);
        if (jsonLdMatch && jsonLdMatch[1]) {
            try {
                const jsonLd = JSON.parse(jsonLdMatch[1]);
                const entities = Array.isArray(jsonLd.mainEntity) ? jsonLd.mainEntity : [];
                if (entities.length > 0) {
                    const pairs = entities
                        .map((entry) => {
                            const q = entry && entry.name ? String(entry.name).trim() : '';
                            const a = entry && entry.acceptedAnswer && entry.acceptedAnswer.text ? String(entry.acceptedAnswer.text).trim() : '';
                            return { question: q, answer: a };
                        })
                        .filter((pair) => pair.question && pair.answer);
                    if (pairs.length > 0) {
                        return this.buildFaqMicrodataFromPairs(pairs);
                    }
                }
            } catch (e) {
                console.warn('Could not parse FAQ JSON-LD, keeping original FAQ HTML.', e);
            }
        }

        // Try to extract Q/A pairs from plain FAQ HTML (h3 + next p)
        try {
            const wrapper = document.createElement('div');
            wrapper.innerHTML = faqHtml;
            const pairs = [];
            const questions = wrapper.querySelectorAll('h3, h4, strong');

            questions.forEach((qNode) => {
                const questionText = (qNode.textContent || '').trim();
                if (!questionText || questionText.length < 3) {
                    return;
                }

                let answerText = '';
                let next = qNode.nextElementSibling;
                while (next) {
                    const t = (next.textContent || '').trim();
                    if (t) {
                        answerText = t;
                        break;
                    }
                    next = next.nextElementSibling;
                }

                if (answerText) {
                    pairs.push({ question: questionText, answer: answerText });
                }
            });

            if (pairs.length > 0) {
                return this.buildFaqMicrodataFromPairs(pairs.slice(0, 8));
            }
        } catch (e) {
            console.warn('Could not normalize FAQ HTML into microdata.', e);
        }

        // Fallback: keep original response if parsing/conversion was not possible
        return faqHtml;
    },

    buildFaqMicrodataFromPairs: function(pairs) {
        if (!Array.isArray(pairs) || pairs.length === 0) {
            return '';
        }

        const title = 'Întrebări frecvente';
        const itemsHtml = pairs.map((pair) => {
            const question = this.escapeHtml(pair.question || '');
            const answer = this.escapeHtml(pair.answer || '');
            return `
  <div itemscope itemprop="mainEntity" itemtype="https://schema.org/Question">
    <h3 itemprop="name">${question}</h3>
    <div itemscope itemprop="acceptedAnswer" itemtype="https://schema.org/Answer">
      <p itemprop="text">${answer}</p>
    </div>
  </div>`;
        }).join('\n');

        return `<section itemscope itemtype="https://schema.org/FAQPage" class="aysa-faq">
  <h2>${title}</h2>
${itemsHtml}
</section>`;
    },
    
    // Escape HTML
    escapeHtml: function(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    },
    
    // Prepare data for API calls
    prepareApiData: async function(formData, secondaryKeywords = null, relatedKeywords = null, projectId = null) {
        // Get WordPress options data passed from PHP
        const wpData = typeof aysaBlogContentAjax !== 'undefined' ? aysaBlogContentAjax : {};
        
        // Get additional data from database like in other SEO suggestions
        let generalInfo = null;
        let toneOfVoice = '';
        
        try {
            generalInfo = await this.getGeneralInformation();
            toneOfVoice = await this.getToneOfVoice();
            console.log('📊 Blog content enhanced data:');
            console.log('  - General info:', generalInfo);
            console.log('  - Tone of voice:', toneOfVoice);
        } catch (error) {
            console.warn('Failed to get enhanced data, using fallback:', error);
        }
        
        // Build client info with brand name, phone and email
        let clientInfo = '';
        if (generalInfo?.brand) {
            clientInfo += generalInfo.brand;
        }
        if (wpData.phone_number) {
            clientInfo += (clientInfo ? ' ' : '') + wpData.phone_number;
        }
        if (wpData.email_address) {
            clientInfo += (clientInfo ? ' ' : '') + wpData.email_address;
        }
        
        return {
            ArticleTopic: formData.article_topic,
            BrandName: generalInfo?.brand || wpData.brand_name || 'Your Brand',
            ClientInfo: clientInfo || wpData.client_info || 'Client information',
            Domain: window.location.hostname,
            PublicationLocation: generalInfo?.businessName || wpData.publication_location || 'Website',
            Language: this.getLanguageOptimizeValue() || wpData.language || 'en',
            LocalSpecifics: formData.local_specifics,
            City: generalInfo?.city || wpData.city || 'Bucharest',
            TargetAudience: wpData.target_audience || 'general public',
            AudienceLevel: wpData.audience_level || '',
            TargetWordCount: '2000',
            PrimaryKeyword: formData.primary_keyword,
            SecondaryKeywords: secondaryKeywords || wpData.secondary_keywords || [],
            RelatedKeywords: relatedKeywords || wpData.related_keywords || [],
            Tone: toneOfVoice || wpData.tone || 'profesionist',
            WebsiteContext: wpData.website_context || 'Website context',
            PhoneNumber: generalInfo?.supportPhoneNumber || wpData.phone_number || '0123456789',
            EmailAddress: generalInfo?.supportEmailAddress || wpData.email_address || 'contact@example.com',
            ProjectId: wpData.project_id || 1
        };
    },

    // Call API directly
    callDirectApi: async function(endpoint, data, apiConfig) {
        const baseUrl = apiConfig && apiConfig.base_url
            ? String(apiConfig.base_url).replace(/\/$/, '').replace(/\/api$/i, '')
            : this.getBlogContentBaseUrl();
        const url = `${baseUrl}/blog-content/${endpoint}`;
        
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });

        if (!response.ok) {
            throw new Error(`API call failed: ${response.status} ${response.statusText}`);
        }

        const result = await response.json();
        return result;
    },

    // Insert generated content into WordPress editor
    insertContentIntoEditor: function(results) {
        // Build complete article content
        let fullContent = '';
        
        // Add TL;DR if available
        if (results.tldr_content) {
            fullContent += results.tldr_content + '\n\n';
        }
        
        // Add introduction if available
        if (results.introduction_content) {
            fullContent += results.introduction_content + '\n\n';
        }
        
        // Add extended content if available
        if (results.extended_content) {
            fullContent += results.extended_content + '\n\n';
        }
        
        // Add FAQ if available
        if (results.faq_html) {
            fullContent += results.faq_html + '\n\n';
        }
        
        // Add conclusion if available
        if (results.conclusion_content) {
            fullContent += results.conclusion_content + '\n\n';
        }
        
        // ✅ Add secondary keywords to WordPress Tags field (max 9)
        const secondaryKeywordsField = document.getElementById('aysa-entity-second-keyword');
        if (secondaryKeywordsField && secondaryKeywordsField.value.trim()) {
            const secondaryKeywords = secondaryKeywordsField.value.split(',')
                .map(k => k.trim())
                .filter(k => k !== '')
                .slice(0, 9); // Max 9 keywords
            
            if (secondaryKeywords.length > 0) {
                console.log('🏷️ Adding secondary keywords to WordPress Tags field:', secondaryKeywords);
                this.addKeywordsToWordPressTags(secondaryKeywords);
            }
        }
        
        // Extract H1 from content and set as post title, then remove H1 from content
        let extractedTitle = '';
        console.log('🔍 Looking for H1 in content. Content length:', fullContent.length);
        const h1Match = fullContent.match(/<h1[^>]*>(.*?)<\/h1>/i);
        if (h1Match) {
            extractedTitle = h1Match[1].trim();
            console.log('✅ Found H1 tag:', h1Match[0]);
            console.log('📝 Extracted title:', extractedTitle);
            
            // Remove the H1 tag from content
            const contentBeforeRemoval = fullContent.length;
            fullContent = fullContent.replace(/<h1[^>]*>.*?<\/h1>\s*/gi, '');
            console.log('🗑️ Removed H1 from content. Length before:', contentBeforeRemoval, 'after:', fullContent.length);
            console.log('📄 Content preview after H1 removal:', fullContent.substring(0, 300) + '...');
        } else {
            console.log('⚠️ No H1 tag found in content');
        }
        
        // Save full content to hidden textarea for copying
        console.log('Saving full content to textarea:', fullContent);
        jQuery('#aysa-generated-full-content').val(fullContent);
        
        // Get existing content and append new content
        let existingContent = '';
        
        // Insert content directly into WordPress editor
        if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch('core/editor')) {
            // Gutenberg editor - replace content completely
            try {
                const { dispatch } = wp.data;
                const postUpdate = { content: fullContent };
                
                // Set post title if H1 was extracted
                if (extractedTitle) {
                    postUpdate.title = extractedTitle;
                    console.log('Setting post title to:', extractedTitle);
                }
                
                dispatch('core/editor').editPost(postUpdate);
                console.log('Content set in Gutenberg editor');
            } catch (error) {
                console.log('Gutenberg failed, trying fallback:', error);
                this.insertViaFallback(fullContent, extractedTitle);
            }
        } else if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
            // Classic editor - replace content completely
            tinyMCE.get('content').setContent(fullContent);
            console.log('Content set in Classic editor');
            
            // Set title in classic editor
            if (extractedTitle) {
                const titleField = jQuery('#title, input[name="post_title"]');
                if (titleField.length) {
                    titleField.val(extractedTitle);
                    console.log('Title set in Classic editor:', extractedTitle);
                }
            }
        } else {
            // Fallback methods
            this.insertViaFallback(fullContent, extractedTitle);
        }
        
        // Also set meta title and description if available
        if (results.meta_title) {
            // Try to find and populate meta title field
            const metaTitleField = jQuery('#aysa-meta-title, input[name*="meta_title"], #yoast_wpseo_title');
            if (metaTitleField.length) {
                metaTitleField.val(results.meta_title);
                // Trigger character count update if function exists
                if (typeof updateMetaTitleCount === 'function') {
                    updateMetaTitleCount();
                }
            }
        }
        
        if (results.meta_description) {
            // Try to find and populate meta description field
            const metaDescField = jQuery('#aysa-meta-description, textarea[name*="meta_description"], #yoast_wpseo_metadesc');
            if (metaDescField.length) {
                metaDescField.val(results.meta_description);
                // Trigger character count update if function exists
                if (typeof updateMetaDescCount === 'function') {
                    updateMetaDescCount();
                }
            }
        }
        
        if (results.url_recomandat) {
            // Try to find and populate URL recomandat field
            const urlRecomandatField = jQuery('#aysa-url-recomandat, input[name*="url_recomandat"]');
            if (urlRecomandatField.length) {
                urlRecomandatField.val(results.url_recomandat);
            }
        }
        
        // Set featured image if generated
        if (results.featured_image_url) {
            this.setFeaturedImage(results.featured_image_url);
        }
    },

    // Fallback method to insert content using multiple approaches
    insertViaFallback: function(fullContent, extractedTitle = '') {
        console.log('Trying fallback content insertion methods');
        
        // Set title if provided
        if (extractedTitle) {
            const titleField = jQuery('#title, input[name="post_title"], .editor-post-title__input');
            if (titleField.length) {
                titleField.val(extractedTitle);
                console.log('Title set in fallback method:', extractedTitle);
            }
        }
        
        // Method 1: Direct textarea - set content completely
        if (jQuery('#content').length) {
            jQuery('#content').val(fullContent);
            console.log('Content set in textarea fallback');
            return;
        }
        
        // Method 2: Try to find Gutenberg content area
        const gutenbergContent = jQuery('.wp-block-post-content, .editor-post-text-editor, .block-editor-writing-flow');
        if (gutenbergContent.length) {
            console.log('Found Gutenberg content area, trying to insert');
            // This might not work perfectly but it's a fallback
        }
        
        // Method 3: Try iframe content (for some editors)
        const iframe = jQuery('iframe[id*="content"]');
        if (iframe.length) {
            try {
                const iframeDoc = iframe[0].contentDocument || iframe[0].contentWindow.document;
                const body = jQuery(iframeDoc.body);
                if (body.length) {
                    const existingContent = body.html();
                    const newContent = existingContent + '<br><br>' + fullContent.replace(/\n/g, '<br>');
                    body.html(newContent);
                    console.log('Content inserted via iframe fallback');
                    return;
                }
            } catch (e) {
                console.log('Iframe method failed:', e);
            }
        }
        
        console.log('All fallback methods failed');
        
        // As a last resort, save content to hidden textarea for manual copying
        jQuery('#aysa-generated-full-content').val(fullContent);
    },

    // Copy generated content to clipboard
    copyContentToClipboard: function() {
        const content = jQuery('#aysa-generated-full-content').val();
        console.log('Attempting to copy content:', content);
        console.log('Content length:', content ? content.length : 0);
        
        if (!content) {
            this.showError('No content to copy');
            return;
        }

        // Try to copy to clipboard
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(content).then(() => {
                this.showSuccess('Content copied to clipboard! You can now paste it in the editor.');
            }).catch(() => {
                this.fallbackCopyToClipboard(content);
            });
        } else {
            this.fallbackCopyToClipboard(content);
        }
    },

    // Fallback copy method
    fallbackCopyToClipboard: function(content) {
        const textarea = jQuery('#aysa-generated-full-content');
        textarea.show().select();
        
        try {
            document.execCommand('copy');
            this.showSuccess('Content copied to clipboard! You can now paste it in the editor.');
        } catch (err) {
            this.showError('Copy failed. Please manually copy the content from the text area below.');
            textarea.show();
        }
        
        setTimeout(() => textarea.hide(), 3000);
    },

    // Auto-save inputs
    autoSaveInputs: function() {
        // This could save to localStorage or send AJAX request
        console.log('Auto-saving inputs...');
    },
    
    // UI Helper Methods
    showLoading: function(text) {
        jQuery('#aysa-loading-text').text(text || 'Generating content...');
        jQuery('#aysa-loading').addClass('active');
        jQuery('#aysa-generate-all-content .aysa-spinner').show();
    },
    
    hideLoading: function() {
        jQuery('#aysa-loading').removeClass('active');
        jQuery('#aysa-generate-all-content .aysa-spinner').hide();
    },
    
    updateLoadingText: function(text) {
        jQuery('#aysa-loading-text').text(text);
    },
    
    showGeneratedContent: function() {
        jQuery('#aysa-generated-content').show();
    },
    
    disableButtons: function() {
        jQuery('#aysa-generate-all-content, #aysa-generate-step-by-step, #aysa-regenerate-content').prop('disabled', true);
    },
    
    enableButtons: function() {
        jQuery('#aysa-generate-all-content, #aysa-generate-step-by-step, #aysa-regenerate-content').prop('disabled', false);
    },
    
    updateProgress: function(percentage) {
        jQuery('#aysa-progress-fill').css('width', percentage + '%');
    },
    
    resetProgress: function() {
        this.updateProgress(0);
    },
    
    updateStepIndicator: function(stepName, status) {
        const step = jQuery(`.aysa-step[data-step="${stepName}"]`);
        step.removeClass('active completed error').addClass(status);
    },
    
    resetStepIndicators: function() {
        jQuery('.aysa-step').removeClass('active completed error');
    },
    
    markAllStepsCompleted: function() {
        jQuery('.aysa-step').removeClass('active error').addClass('completed');
    },
    
    // Get general information from database
    getGeneralInformation: async function() {
        try {
            const projectId = aysaBlogContentAjax.project_id || 0;
            if (!projectId) {
                console.warn('No project ID found for general information');
                return null;
            }

            // Use AysaAPI to get the correct endpoint URL (including localhost routing)
            const url = AysaAPI.getEndpointUrl('general_information_by_project', { projectId: projectId });
            console.log('🏢 Fetching general information:', url);

            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Origin': window.location.origin
                },
                mode: 'cors'
            });

            if (response.ok) {
                const data = await response.json();
                console.log('✅ General information received:', data);
                return data;
            } else {
                console.warn('⚠️ Failed to fetch general information:', response.status);
                return null;
            }
        } catch (error) {
            console.warn('⚠️ Error fetching general information:', error);
            return null;
        }
    },
    
    // Get tone of voice from database
    getToneOfVoice: async function() {
        try {
            const projectId = aysaBlogContentAjax.project_id || 0;
            if (!projectId) {
                console.warn('No project ID found for tone of voice');
                return '';
            }

            const url = this.buildApiUrl(`api/ToneOfVoice/ByProject/${projectId}`);
            console.log('🎵 Fetching tone of voice:', url);

            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Origin': window.location.origin
                },
                mode: 'cors'
            });

            if (response.ok) {
                const data = await response.json();
                console.log('✅ Tone of voice received:', data);
                return data.tone || data.Tone || '';
            } else {
                console.warn('⚠️ Failed to fetch tone of voice:', response.status);
                return '';
            }
        } catch (error) {
            console.warn('⚠️ Error fetching tone of voice:', error);
            return '';
        }
    },
    
    // Set featured image from URL
    setFeaturedImage: function(imageUrl) {
        if (!imageUrl) {
            console.warn('No image URL provided for featured image');
            return;
        }
        
        console.log('Setting featured image from URL:', imageUrl);
        
        // Make AJAX call to WordPress backend to download and set featured image
        jQuery.ajax({
            url: aysaBlogContentAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_set_featured_image',
                nonce: aysaBlogContentAjax.nonce,
                post_id: aysaBlogContentAjax.post_id,
                image_url: imageUrl
            },
            success: function(response) {
                console.log('Featured image response:', response);
                
                if (response.success) {
                    console.log('✅ Featured image set successfully');
                    
                    // Try to update the WordPress featured image UI
                    if (response.data && response.data.thumbnail_html) {
                        // Update the featured image container if it exists
                        const featuredImageContainer = jQuery('#postimagediv .inside');
                        if (featuredImageContainer.length) {
                            featuredImageContainer.html(response.data.thumbnail_html);
                        }
                    }
                    
                    // Show success message
                    AysaBlogContent.showNotice('✅ Featured image set successfully!', 'success');
                } else {
                    console.error('Failed to set featured image:', response.data);
                    AysaBlogContent.showNotice('❌ Failed to set featured image: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error setting featured image:', error);
                AysaBlogContent.showNotice('❌ Error setting featured image: ' + error, 'error');
            }
        });
    },
    
    // Save keywords and create associations
    saveKeywordsAndAssociations: async function(formData, secondaryKeywords) {
        console.log('💾 Saving keywords and creating associations...');
        
        if (!aysaBlogContentAjax || !aysaBlogContentAjax.post_id) {
            console.error('Missing AJAX configuration or post ID');
            return;
        }
        
        const postId = aysaBlogContentAjax.post_id;
        const primaryKeyword = formData.primary_keyword || '';
        
        // Ensure keyword is synced silently before saving
        this.syncKeywordSilently(primaryKeyword);
        
        const secondaryKeywordsField = document.getElementById('aysa-entity-second-keyword');
        const allSecondaryKeywords = secondaryKeywordsField ? secondaryKeywordsField.value : '';
        
        console.log('Keywords to save:', {
            postId,
            primaryKeyword,
            allSecondaryKeywords,
            generatedSecondaryKeywords: secondaryKeywords
        });
        
        // 1. Save to WordPress via AJAX (similar to other metaboxes)
        try {
            const saveData = {
                action: 'aysa_save_seo_data',
                entity_id: postId,
                entity_type: 'Post', // Correct entity type
                keyword: primaryKeyword,
                second_keyword: allSecondaryKeywords,
                aysa_keyword: primaryKeyword, // Also send new format
                aysa_secondary_keywords: allSecondaryKeywords, // Also send new format
                meta_title: document.getElementById('aysa-meta-title')?.value || '',
                meta_description: document.getElementById('aysa-meta-description')?.value || '',
                meta_keywords: '',
                url_recomandat: document.getElementById('aysa-url-recomandat')?.value || '',
                nonce: aysaBlogContentAjax.nonce
            };
            
            const saveResponse = await fetch(aysaBlogContentAjax.ajax_url, {
                method: 'POST',
                body: new URLSearchParams(saveData),
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            });
            
            const saveResult = await saveResponse.json();
            console.log('WordPress save result:', saveResult);
            if (!saveResult || !saveResult.success) {
                const saveError = (saveResult && saveResult.data && (saveResult.data.message || saveResult.data)) || 'Unknown save error';
                this.showNotice('SEO data was generated but not fully saved: ' + saveError, 'warning');
            }
            
            // 2. MAIN KEYWORD UPSERT with IsMain=true (like categories/products)
            if (primaryKeyword) {
                console.log('Creating API associations...');
                
                // Get project ID
                const projectId = aysaBlogContentAjax.project_id || 0;
                
                if (projectId) {
                    // First, upsert main keyword with IsMain=true
                    await this.upsertMainKeyword(postId, primaryKeyword, projectId);
                    
                    // Then, process secondary keywords
                    const secondaryKeywordsArray = allSecondaryKeywords ? 
                        allSecondaryKeywords.split(',').map(k => k.trim()).filter(k => k !== '') : [];
                    
                    if (secondaryKeywordsArray.length > 0 && typeof window.processSecondaryKeywordsAfterUpsert === 'function') {
                        // Prepare main association data
                        const post = document.getElementById('title') || document.querySelector('#post-title-0');
                        const postTitle = post ? post.value || post.textContent : 'Blog Post';
                        const postLink = window.location.href; // Current post URL
                        
                        const mainAssociationData = {
                            value: postTitle,
                            link: postLink,
                            metaTitle: document.getElementById('aysa-meta-title')?.value || '',
                            metaDescription: document.getElementById('aysa-meta-description')?.value || '',
                            metaKeywords: '',
                            // Add missing fields that secondary keywords might need
                            targetedSearchEngine: '',
                            targetedCountry: '',
                            targetedRegion: '',
                            targetedCity: '',
                            updateFrequency: '',
                            languageOptimize: this.getLanguageOptimizeValue() || 'en',
                            deviceOptimize: '',
                            index: true,
                            noFollow: false,
                            noArchive: false,
                            noImageIndex: false,
                            noSnippet: false,
                            maxSnippet: -1,
                            maxVideoPreview: -1,
                            maxImagePreview: 'large',
                            canonicalUrl: ''
                        };
                        
                        await window.processSecondaryKeywordsAfterUpsert(postId, 'Post', projectId, secondaryKeywordsArray, mainAssociationData);
                        console.log('API associations created successfully');
                    } else {
                        console.log('No secondary keywords to create associations for');
                    }
                } else {
                    console.log('Skipping API associations - missing project ID');
                }
            } else {
                console.log('Skipping API associations - missing primary keyword');
            }
            
        } catch (error) {
            console.error('Error saving keywords and associations:', error);
        }
    },
    
    // Upsert main keyword with IsMain=true (like categories/products)
    upsertMainKeyword: async function(postId, primaryKeyword, projectId) {
        console.log('🔑 UPSERTING MAIN KEYWORD with IsMain=true:', primaryKeyword);
        
        try {
            // First, get existing associations to find main association ID
            const getUrl = this.buildApiUrl(`api/Association/GetAllByAssociatedOnAndIdIntern?associatedOn=Post&idIntern=${postId}&projectId=${projectId}`);
            
            let mainAssociationId = null;
            try {
                const getResponse = await fetch(getUrl, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json',
                        'Origin': window.location.origin
                    },
                    mode: 'cors'
                });
                
                if (getResponse.ok) {
                    const existingAssociations = await getResponse.json();
                    if (Array.isArray(existingAssociations)) {
                        const mainAssociation = existingAssociations.find(a => a.isMain === true);
                        if (mainAssociation) {
                            mainAssociationId = mainAssociation.id;
                            console.log('🔑 Found existing main association ID:', mainAssociationId);
                        }
                    }
                }
            } catch (error) {
                console.log('🔑 Could not fetch existing associations:', error);
            }
            
            // Prepare main keyword association data
            const post = document.getElementById('title') || document.querySelector('#post-title-0');
            const postTitle = post ? post.value || post.textContent : 'Blog Post';
            const postUrl = window.location.href; // Current post URL
            
            const mainAssociationData = {
                Id: mainAssociationId || 0, // 0 for new, existing ID for update
                IdIntern: postId,
                AssociatedOn: 'Post',
                Value: postTitle,
                Link: postUrl,
                Keyword: primaryKeyword,
                ProjectId: projectId,
                IsMain: true, // ✅ CRITICAL: Set as main keyword
                IsTracked: true, // Main keyword is always tracked
                ForceOverride: true, // Allow keyword conflicts
                
                // SEO fields
                MetaTitle: document.getElementById('aysa-meta-title')?.value || '',
                MetaDescription: document.getElementById('aysa-meta-description')?.value || '',
                MetaKeywords: '',
                
                // Additional fields that backend expects
                SecondKeyword: '', // Will be handled separately
                TargetedSearchEngine: '',
                TargetedCountry: '',
                TargetedRegion: '',
                TargetedCity: '',
                UpdateFrequency: '',
                LanguageOptimize: 'ro',
                DeviceOptimize: '',
                Index: true,
                NoFollow: false,
                NoArchive: false,
                NoImageIndex: false,
                NoSnippet: false,
                MaxSnippet: -1,
                MaxVideoPreview: -1,
                MaxImagePreview: 'large',
                CanonicalUrl: ''
            };
            
            console.log('🔑 Main keyword association data:', mainAssociationData);
            
            // Make upsert API call
            const upsertUrl = this.buildApiUrl('api/Association/upsert');
            
            const upsertResponse = await fetch(upsertUrl, {
                method: 'PUT', // ✅ Backend uses PUT for upsert
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'Origin': window.location.origin
                },
                mode: 'cors',
                body: JSON.stringify(mainAssociationData)
            });
            
            if (upsertResponse.ok) {
                const result = await upsertResponse.json();
                console.log('✅ Main keyword upserted successfully:', result);
                return result;
            } else {
                const errorText = await upsertResponse.text();
                console.error('❌ Failed to upsert main keyword:', upsertResponse.status, errorText);
                throw new Error(`Failed to upsert main keyword: ${upsertResponse.status} - ${errorText}`);
            }
            
        } catch (error) {
            console.error('❌ Error upserting main keyword:', error);
            throw error;
        }
    },
    
    showSuccess: function(message) {
        this.showNotice(message, 'success');
    },
    
    showError: function(message) {
        this.showNotice(message, 'error');
    },
    
    showNotice: function(message, type) {
        // Create notice element
        const notice = jQuery(`
            <div class="aysa-notice aysa-notice-${type}" style="
                position: fixed;
                top: 32px;
                right: 20px;
                background: ${type === 'success' ? '#d4edda' : '#f8d7da'};
                color: ${type === 'success' ? '#155724' : '#721c24'};
                border: 1px solid ${type === 'success' ? '#c3e6cb' : '#f5c6cb'};
                padding: 12px 16px;
                border-radius: 4px;
                z-index: 10000;
                max-width: 400px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            ">
                ${message}
            </div>
        `);
        
        jQuery('body').append(notice);
        
        // Auto-hide after 5 seconds
        setTimeout(() => {
            notice.fadeOut(() => notice.remove());
        }, 5000);
        
        // Allow manual close
        notice.on('click', () => {
            notice.fadeOut(() => notice.remove());
        });
    },
    
    // Add keywords to WordPress Tags field (both Classic and Gutenberg editors)
    addKeywordsToWordPressTags: function(keywords) {
        console.log('🏷️ Starting to add keywords to WordPress Tags field:', keywords);
        
        try {
            // Detect which editor we're using
            const isGutenberg = typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor');
            const isClassic = document.getElementById('new-tag-post_tag');
            
            console.log('🔍 Editor detection:', { isGutenberg, isClassic });
            
            if (isGutenberg) {
                console.log('🏷️ Using Gutenberg editor method');
                this.addTagsToGutenberg(keywords);
            } else if (isClassic) {
                console.log('🏷️ Using Classic editor method');
                this.addTagsToClassic(keywords);
            } else {
                console.warn('🏷️ No supported editor detected, retrying in 1 second...');
                setTimeout(() => {
                    this.addKeywordsToWordPressTags(keywords);
                }, 1000);
            }
            
        } catch (error) {
            console.error('🏷️ Error in addKeywordsToWordPressTags:', error);
        }
    },
    
    // Add tags to Classic Editor
    addTagsToClassic: function(keywords) {
        console.log('🏷️ Adding tags to Classic Editor:', keywords);
        
        const tagsInput = document.getElementById('new-tag-post_tag');
        const addButton = document.querySelector('#tagsdiv-post_tag .tagadd');
        const tagsContainer = document.getElementById('tagchecklist');
        
        if (!tagsInput || !addButton) {
            console.error('🏷️ Classic editor elements not found');
            return;
        }
        
        // Clear existing tags first - multiple methods
        if (tagsContainer) {
            const deleteButtons = tagsContainer.querySelectorAll('.ntdelbutton');
            console.log(`🏷️ Clearing ${deleteButtons.length} existing tags...`);
            
            // Method 1: Click delete buttons
            deleteButtons.forEach((button, index) => {
                setTimeout(() => {
                    button.click();
                    console.log(`🏷️ Deleted tag ${index + 1}/${deleteButtons.length}`);
                }, index * 100);
            });
            
            // Method 2: Clear hidden input if available
            setTimeout(() => {
                const hiddenTagsInput = document.getElementById('tax-input-post_tag');
                if (hiddenTagsInput) {
                    hiddenTagsInput.value = '';
                    console.log('🏷️ Cleared hidden tags input');
                }
                
                // Method 3: Use WordPress tagBox clear if available
                if (typeof tagBox !== 'undefined' && tagBox.parseTags) {
                    const tagDiv = document.getElementById('tagsdiv-post_tag');
                    if (tagDiv) {
                        // Clear the display
                        const tagsList = tagDiv.querySelector('.tagchecklist');
                        if (tagsList) {
                            tagsList.innerHTML = '';
                        }
                    }
                }
            }, deleteButtons.length * 100 + 200);
        }
        
        // Add new tags one by one - with proper delay after clearing
        const startDelay = tagsContainer ? (tagsContainer.querySelectorAll('.ntdelbutton').length * 100 + 500) : 200;
        
        setTimeout(() => {
            let currentIndex = 0;
            const addNextTag = () => {
                if (currentIndex >= keywords.length) {
                    console.log('🏷️ ✅ All tags added successfully!');
                    return;
                }
                
                const keyword = keywords[currentIndex];
                console.log(`🏷️ Adding tag ${currentIndex + 1}/${keywords.length}: "${keyword}"`);
                
                // Set input value and add tag
                tagsInput.value = keyword.trim();
                tagsInput.focus();
            
            // Try multiple methods to ensure tag is added
            setTimeout(() => {
                // Method 1: Use WordPress tagBox if available
                if (typeof tagBox !== 'undefined' && tagBox.flushTags) {
                    const tagDiv = document.getElementById('tagsdiv-post_tag');
                    tagBox.flushTags(tagDiv, false);
                }
                
                // Method 2: Click add button
                addButton.click();
                
                // Method 3: Simulate Enter key
                const enterEvent = new KeyboardEvent('keypress', {
                    key: 'Enter',
                    keyCode: 13,
                    which: 13,
                    bubbles: true
                });
                tagsInput.dispatchEvent(enterEvent);
                
                currentIndex++;
                
                // Wait before adding next tag
                setTimeout(addNextTag, 500);
            }, 100);
            };
            
            addNextTag();
        }, startDelay);
    },
    
    // Add tags to Gutenberg Editor
    addTagsToGutenberg: async function(keywords) {
        console.log('🏷️ Adding tags to Gutenberg Editor:', keywords);
        
        try {
            // Wait for WordPress to be ready
            if (typeof wp === 'undefined' || !wp.data) {
                console.warn('🏷️ WordPress not ready, retrying...');
                setTimeout(() => {
                    this.addTagsToGutenberg(keywords);
                }, 1000);
                return;
            }
            
            const { select, dispatch } = wp.data;
            
            // Get current post
            const currentPost = select('core/editor').getCurrentPost();
            if (!currentPost) {
                console.warn('🏷️ No current post found, retrying...');
                setTimeout(() => {
                    this.addTagsToGutenberg(keywords);
                }, 500);
                return;
            }
            
            console.log('🏷️ Current post ID:', currentPost.id);
            console.log('🏷️ Current post tags before clearing:', currentPost.tags);
            
            // FORCE clear existing tags first - multiple attempts to ensure it works
            console.log('🏷️ 🗑️ FORCE clearing ALL existing tags...');
            
            // Method 1: Clear via editPost
            await dispatch('core/editor').editPost({ tags: [] });
            await new Promise(resolve => setTimeout(resolve, 500));
            
            // Method 2: If tags still exist, force clear again
            let postAfterClear = select('core/editor').getCurrentPost();
            console.log('🏷️ Post tags after first clear attempt:', postAfterClear.tags);
            
            if (postAfterClear.tags && postAfterClear.tags.length > 0) {
                console.log('🏷️ 🔄 Tags still exist, forcing second clear...');
                
                // Try to remove tags one by one if bulk clear failed
                const currentTags = [...postAfterClear.tags];
                for (const tagId of currentTags) {
                    try {
                        const remainingTags = postAfterClear.tags.filter(id => id !== tagId);
                        await dispatch('core/editor').editPost({ tags: remainingTags });
                        await new Promise(resolve => setTimeout(resolve, 100));
                        postAfterClear = select('core/editor').getCurrentPost();
                        console.log(`🏷️ Removed tag ${tagId}, remaining:`, postAfterClear.tags);
                    } catch (error) {
                        console.error(`🏷️ Failed to remove tag ${tagId}:`, error);
                    }
                }
                
                // Final attempt with empty array
                await dispatch('core/editor').editPost({ tags: [] });
                await new Promise(resolve => setTimeout(resolve, 300));
            }
            
            // Final verification
            const finalClearPost = select('core/editor').getCurrentPost();
            console.log('🏷️ Final post tags after clearing:', finalClearPost.tags);
            
            if (finalClearPost.tags && finalClearPost.tags.length > 0) {
                console.warn('🏷️ ⚠️ WARNING: Could not clear all existing tags:', finalClearPost.tags);
            } else {
                console.log('🏷️ ✅ All existing tags successfully cleared');
            }
            
            // Force refresh available tags to get the most current list
            console.log('🏷️ Refreshing available tags...');
            
            // Invalidate cache first to ensure fresh data
            await dispatch('core').invalidateResolutionForStoreSelector('getEntityRecords', ['taxonomy', 'post_tag']);
            
            // Get fresh tags
            let allTags = [];
            try {
                const allTagsResponse = await wp.data.resolveSelect('core').getEntityRecords('taxonomy', 'post_tag', { 
                    per_page: -1,
                    _fields: 'id,name,slug'
                });
                allTags = allTagsResponse || [];
                console.log('🏷️ Available tags in WordPress:', allTags.length);
                
                // Pre-search for each keyword to ensure we have all relevant tags
                for (const keyword of keywords) {
                    try {
                        const searchResults = await wp.data.resolveSelect('core').getEntityRecords('taxonomy', 'post_tag', {
                            search: keyword.trim(),
                            per_page: 10,
                            _fields: 'id,name,slug'
                        });
                        
                        if (searchResults && searchResults.length > 0) {
                            // Add any found tags that aren't already in our list
                            for (const foundTag of searchResults) {
                                if (!allTags.find(t => t.id === foundTag.id)) {
                                    allTags.push(foundTag);
                                    console.log(`🏷️ 🔍 Found additional tag via search: "${foundTag.name}" (ID: ${foundTag.id})`);
                                }
                            }
                        }
                    } catch (searchError) {
                        console.warn(`🏷️ Search failed for "${keyword}":`, searchError);
                    }
                }
                
                console.log('🏷️ Total tags after search enhancement:', allTags.length);
            } catch (error) {
                console.error('🏷️ Failed to refresh tags:', error);
                // Fallback to cached data
                allTags = select('core').getEntityRecords('taxonomy', 'post_tag', { 
                    per_page: -1,
                    _fields: 'id,name,slug'
                }) || [];
            }
            
            const tagIds = [];
            
            // Process each keyword
            for (let i = 0; i < keywords.length; i++) {
                const keyword = keywords[i];
                console.log(`🏷️ [${i + 1}/${keywords.length}] Processing: "${keyword}"`);
                
                // Check if tag exists (case-insensitive, multiple checks)
                let existingTag = null;
                
                // Method 1: Exact name match
                existingTag = allTags.find(tag => 
                    tag.name && keyword && 
                    tag.name.toLowerCase().trim() === keyword.toLowerCase().trim()
                );
                
                // Method 2: If not found, try slug match
                if (!existingTag) {
                    const keywordSlug = keyword.toLowerCase()
                        .replace(/\s+/g, '-')
                        .replace(/[^a-z0-9-]/g, '')
                        .replace(/-+/g, '-')
                        .replace(/^-|-$/g, '');
                    
                    existingTag = allTags.find(tag => 
                        tag.slug && keywordSlug && 
                        tag.slug.toLowerCase() === keywordSlug
                    );
                    
                    if (existingTag) {
                        console.log(`🏷️ 🔍 Found tag via slug match: "${keyword}" -> "${existingTag.name}" (ID: ${existingTag.id})`);
                    }
                }
                
                if (existingTag) {
                    tagIds.push(existingTag.id);
                    console.log(`🏷️ ✅ Using existing tag: "${keyword}" (ID: ${existingTag.id})`);
                } else {
                    // Try to create new tag
                    try {
                        console.log(`🏷️ 🆕 Creating new tag: "${keyword}"`);
                        
                        const slug = keyword.toLowerCase()
                            .replace(/\s+/g, '-')           // Replace spaces with hyphens
                            .replace(/[^a-z0-9-]/g, '')     // Remove special characters
                            .replace(/-+/g, '-')            // Replace multiple hyphens with single
                            .replace(/^-|-$/g, '');         // Remove leading/trailing hyphens
                        
                        const newTag = await dispatch('core').saveEntityRecord('taxonomy', 'post_tag', {
                            name: keyword.trim(),
                            slug: slug || `tag-${Date.now()}-${i}` // Fallback slug if empty
                        });
                        
                        if (newTag && newTag.id) {
                            tagIds.push(newTag.id);
                            console.log(`🏷️ ✅ Created new tag: "${keyword}" (ID: ${newTag.id})`);
                            
                            // Add to our local cache to avoid duplicate creation attempts
                            allTags.push(newTag);
                        } else {
                            console.error(`🏷️ ❌ Failed to create tag: "${keyword}" - no ID returned`);
                        }
                        
                    } catch (error) {
                        console.error(`🏷️ ❌ Error creating tag: "${keyword}"`, error);
                        console.error('🏷️ Full error object:', JSON.stringify(error, null, 2));
                        
                        // Handle term_exists error specifically
                        if (error.code === 'term_exists') {
                            let termId = null;
                            
                            // Try multiple ways to get the term ID
                            if (error.data && error.data.term_id) {
                                termId = error.data.term_id;
                                console.log(`🏷️ Got term ID from error.data.term_id: ${termId}`);
                            } else if (error.additional_data && error.additional_data[0]) {
                                termId = error.additional_data[0];
                                console.log(`🏷️ Got term ID from error.additional_data[0]: ${termId}`);
                            } else if (error.additional_data && error.additional_data[1]) {
                                termId = error.additional_data[1];
                                console.log(`🏷️ Got term ID from error.additional_data[1]: ${termId}`);
                            }
                            
                            if (termId) {
                                tagIds.push(termId);
                                console.log(`🏷️ ✅ Using existing tag from error: "${keyword}" (ID: ${termId})`);
                            } else {
                                console.warn(`🏷️ ⚠️ Tag exists but couldn't extract ID from error for: "${keyword}"`);
                                console.warn('🏷️ Available error properties:', Object.keys(error));
                                
                                // Force refresh the tags list and search again
                                try {
                                    console.log(`🏷️ 🔍 Force refreshing tags and searching for: "${keyword}"`);
                                    
                                    // Invalidate cache and get fresh data
                                    await dispatch('core').invalidateResolutionForStoreSelector('getEntityRecords', ['taxonomy', 'post_tag']);
                                    
                                    const freshTags = await wp.data.resolveSelect('core').getEntityRecords('taxonomy', 'post_tag', {
                                        per_page: -1,
                                        search: keyword,
                                        _fields: 'id,name'
                                    });
                                    
                                    console.log(`🏷️ Fresh search results for "${keyword}":`, freshTags);
                                    
                                    if (freshTags && freshTags.length > 0) {
                                        const exactMatch = freshTags.find(tag => 
                                            tag.name.toLowerCase().trim() === keyword.toLowerCase().trim()
                                        );
                                        if (exactMatch) {
                                            tagIds.push(exactMatch.id);
                                            console.log(`🏷️ ✅ Found existing tag via fresh search: "${keyword}" (ID: ${exactMatch.id})`);
                                            
                                            // Add to our local cache
                                            allTags.push(exactMatch);
                                        } else {
                                            console.warn(`🏷️ ⚠️ No exact match found in fresh search for: "${keyword}"`);
                                        }
                                    } else {
                                        console.warn(`🏷️ ⚠️ No search results for: "${keyword}"`);
                                    }
                                } catch (searchError) {
                                    console.error(`🏷️ ❌ Fresh search failed for: "${keyword}"`, searchError);
                                }
                            }
                        } else {
                            console.error(`🏷️ ❌ Non-term_exists error for "${keyword}":`, error.code, error.message);
                        }
                    }
                }
                
                // Small delay between operations to avoid overwhelming the API
                if (i < keywords.length - 1) {
                    await new Promise(resolve => setTimeout(resolve, 100));
                }
            }
            
            // Update post with all tag IDs
            if (tagIds.length > 0) {
                console.log(`🏷️ 🎯 Updating post with ${tagIds.length} tags:`, tagIds);
                await dispatch('core/editor').editPost({ tags: tagIds });
                
                // Wait for the update to process
                await new Promise(resolve => setTimeout(resolve, 300));
                
                // Verify the update
                const finalPost = select('core/editor').getCurrentPost();
                console.log('🏷️ ✅ Final post tags:', finalPost.tags);
                console.log('🏷️ ✅ Tags updated successfully!');
            } else {
                console.warn('🏷️ ⚠️ No tags to add - all operations failed');
            }
            
        } catch (error) {
            console.error('🏷️ ❌ Critical error in addTagsToGutenberg:', error);
        }
    },
    
    // Manually render secondary keyword tags when the main render function is not available
    renderSecondaryKeywordTagsManually: function(keywordsStr) {
        console.log('🏷️ renderSecondaryKeywordTagsManually called with:', keywordsStr);
        
        const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
        const mainInput = document.getElementById('aysa-entity-second-keyword');
        
        if (!secondaryKeywordsContainer || !mainInput) {
            console.error('🏷️ Container or input not found for manual rendering');
            return;
        }
        
        // Clear existing content
        secondaryKeywordsContainer.innerHTML = '';
        
        if (!keywordsStr || keywordsStr.trim() === '') {
            console.log('🏷️ No keywords to render');
            return;
        }
        
        // Split and create tags
        const keywords = keywordsStr.split(',').map(k => k.trim()).filter(k => k !== '');
        
        keywords.forEach(keyword => {
            if (keyword && keyword.trim()) {
                this.createKeywordTag(keyword.trim(), false);
            }
        });
        
        console.log('🏷️ Rendered', keywords.length, 'keyword tags manually');
    },
    
    // Create a keyword tag
    createKeywordTag: function(keyword, isTracked = false) {
        const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
        if (!secondaryKeywordsContainer) return;
        
        const tag = document.createElement('div');
        tag.className = 'keyword-tag';
        if (isTracked) {
            tag.classList.add('is-tracked');
        }
        tag.innerHTML = `
            <span class="tag-text">${keyword}</span>
            ${isTracked ? '<span class="track-icon" title="Tracked">📊</span>' : ''}
            <span class="tag-remove">×</span>
        `;
        
        // Store tracking status
        tag.dataset.isTracked = isTracked ? 'true' : 'false';
        tag.dataset.keyword = keyword;
        
        // Add click event to show context menu (placeholder for now)
        tag.querySelector('.tag-text').addEventListener('click', function(e) {
            e.stopPropagation();
            console.log('🏷️ Keyword clicked:', keyword);
            // TODO: Implement context menu with "Set main", "Track", etc.
        });
        
        // Add click event to remove the tag
        tag.querySelector('.tag-remove').addEventListener('click', (e) => {
            e.stopPropagation();
            this.removeKeywordTag(tag, keyword);
        });
        
        // Add to container
        secondaryKeywordsContainer.appendChild(tag);
    },
    
    // Remove a keyword tag
    removeKeywordTag: function(tag, keyword) {
        const mainInput = document.getElementById('aysa-entity-second-keyword');
        if (!mainInput) return;
        
        // Remove from hidden input
        const currentKeywords = mainInput.value.split(',').map(k => k.trim()).filter(k => k !== '');
        const updatedKeywords = currentKeywords.filter(k => k !== keyword);
        mainInput.value = updatedKeywords.join(', ');
        
        // Remove the tag element
        tag.remove();
        
        console.log('🏷️ Removed keyword:', keyword);
    },
    
    // Sync primary keyword with hidden input silently (without triggering events)
    syncKeywordSilently: function(primaryKeyword) {
        // DISABLED: Don't sync with aysa-entity-keyword to completely avoid conflict dialogs
        // The blog content system will manage keywords independently
        console.log('🔑 Keyword sync disabled for blog content to avoid conflicts:', primaryKeyword);
    },

    // Initialize secondary keywords system
    initSecondaryKeywords: function() {
        const self = this;
        
        // Initialize existing keywords as tags
        const hiddenInput = document.getElementById('aysa-entity-second-keyword');
        if (hiddenInput && hiddenInput.value.trim()) {
            this.renderSecondaryKeywordTagsManually(hiddenInput.value);
        }
        
        // Add keyword button functionality
        const addButton = document.getElementById('add-secondary-keyword-btn');
        const newKeywordInput = document.getElementById('new-secondary-keyword');
        const trackCheckbox = document.getElementById('track-new-keyword');
        
        if (addButton && newKeywordInput) {
            addButton.addEventListener('click', function() {
                self.addSecondaryKeyword();
            });
            
            // Allow Enter key to add keyword
            newKeywordInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    self.addSecondaryKeyword();
                }
            });
        }
        
        console.log('🏷️ Secondary keywords system initialized');
    },
    
    // Add a new secondary keyword
    addSecondaryKeyword: function() {
        const newKeywordInput = document.getElementById('new-secondary-keyword');
        const trackCheckbox = document.getElementById('track-new-keyword');
        const hiddenInput = document.getElementById('aysa-entity-second-keyword');
        
        if (!newKeywordInput || !hiddenInput) return;
        
        const newKeyword = newKeywordInput.value.trim();
        if (!newKeyword) return;
        
        // Check if keyword already exists
        const currentKeywords = hiddenInput.value.split(',').map(k => k.trim()).filter(k => k !== '');
        if (currentKeywords.includes(newKeyword)) {
            this.showNotice('Keyword already exists!', 'error');
            return;
        }
        
        // Add to hidden input
        const updatedKeywords = [...currentKeywords, newKeyword];
        hiddenInput.value = updatedKeywords.join(', ');
        
        // Create tag
        const isTracked = trackCheckbox ? trackCheckbox.checked : false;
        this.createKeywordTag(newKeyword, isTracked);
        
        // Clear input
        newKeywordInput.value = '';
        
        console.log('🏷️ Added keyword:', newKeyword, 'Tracked:', isTracked);
    },
    
    // Clear existing secondary keywords from database (like categories/products)
    clearExistingSecondaryKeywords: async function() {
        console.log('🧹 CLEARING EXISTING SECONDARY KEYWORDS FROM DATABASE...');
        
        const postId = (typeof aysaBlogContentAjax !== 'undefined' && aysaBlogContentAjax.post_id) ? 
                       aysaBlogContentAjax.post_id : 0;
        const projectId = (typeof aysaBlogContentAjax !== 'undefined' && aysaBlogContentAjax.project_id) ? 
                          aysaBlogContentAjax.project_id : 0;
        
        if (!postId || !projectId) {
            console.log('🧹 SKIPPING API DELETE - Missing post ID or project ID');
            this.clearSecondaryKeywordsFromFrontend();
            return;
        }
        
        try {
            const entityType = 'Post';
            const params = new URLSearchParams({
                action: 'aysa_delete_entity_associations',
                nonce: this.getAjaxNonce(),
                entity_id: String(postId),
                entity_type: entityType,
                project_id: String(projectId)
            });
            const response = await fetch(this.getAjaxUrl(), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: params.toString(),
                credentials: 'same-origin'
            });
            const payload = await response.json();

            if (response.ok && payload && payload.success) {
                console.log('✅ Successfully deleted existing secondary keywords from database');
            } else {
                console.warn('⚠️ Failed to delete secondary keywords from database:', payload && payload.data ? payload.data : response.status);
            }
        } catch (error) {
            console.warn('⚠️ Error deleting secondary keywords from database:', error);
        }
        
        // Clear frontend regardless of API result
        this.clearSecondaryKeywordsFromFrontend();
    },
    
    // Clear secondary keywords from frontend
    clearSecondaryKeywordsFromFrontend: function() {
        console.log('🧹 CLEARING FRONTEND SECONDARY KEYWORDS...');
        
        // Clear the input field
        const secondKeywordField = document.getElementById('aysa-entity-second-keyword');
        if (secondKeywordField) {
            secondKeywordField.value = '';
            console.log('🧹 Cleared secondary keyword input field');
        }
        
        // Clear the tags container
        const secondaryContainer = document.getElementById('secondary-keywords-container');
        if (secondaryContainer) {
            secondaryContainer.innerHTML = '';
            console.log('🧹 Cleared secondary keywords container');
        }
        
        console.log('✅ FRONTEND SECONDARY KEYWORDS CLEARED');
    },
    
    // Update secondary keywords using the same smart logic as other entities
    updateSecondaryKeywordsWithSmartLogic: async function(suggestedKeywords, mainKeyword) {
        console.log('🧠 SMART LOGIC: Processing secondary keywords with main keyword:', mainKeyword);
        
        const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
        if (!secondaryKeywordInput) {
            console.error('Secondary keyword input not found');
            return;
        }
        
        // Check if force regenerate was requested
        const forceRegenerateCheckbox = document.getElementById('aysa-force-regenerate-secondary');
        const forceRegenerate = forceRegenerateCheckbox?.checked || false;
        
        // If force regenerate is enabled, delete existing secondary keywords from database
        if (forceRegenerate) {
            await this.clearExistingSecondaryKeywords();
        }
        
        // Get existing keywords (only needed for merge mode)
        const existingKeywordsStr = secondaryKeywordInput.value.trim();
        const existingKeywords = forceRegenerate ? [] : 
            (existingKeywordsStr ? existingKeywordsStr.split(',').map(k => k.trim()).filter(k => k !== '') : []);
        
        console.log('🧠 SMART LOGIC DECISION:');
        console.log('  - Force regenerate checked:', forceRegenerate);
        console.log('  - Existing secondary keywords:', existingKeywords.length > 0 ? existingKeywords : 'NONE');
        console.log('  - Suggested keywords:', suggestedKeywords);
        console.log('  - Main keyword to exclude:', mainKeyword);
        
        // Filter out main keyword and (if merging) duplicates
        let newKeywords = [];
        if (forceRegenerate) {
            // Replace mode: only filter out main keyword
            newKeywords = suggestedKeywords.filter(k => k !== mainKeyword);
            console.log('🧠 REPLACE MODE - replacing all secondary keywords');
        } else {
            // Merge mode: filter out duplicates and main keyword
            newKeywords = suggestedKeywords.filter(k => 
                k !== mainKeyword && !existingKeywords.includes(k)
            );
            console.log('🧠 MERGE MODE - adding new keywords to existing ones');
        }
        
        // Combine keywords based on mode
        const allKeywords = forceRegenerate ? newKeywords : [...existingKeywords, ...newKeywords];
        
        // Update the input field
        secondaryKeywordInput.value = allKeywords.join(', ');
        
        // Store flag for other functions to know we processed this
        window.aysaForceRegeneratedSecondary = forceRegenerate;
        
        // Reset the force regenerate checkbox after use (like categories/products)
        if (forceRegenerateCheckbox && forceRegenerate) {
            forceRegenerateCheckbox.checked = false;
            console.log('🔄 Reset force regenerate checkbox');
        }
        
        console.log('🧠 FINAL RESULT:', {
            mode: forceRegenerate ? 'REPLACE' : 'MERGE',
            finalKeywords: allKeywords,
            totalCount: allKeywords.length
        });
        
        // Render the tags visually
        if (typeof window.renderSecondaryKeywordTags === 'function') {
            console.log('🏷️ Rendering secondary keywords as tags');
            window.renderSecondaryKeywordTags();
        } else if (typeof renderSecondaryKeywordTags === 'function') {
            console.log('🏷️ Rendering secondary keywords as tags (global)');
            renderSecondaryKeywordTags();
        } else {
            console.log('🏷️ Rendering secondary keywords manually');
            this.renderSecondaryKeywordTagsManually(secondaryKeywordInput.value);
        }
    },
    
    // Load keywords from API and render tags
    loadKeywordsFromApi: function() {
        // Get post ID and project ID from available sources
        const postId = (typeof aysaBlogContentAjax !== 'undefined' && aysaBlogContentAjax.post_id) ? 
                       aysaBlogContentAjax.post_id : 
                       (typeof aysaParams !== 'undefined' && aysaParams.postId) ? aysaParams.postId : 0;
                       
        const projectId = (typeof aysaBlogContentAjax !== 'undefined' && aysaBlogContentAjax.project_id) ? 
                          aysaBlogContentAjax.project_id : 
                          (typeof aysaParams !== 'undefined' && aysaParams.project_id) ? aysaParams.project_id : 0;
        
        if (!postId || !projectId) {
            console.log('Cannot load keywords: Missing post ID or project ID', {postId, projectId});
            return;
        }
        const entityType = 'Post'; // For blog posts
        
        console.log('Loading keywords for post:', postId, 'project:', projectId);
        
        const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
        if (secondaryKeywordsContainer) {
            // Show loading state
            secondaryKeywordsContainer.innerHTML = '<div class="loading-placeholder" style="color: #999; font-style: italic;">Loading keywords...</div>';
        }
        
        this.fetchAssociationsForEntity(postId, entityType, projectId)
        .then(data => {
            console.log('Keywords loaded from API:', data);
            this.updateFormWithApiData(data);
        })
        .catch(error => {
            console.error('Error loading keywords from API:', error);
            // Clear loading state
            if (secondaryKeywordsContainer) {
                secondaryKeywordsContainer.innerHTML = '';
            }
        });
    },
    
    // Update form with data from API
    updateFormWithApiData: function(data) {
        // Check if the response is valid
        if (!data) {
            console.log('No keyword data returned from API');
            return;
        }
        
        // Check if the response is an array (multiple associations)
        const associations = Array.isArray(data) ? data : [data];
        
        if (associations.length > 0) {
            console.log('Processing', associations.length, 'keyword associations');
            
            // Find the main association (with isMain=true), or use the first one if none is marked as main
            const mainAssociation = associations.find(a => a.isMain === true) || associations[0];
            console.log('Main association identified:', mainAssociation);
            
            // Update main keyword field and display
            if (mainAssociation && mainAssociation.keyword) {
                const mainKeywordInput = document.getElementById('aysa-entity-keyword');
                const primaryKeywordInput = document.getElementById('aysa-primary-keyword');
                
                if (mainKeywordInput) {
                    console.log(`Setting main keyword: "${mainAssociation.keyword}" (isMain=${mainAssociation.isMain})`);
                    mainKeywordInput.value = mainAssociation.keyword;
                }
                
                // Also update the primary keyword input for consistency
                if (primaryKeywordInput && !primaryKeywordInput.value) {
                    primaryKeywordInput.value = mainAssociation.keyword;
                }
            }
            
            // Collect all other keywords from associations (not the main one)
            if (associations.length > 1) {
                const secondaryKeywords = associations
                    .filter(assoc => assoc.id !== mainAssociation.id)  // Exclude main association by ID
                    .map(assoc => assoc.keyword)
                    .filter(keyword => keyword && keyword.trim() !== '');
                
                console.log('Secondary keywords from API:', secondaryKeywords);
                
                // Update secondary keyword field
                const secondKeywordInput = document.getElementById('aysa-entity-second-keyword');
                if (secondKeywordInput && secondaryKeywords.length > 0) {
                    secondKeywordInput.value = secondaryKeywords.join(', ');
                    console.log('📥 Populated secondary keywords from API:', secondaryKeywords.join(', '));
                    
                    // Render the tags visually
                    this.renderSecondaryKeywordTagsManually(secondKeywordInput.value);
                } else if (secondKeywordInput) {
                    // Clear field if no secondary keywords from API
                    secondKeywordInput.value = '';
                    console.log('📥 No secondary keywords in API');
                    
                    // Clear the container
                    const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
                    if (secondaryKeywordsContainer) {
                        secondaryKeywordsContainer.innerHTML = '';
                    }
                }
            } else {
                console.log('📥 Only main keyword found, no secondary keywords');
                
                // Clear secondary keywords
                const secondKeywordInput = document.getElementById('aysa-entity-second-keyword');
                if (secondKeywordInput) {
                    secondKeywordInput.value = '';
                }
                
                const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
                if (secondaryKeywordsContainer) {
                    secondaryKeywordsContainer.innerHTML = '';
                }
            }
        } else {
            console.log('📥 No keyword associations found for this post');
            
            // Clear all keyword fields
            const mainKeywordInput = document.getElementById('aysa-entity-keyword');
            const secondKeywordInput = document.getElementById('aysa-entity-second-keyword');
            
            if (mainKeywordInput) mainKeywordInput.value = '';
            if (secondKeywordInput) secondKeywordInput.value = '';
            
            // Clear containers
            const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
            if (secondaryKeywordsContainer) {
                secondaryKeywordsContainer.innerHTML = '';
            }
        }
    }
};

// Initialize when document is ready
jQuery(document).ready(function() {
    if (typeof AysaBlogContent !== 'undefined') {
        AysaBlogContent.init();
    }
});
