/**
 * AYSA Actions
 * Functions for handling various action buttons
 */

const aysaNativeConsole = window.console || {
    log: function() {},
    warn: function() {},
    error: function() {}
};
var console = {
    log: function() {
        if (window.AYSA_DEBUG === true) {
            aysaNativeConsole.log.apply(aysaNativeConsole, arguments);
        }
    },
    warn: function() {
        if (window.AYSA_DEBUG === true) {
            aysaNativeConsole.warn.apply(aysaNativeConsole, arguments);
        }
    },
    error: function() {
        aysaNativeConsole.error.apply(aysaNativeConsole, arguments);
    }
};

// Canonical API routing shim for scripts that can run without aysa-admin.js.
(function initAysaApiRouting() {
    const prodBase = 'https://api.aysa.ai';
    window.AYSA_API_BASE = window.AYSA_API_BASE || prodBase;

    function rewriteUrl(url) {
        if (typeof url !== 'string') {
            return url;
        }
        if (url.indexOf(prodBase) !== 0) {
            return url;
        }
            return window.AYSA_API_BASE + url.slice(prodBase.length);
        }

    if (typeof window.fetch === 'function' && !window.__aysaFetchRewriterInstalled) {
        const nativeFetch = window.fetch.bind(window);
        window.fetch = function(resource, init) {
            try {
                if (typeof resource === 'string') {
                    return nativeFetch(rewriteUrl(resource), init);
                }
                if (resource && typeof resource.url === 'string' && typeof Request === 'function' && resource instanceof Request) {
                    const rewritten = rewriteUrl(resource.url);
                    if (rewritten !== resource.url) {
                        return nativeFetch(new Request(rewritten, resource), init);
                    }
                }
            } catch (e) {
                // fallback
            }
            return nativeFetch(resource, init);
        };
        window.__aysaFetchRewriterInstalled = true;
    }

    if (typeof window.XMLHttpRequest === 'function' && !window.__aysaXhrRewriterInstalled) {
        const originalOpen = window.XMLHttpRequest.prototype.open;
        window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
            const nextUrl = rewriteUrl(url);
            return originalOpen.call(this, method, nextUrl, async, user, password);
        };
        window.__aysaXhrRewriterInstalled = true;
    }
})();

function getAysaApiBaseUrl() {
    if (typeof window.AYSA_API_BASE === 'string' && window.AYSA_API_BASE) {
        return String(window.AYSA_API_BASE).replace(/\/$/, '');
    }
    return 'https://api.aysa.ai';
}

/** * Handle Edit Snippet button click * Updates all SEO metadata in one API call * Note: This function is now called from WordPress update button, not from a dedicated button */
function handleEditSnippet(e) {
    // Only prevent default if explicitly called with an event that should be prevented
    // When called from the WordPress update button, we should NOT prevent the default form submission
    if (e && e.preventDefault && e._shouldPreventDefault) {
        e.preventDefault();
    }
    
    console.log('Edit Snippet functionality triggered via WordPress update');
    
    // Return a promise to make this function async-compatible
    return new Promise((resolve, reject) => {
    
    // Get entity ID and type
    const entityId = getEntityId();
    const entityType = getEntityTypeGood();
    
    // Check if this is a new entity - if so, allow saving without a keyword
    const isNewEntity = (entityId === 0);
    
    if (entityId === 0 && !isNewEntity) {
        console.log("Cannot identify entity ID. Please save the entity first.");
        return;
    }
    
    // Get project ID from WordPress params instead of localStorage
    let projectId = 0;
    if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
        projectId = parseInt(aysaParams.project_id);
        console.log('Using project ID from WordPress:', projectId);
    } else {
        // Fallback to localStorage if needed
        const storedProjectId = localStorage.getItem('aysa_project_id');
        if (storedProjectId) {
            projectId = parseInt(storedProjectId);
            console.log('Using project ID from localStorage:', projectId);
        } else {
            console.warn('No project ID found!');
        }
    }
    
    // Find the name element
    const nameElement = document.getElementById('title') || 
                      document.querySelector('input[name="name"]') || 
                      document.getElementById('name') || 
                      document.querySelector('input[name="post_title"]');
    
    // Get the main keyword
    const mainKeyword = document.getElementById('aysa-entity-keyword')?.value || '';
    
    // Get secondary keywords
    const secondaryKeywordsValue = document.getElementById('aysa-entity-second-keyword')?.value || '';
    const secondaryKeywords = secondaryKeywordsValue.split(',')
        .map(keyword => keyword.trim())
        .filter(keyword => keyword !== '' && keyword !== mainKeyword);
    
    // Log the data we're about to save for debugging
    console.log('Saving AYSA SEO data:', {
        entityId: entityId,
        entityType: entityType,
        keyword: mainKeyword,
        secondaryKeywords: secondaryKeywords,
        metaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
        metaDescription: document.getElementById('aysa-entity-meta-description')?.value || ''
    });
    
        // If this is a new entity (category being created), save data for later processing
        if (isNewEntity) {
            console.log('New entity detected - saving data for post-creation processing');
            
            // Save all AYSA data to localStorage to be processed after entity creation
            const newEntityData = {
                keyword: mainKeyword,
                secondaryKeywords: secondaryKeywords,
                metaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
                metaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
                metaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
                entityType: entityType,
                projectId: projectId,
                entityName: nameElement ? nameElement.value : '',
                // SEO Settings
                targetedSearchEngine: document.getElementById('targeted_se')?.value || '',
                targetedCountry: document.getElementById('targeted_country')?.value || '',
                targetedRegion: document.getElementById('targeted_region')?.value || '',
                targetedCity: document.getElementById('targeted_city')?.value || '',
                updateFrequency: document.getElementById('update_frequency')?.value || '',
                languageOptimize: document.getElementById('language_optimize')?.value || '',
                deviceOptimize: document.getElementById('device_optimize')?.value || '',
                // Advanced
                index: document.getElementById('robots_index')?.checked || false,
                noFollow: document.getElementById('robots_nofollow')?.checked || false,
                noArchive: document.getElementById('robots_noarchive')?.checked || false,
                noImageIndex: document.getElementById('robots_noimageindex')?.checked || false,
                noSnippet: document.getElementById('robots_nosnippet')?.checked || false,
                maxSnippet: parseInt(document.getElementById('max_snippet')?.value) || -1,
                maxVideoPreview: parseInt(document.getElementById('max_video_preview')?.value) || -1,
                maxImagePreview: document.getElementById('max_image_preview')?.value || 'small',
                canonicalUrl: document.getElementById('canonical_url')?.value || '',
                timestamp: new Date().toISOString()
            };
            
            // Use a unique key for pending new entities
            const pendingKey = `aysa_pending_${entityType}_${Date.now()}`;
            localStorage.setItem(pendingKey, JSON.stringify(newEntityData));
            console.log('New entity data saved to localStorage with key:', pendingKey);
            
            // Set up detection for when the entity gets created
            setupNewEntityDetection(entityType, newEntityData, pendingKey);
            
            resolve('New entity - data saved for post-creation processing');
            return;
        }
        
        // Skip API call if no keyword is provided (allow empty keywords)
        if (!mainKeyword) {
            console.log('No keyword provided. Skipping API call.');
            resolve('No keyword provided - skipped API call');
            return;
        }
    
    // Store data in localStorage as a fallback mechanism, in case the API call fails
    try {
        const aysaFormData = {
            keyword: mainKeyword,
            second_keyword: secondaryKeywords.join(', '),
            meta_title: document.getElementById('aysa-entity-meta-title')?.value || '',
            meta_description: document.getElementById('aysa-entity-meta-description')?.value || '',
            meta_keywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
            // Add timestamp
            saved_at: new Date().toISOString()
        };
        
        localStorage.setItem(`aysa_form_data_${entityType}_${entityId}`, JSON.stringify(aysaFormData));
        console.log('Form data saved to localStorage as backup');
    } catch (err) {
        console.error('Failed to store backup data in localStorage:', err);
    }
    
    // Prepare the association data regardless of whether we're updating or creating
    const createAssociationData = {
        IdIntern: entityId,
        AssociatedOn: entityType,
        Value: nameElement ? nameElement.value : '',
        Link: window.location.href,
        Keyword: mainKeyword,
        ProjectId: projectId,
        IsMain: true,
        
        // SEO fields
        MetaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
        MetaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
        MetaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
        
        // SEO Settings
        TargetedSearchEngine: document.getElementById('targeted_se')?.value || '',
        TargetedCountry: document.getElementById('targeted_country')?.value || '',
        TargetedRegion: document.getElementById('targeted_region')?.value || '',
        TargetedCity: document.getElementById('targeted_city')?.value || '',
        UpdateFrequency: document.getElementById('update_frequency')?.value || '',
        LanguageOptimize: document.getElementById('language_optimize')?.value || '',
        DeviceOptimize: document.getElementById('device_optimize')?.value || '',
        
        // Advanced
        Index: document.getElementById('robots_index')?.checked || false,
        NoFollow: document.getElementById('robots_nofollow')?.checked || false,
        NoArchive: document.getElementById('robots_noarchive')?.checked || false,
        NoImageIndex: document.getElementById('robots_noimageindex')?.checked || false,
        NoSnippet: document.getElementById('robots_nosnippet')?.checked || false,
        MaxSnippet: parseInt(document.getElementById('max_snippet')?.value) || -1,
        MaxVideoPreview: parseInt(document.getElementById('max_video_preview')?.value) || -1,
        MaxImagePreview: document.getElementById('max_image_preview')?.value || 'small',
        CanonicalUrl: document.getElementById('canonical_url')?.value || '',
        
        // Include secondary keywords as a comma-separated string
        SecondKeyword: secondaryKeywords.join(', ')
    };
    
    // Log exact data being sent to API
    console.log('Preparing to send data to API:', JSON.stringify(createAssociationData));
    
    // Get existing associations to update if possible, or create new one
    const apiUrlGet = `${getAysaApiBaseUrl()}/api/Association/GetAllByAssociatedOnAndIdIntern?associatedOn=${entityType}&idIntern=${entityId}&projectId=${projectId}`;
    
    console.log('Fetching existing associations from:', apiUrlGet);
    
    fetch(apiUrlGet, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Origin': window.location.origin
        },
        mode: 'cors'
    })
    .then(response => {
        console.log('API response status:', response.status);
        if (!response.ok) {
            // If 404 error, it means no associations exist yet - create a new one
            if (response.status === 404) {
                console.log('No existing associations found. Creating a new one.');
                return { createNew: true };
            }
            throw new Error('API response status when fetching associations: ' + response.status);
        }
        return response.json().then(data => {
            console.log('Received response data:', data);
            return { data };
        });
    })
    .then(result => {
        let associationData = createAssociationData;
        
        // If we're creating a new association, use the data we prepared earlier
        if (result.createNew) {
            console.log('Using new association data:', associationData);
        } else {
            // We have existing associations to update
            const associations = result.data;
            console.log('Existing associations:', associations);
            
            // Găsim asocierea principală (isMain = true) sau prima asociere dacă nu există una principală
            let mainAssociation = null;
            
            if (Array.isArray(associations)) {
                mainAssociation = associations.find(a => a.isMain === true) || associations[0];
            } else if (associations && typeof associations === 'object') {
                // Dacă primim un singur obiect, îl folosim pe acesta
                mainAssociation = associations;
            }
            
            console.log('Main association:', mainAssociation);
            
            // Include the ID if we have a main association
            if (mainAssociation && mainAssociation.id) {
                associationData.Id = mainAssociation.id;
            }
        }
        
        console.log('Sending association data to API:', associationData);
        
        // Make API call to upsert the association
        const apiUrl = `${getAysaApiBaseUrl()}/api/Association/upsert`;
        
        return handleKeywordConflictAndUpsert(apiUrl, associationData);
    })
    .then(response => {
        console.log('Upsert API response status:', response.status);
        if (!response.ok) {
            throw new Error('API response status: ' + response.status);
        }
        return response.json();
    })
        .then(data => {
            console.log('API response for upsert:', data);
            
            // After successful upsert, process secondary keywords if any
            if (secondaryKeywords.length > 0) {
                console.log('Processing secondary keywords after main upsert:', secondaryKeywords);
                return processSecondaryKeywordsAfterUpsert(entityId, entityType, projectId, secondaryKeywords, data)
                    .then(() => {
                        // Also save the data in local WordPress storage via AJAX if possible
                        saveToWordPress(entityId, entityType, mainKeyword, secondaryKeywords.join(', '));
                        return data;
                    });
            } else {
                // Also save the data in local WordPress storage via AJAX if possible
                saveToWordPress(entityId, entityType, mainKeyword, secondaryKeywords.join(', '));
                return data;
            }
        })
        .then(finalData => {
            resolve(finalData);
        })
        .catch(error => {
            console.error('Error updating SEO data:', error);
            reject(error);
        });
    }); // Close the main promise
}

/**
 * Set up detection for when a new entity gets created
 */
function setupNewEntityDetection(entityType, newEntityData, pendingKey) {
    console.log('Setting up new entity detection for:', entityType);
    
    // Monitor for URL changes that indicate entity creation
    const originalUrl = window.location.href;
    
    // For categories, intercept the WordPress AJAX call to get the new category ID immediately
    if (entityType === 'Category') {
        console.log('Setting up category-specific AJAX interception...');
        
        // Store the original jQuery.ajax function
        const originalAjax = jQuery.ajax;
        let ajaxInterceptorActive = true;
        
        // Override jQuery.ajax to intercept category creation
        jQuery.ajax = function(options) {
            // Check if this is the add-tag AJAX call
            if (ajaxInterceptorActive && options.data && 
                ((typeof options.data === 'string' && options.data.includes('action=add-tag')) ||
                 (typeof options.data === 'object' && options.data.action === 'add-tag'))) {
                
                console.log('🎯 Intercepted add-tag AJAX call!', options);
                
                // Store the original success callback
                const originalSuccess = options.success;
                
                // Override the success callback
                options.success = function(response) {
                    console.log('🎯 Add-tag AJAX response received:', response);
                    
                    // Call the original success callback first
                    if (originalSuccess) {
                        originalSuccess.call(this, response);
                    }
                    
                    // Try to extract the new category ID from response
                    let newCategoryId = null;
                    
                    if (response) {
                        // Try different response formats
                        if (response.data && response.data.term_id) {
                            newCategoryId = parseInt(response.data.term_id);
                        } else if (response.term_id) {
                            newCategoryId = parseInt(response.term_id);
                        } else if (response.data && response.data.newcat) {
                            newCategoryId = parseInt(response.data.newcat);
                        } else if (typeof response === 'string') {
                            // Try to extract from HTML response
                            const termIdMatch = response.match(/data-term-id="(\d+)"/);
                            if (termIdMatch) {
                                newCategoryId = parseInt(termIdMatch[1]);
                            } else {
                                // Try to find term ID in JSON within HTML
                                const jsonMatch = response.match(/"term_id":(\d+)/);
                                if (jsonMatch) {
                                    newCategoryId = parseInt(jsonMatch[1]);
                                }
                            }
                        }
                    }
                    
                    if (newCategoryId && newCategoryId > 0) {
                        console.log('🎉 Successfully extracted new category ID:', newCategoryId);
                        
                        // Restore original jQuery.ajax immediately
                        ajaxInterceptorActive = false;
                        jQuery.ajax = originalAjax;
                        
                        // Process the pending data with a small delay to ensure WordPress finishes
                        setTimeout(() => {
                            processNewEntityData(newCategoryId, newEntityData, pendingKey);
                        }, 1000);
                    } else {
                        console.log('⚠️ Could not extract category ID from response, trying fallback detection');
                        console.log('Response structure:', response);
                        
                        // Restore original jQuery.ajax
                        ajaxInterceptorActive = false;
                        jQuery.ajax = originalAjax;
                        
                        // Fall back to DOM-based detection
                        setTimeout(() => {
                            tryFindNewCategoryInPage(newEntityData, pendingKey);
                        }, 2000);
                    }
                };
                
                // Store original error callback
                const originalError = options.error;
                
                // Override error callback
                options.error = function(xhr, status, error) {
                    console.log('❌ Add-tag AJAX error:', status, error);
                    
                    // Call original error callback
                    if (originalError) {
                        originalError.call(this, xhr, status, error);
                    }
                    
                    // Restore original jQuery.ajax
                    ajaxInterceptorActive = false;
                    jQuery.ajax = originalAjax;
                };
            }
            
            // Call the original jQuery.ajax
            return originalAjax.call(this, options);
        };
        
        // Set up a timeout to restore jQuery.ajax if nothing happens within 30 seconds
        setTimeout(() => {
            if (ajaxInterceptorActive) {
                ajaxInterceptorActive = false;
                jQuery.ajax = originalAjax;
                console.log('🔄 Restored original jQuery.ajax after timeout');
            }
        }, 30000);
        
        return;
    } else {
        // For other entity types, use the original detection method
        // Set up a mutation observer to watch for success messages
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) { // Element node
                        // Look for WordPress success messages
                        const successMessages = node.querySelectorAll ? 
                            node.querySelectorAll('.notice-success, .updated, .notice.is-dismissible') : [];
                        
                        if (successMessages.length > 0) {
                            console.log('Success message detected, checking for entity creation...');
                            // Small delay to ensure redirect happens
                            setTimeout(() => {
                                checkForNewEntityCreation(entityType, newEntityData, pendingKey, originalUrl);
                            }, 1000);
                        }
                    }
                });
            });
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        
        // Also check for URL changes (redirect after creation)
        const urlCheckInterval = setInterval(() => {
            if (window.location.href !== originalUrl) {
                console.log('URL changed, checking for entity creation...');
                clearInterval(urlCheckInterval);
                observer.disconnect();
                setTimeout(() => {
                    checkForNewEntityCreation(entityType, newEntityData, pendingKey, originalUrl);
                }, 500);
            }
        }, 1000);
        
        // Clean up after 30 seconds if nothing happens
        setTimeout(() => {
            clearInterval(urlCheckInterval);
            observer.disconnect();
        }, 30000);
    }
}

/**
 * Try to find the new category in the page as a fallback method
 */
function tryFindNewCategoryInPage(newEntityData, pendingKey) {
    console.log('🔍 Trying to find new category in page...');
    
    let attempts = 0;
    const maxAttempts = 10;
    
    const searchInterval = setInterval(() => {
        attempts++;
        console.log(`🔍 Search attempt ${attempts}/${maxAttempts}`);
        
        // Look for success messages first
        const successMessages = document.querySelectorAll('.notice-success, .updated, .notice.is-dismissible');
        if (successMessages.length > 0) {
            console.log('✅ Success message found, looking for new category...');
            
            // Try to find the new category in the table
            const categoryTable = document.querySelector('.wp-list-table tbody');
            if (categoryTable) {
                const rows = categoryTable.querySelectorAll('tr');
                if (rows.length > 0) {
                    // Get the first row (newest category)
                    const firstRow = rows[0];
                    const editLink = firstRow.querySelector('a[href*="tag_ID="]');
                    if (editLink) {
                        const href = editLink.getAttribute('href');
                        const match = href.match(/tag_ID=(\d+)/);
                        if (match) {
                            const newCategoryId = parseInt(match[1]);
                            console.log('🎉 Found new category ID from table:', newCategoryId);
                            clearInterval(searchInterval);
                            processNewEntityData(newCategoryId, newEntityData, pendingKey);
                            return;
                        }
                    }
                }
            }
        }
        
        // Check if we've been redirected to an edit page
        if (window.location.href.includes('tag_ID=')) {
            const urlParams = new URLSearchParams(window.location.search);
            const categoryId = urlParams.get('tag_ID');
            if (categoryId) {
                console.log('🎉 Found category ID from redirect URL:', categoryId);
                clearInterval(searchInterval);
                processNewEntityData(parseInt(categoryId), newEntityData, pendingKey);
                return;
            }
        }
        
        // Stop after max attempts
        if (attempts >= maxAttempts) {
            console.log('❌ Max search attempts reached, giving up');
            clearInterval(searchInterval);
            
            // Show message that data is saved for manual processing
            if (typeof showToast === 'function') {
                showToast('Category created but AYSA data detection failed. Data saved for manual processing.', 'warning');
            }
        }
    }, 1000);
}

/**
 * Check if a new entity was created and process pending data
 */
function checkForNewEntityCreation(entityType, newEntityData, pendingKey, originalUrl) {
    const currentEntityId = getEntityId();
    
    if (currentEntityId && currentEntityId !== 0) {
        console.log('New entity created with ID:', currentEntityId);
        // Process the pending AYSA data
        processNewEntityData(currentEntityId, newEntityData, pendingKey);
    } else {
        console.log('No entity ID found yet, will retry...');
        // Retry after a short delay
        setTimeout(() => {
            const retryEntityId = getEntityId();
            if (retryEntityId && retryEntityId !== 0) {
                console.log('New entity found on retry with ID:', retryEntityId);
                processNewEntityData(retryEntityId, newEntityData, pendingKey);
            }
        }, 2000);
    }
}

/**
 * Process AYSA data for newly created entity
 */
async function processNewEntityData(entityId, newEntityData, pendingKey) {
    console.log('Processing new entity data for ID:', entityId, newEntityData);
    
    try {
        // Prepare the association data for the new entity
        const associationData = {
            IdIntern: entityId,
            AssociatedOn: newEntityData.entityType,
            Value: newEntityData.entityName,
            Link: window.location.href,
            Keyword: newEntityData.keyword,
            ProjectId: newEntityData.projectId,
            IsMain: true,
            
            // SEO fields
            MetaTitle: newEntityData.metaTitle,
            MetaDescription: newEntityData.metaDescription,
            MetaKeywords: newEntityData.metaKeywords,
            
            // SEO Settings
            TargetedSearchEngine: newEntityData.targetedSearchEngine,
            TargetedCountry: newEntityData.targetedCountry,
            TargetedRegion: newEntityData.targetedRegion,
            TargetedCity: newEntityData.targetedCity,
            UpdateFrequency: newEntityData.updateFrequency,
            LanguageOptimize: newEntityData.languageOptimize,
            DeviceOptimize: newEntityData.deviceOptimize,
            
            // Advanced
            Index: newEntityData.index,
            NoFollow: newEntityData.noFollow,
            NoArchive: newEntityData.noArchive,
            NoImageIndex: newEntityData.noImageIndex,
            NoSnippet: newEntityData.noSnippet,
            MaxSnippet: newEntityData.maxSnippet,
            MaxVideoPreview: newEntityData.maxVideoPreview,
            MaxImagePreview: newEntityData.maxImagePreview,
            CanonicalUrl: newEntityData.canonicalUrl,
            
            // Include secondary keywords as a comma-separated string
            SecondKeyword: newEntityData.secondaryKeywords.join(', ')
        };
        
        console.log('Creating main association for new entity:', associationData);
        
        // Create the main association
        const apiUrl = `${getAysaApiBaseUrl()}/api/Association/upsert`;
        
        const response = await handleKeywordConflictAndUpsert(apiUrl, associationData);
        
        if (!response.ok) {
            throw new Error('API response status: ' + response.status);
        }
        
        const mainAssociationData = await response.json();
        console.log('Main association created successfully:', mainAssociationData);
        
        // Process secondary keywords if any
        if (newEntityData.secondaryKeywords.length > 0) {
            console.log('Processing secondary keywords for new entity:', newEntityData.secondaryKeywords);
            
            await processSecondaryKeywordsWithTracking(
                entityId, 
                newEntityData.entityType, 
                newEntityData.projectId, 
                newEntityData.secondaryKeywords, 
                mainAssociationData
            );
        }
        
        // Clean up localStorage
        localStorage.removeItem(pendingKey);
        console.log('Removed pending data from localStorage:', pendingKey);
        
        // Show success message
        if (typeof showToast === 'function') {
            showToast('AYSA SEO data processed successfully for new entity!', 'success');
        }
        
    } catch (error) {
        console.error('Error processing new entity data:', error);
        // Keep the data in localStorage for manual retry
        if (typeof showToast === 'function') {
            showToast('Error processing AYSA data. Data saved for retry.', 'error');
        }
    }
}

// Make processNewEntityData globally available
window.processNewEntityData = processNewEntityData;

/**
 * Process secondary keywords with tracking information for new entities
 */
async function processSecondaryKeywordsWithTracking(entityId, entityType, projectId, secondaryKeywords, mainAssociationData) {
    console.log('Processing secondary keywords with tracking for new entity:', secondaryKeywords);
    
    // Prepare associations array for bulk insert
    const associationsArray = secondaryKeywords
        .map((keywordData, index) => {
            // Handle both string and object formats
            const keyword = typeof keywordData === 'string' ? keywordData : keywordData.keyword;
            const isTracked = typeof keywordData === 'object' && keywordData.isTracked !== undefined ? 
                             keywordData.isTracked : true; // Default to tracked
            
            if (!keyword || keyword.trim() === '') return null;
            
            const secondaryAssociationData = {
                IdIntern: entityId,
                AssociatedOn: entityType,
                Value: mainAssociationData.value || '',
                Link: window.location.href,
                Keyword: keyword.trim(),
                ProjectId: projectId,
                IsMain: false, // Secondary keywords are not main
                IsTracked: isTracked, // Set tracking status
                
                // Copy SEO fields from main association if available
                MetaTitle: mainAssociationData.metaTitle || '',
                MetaDescription: mainAssociationData.metaDescription || '',
                MetaKeywords: mainAssociationData.metaKeywords || '',
                
                // Copy SEO settings from main association
                TargetedSearchEngine: mainAssociationData.targetedSearchEngine || '',
                TargetedCountry: mainAssociationData.targetedCountry || '',
                TargetedRegion: mainAssociationData.targetedRegion || '',
                TargetedCity: mainAssociationData.targetedCity || '',
                UpdateFrequency: mainAssociationData.updateFrequency || '',
                LanguageOptimize: mainAssociationData.languageOptimize || '',
                DeviceOptimize: mainAssociationData.deviceOptimize || '',
                
                // Copy advanced settings
                Index: mainAssociationData.index || false,
                NoFollow: mainAssociationData.noFollow || false,
                NoArchive: mainAssociationData.noArchive || false,
                NoImageIndex: mainAssociationData.noImageIndex || false,
                NoSnippet: mainAssociationData.noSnippet || false,
                MaxSnippet: mainAssociationData.maxSnippet || -1,
                MaxVideoPreview: mainAssociationData.maxVideoPreview || -1,
                MaxImagePreview: mainAssociationData.maxImagePreview || 'small',
                CanonicalUrl: mainAssociationData.canonicalUrl || ''
            };
            
            console.log(`Preparing secondary association ${index + 1} with tracking=${isTracked}:`, secondaryAssociationData);
            return secondaryAssociationData;
        })
        .filter(association => association !== null); // Remove null entries
    
    if (associationsArray.length === 0) {
        console.log('No valid secondary keywords to process');
        return [];
    }
    
    try {
        console.log('Using bulk insert for secondary keywords with tracking:', associationsArray);
        
        const apiUrl = `${getAysaApiBaseUrl()}/api/Association/insertmany`;
        
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            body: JSON.stringify(associationsArray),
            mode: 'cors'
        });
        
        if (!response.ok) {
            throw new Error(`Bulk insert API error: ${response.status}`);
        }
        
        const results = await response.json();
        console.log('All secondary keywords with tracking processed successfully via bulk insert:', results);
        return results;
        
    } catch (error) {
        console.error('Error processing secondary keywords with tracking via bulk insert:', error);
        throw error;
    }
}

/**
 * Process secondary keywords after main upsert
 */
async function processSecondaryKeywordsAfterUpsert(entityId, entityType, projectId, secondaryKeywords, mainAssociationData) {
    console.log('Processing secondary keywords after upsert:', secondaryKeywords);
    
    // Prepare associations array for bulk insert
    const associationsArray = secondaryKeywords
        .map((keyword, index) => {
            if (!keyword || keyword.trim() === '') return null;
            
            const secondaryAssociationData = {
                IdIntern: entityId,
                AssociatedOn: entityType,
                Value: mainAssociationData.value || '',
                Link: window.location.href,
                Keyword: keyword.trim(),
                ProjectId: projectId,
                IsMain: false, // Secondary keywords are not main
                
                // Copy SEO fields from main association if available
                MetaTitle: mainAssociationData.metaTitle || '',
                MetaDescription: mainAssociationData.metaDescription || '',
                MetaKeywords: mainAssociationData.metaKeywords || '',
                
                // Copy SEO settings from main association
                TargetedSearchEngine: mainAssociationData.targetedSearchEngine || '',
                TargetedCountry: mainAssociationData.targetedCountry || '',
                TargetedRegion: mainAssociationData.targetedRegion || '',
                TargetedCity: mainAssociationData.targetedCity || '',
                UpdateFrequency: mainAssociationData.updateFrequency || '',
                LanguageOptimize: mainAssociationData.languageOptimize || '',
                DeviceOptimize: mainAssociationData.deviceOptimize || '',
                
                // Copy advanced settings
                Index: mainAssociationData.index || false,
                NoFollow: mainAssociationData.noFollow || false,
                NoArchive: mainAssociationData.noArchive || false,
                NoImageIndex: mainAssociationData.noImageIndex || false,
                NoSnippet: mainAssociationData.noSnippet || false,
                MaxSnippet: mainAssociationData.maxSnippet || -1,
                MaxVideoPreview: mainAssociationData.maxVideoPreview || -1,
                MaxImagePreview: mainAssociationData.maxImagePreview || 'small',
                CanonicalUrl: mainAssociationData.canonicalUrl || ''
            };
            
            console.log(`Preparing secondary association ${index + 1}:`, secondaryAssociationData);
            return secondaryAssociationData;
        })
        .filter(association => association !== null); // Remove null entries
    
    if (associationsArray.length === 0) {
        console.log('No valid secondary keywords to process');
        return [];
    }
    
    try {
        console.log('Using bulk insert for secondary keywords after upsert:', associationsArray);
        
        const apiUrl = `${getAysaApiBaseUrl()}/api/Association/insertmany`;
        
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            body: JSON.stringify(associationsArray),
            mode: 'cors'
        });
        
        if (!response.ok) {
            throw new Error(`Bulk insert API error: ${response.status}`);
        }
        
        const results = await response.json();
        console.log('All secondary keywords processed successfully via bulk insert:', results);
        return results;
        
    } catch (error) {
        console.error('Error processing secondary keywords via bulk insert:', error);
        throw error;
    }
}

// Make function globally available
window.processSecondaryKeywordsAfterUpsert = processSecondaryKeywordsAfterUpsert;

/**
 * Helper function to also save data to WordPress database for backup
 */
function saveToWordPress(entityId, entityType, keyword, secondKeywords) {
    // Only proceed if we have WordPress AJAX URL
    if (!window.ajaxurl && typeof aysaParams === 'undefined') {
        console.log('Cannot save to WordPress, no AJAX URL available');
        return;
    }
    
    const ajaxUrl = window.ajaxurl || (aysaParams && aysaParams.ajax_url);
    if (!ajaxUrl) {
        console.log('Cannot save to WordPress, no AJAX URL available');
        return;
    }
    
    console.log('Saving SEO data to WordPress database as backup');
    
    // Collect form data
    const formData = new FormData();
    formData.append('action', 'aysa_save_seo_data');
    formData.append('entity_id', entityId);
    formData.append('entity_type', entityType);
    formData.append('keyword', keyword);
    formData.append('second_keyword', secondKeywords);
    formData.append('meta_title', document.getElementById('aysa-entity-meta-title')?.value || '');
    formData.append('meta_description', document.getElementById('aysa-entity-meta-description')?.value || '');
    formData.append('meta_keywords', document.getElementById('aysa-entity-meta-keywords')?.value || '');
    
    // Add nonce if available
    if (typeof aysaParams !== 'undefined' && aysaParams && aysaParams.nonce) {
        formData.append('nonce', aysaParams.nonce);
    }
    
    // Send AJAX request
    fetch(ajaxUrl, {
        method: 'POST',
        body: formData,
        credentials: 'same-origin'
    })
    .then(response => response.json())
    .then(data => {
        console.log('WordPress backup save response:', data);
    })
    .catch(error => {
        console.error('Error saving to WordPress:', error);
    });
}

// Global variable to store data before SEO suggestions are applied
window.aysaPreSuggestionData = {};

/**
 * Handle Generate Suggestions button click
 */
async function handleGenerateSuggestions(e) {
    console.log('🚀 DEBUG: handleGenerateSuggestions CALLED', e);
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();

    const button = e.target.closest('button') || e.target;
    console.log('🚀 DEBUG: Button found:', button);
    
    // 🔒 DISABLE ALL RELEVANT BUTTONS during SEO generation
    disableAllRelevantButtons();
    
    // Show spinner and disable button with progress indicators
    button.disabled = true;
    let currentStep = 'Preparing APIs...';
    
    const updateButtonProgress = (message) => {
        button.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle; animation: spin 1s linear infinite;">
                <path d="M12,4V2A10,10 0 0,0 2,12H4A8,8 0 0,1 12,4Z"/>
            </svg>
            ${message}
        `;
    };
    
    updateButtonProgress(currentStep);
    
    const spinner = button.nextElementSibling;
    if (spinner && spinner.classList.contains('spinner')) {
        spinner.classList.add('is-active');
    }
    
    // Progress indicators to inform user about potentially slow API calls
    const progressTimers = [
        setTimeout(() => updateButtonProgress('Generating meta title...'), 2000),
        setTimeout(() => updateButtonProgress('Generating meta description...'), 8000),
        setTimeout(() => updateButtonProgress('Generating SEO content (may take 1-2 min)...'), 15000),
        setTimeout(() => updateButtonProgress('Slower APIs in progress... please wait...'), 30000),
        setTimeout(() => updateButtonProgress('Finalizing processing...'), 60000),
        setTimeout(() => updateButtonProgress('Last APIs... almost done...'), 90000)
    ];

    // Get entity ID and type - prioritize button attributes
    let entityId = 0;
    let entityType = 'Page';
    
    // First try to get from button attributes (for sidebar/floating buttons)
    if (button.getAttribute('data-entity-id')) {
        entityId = parseInt(button.getAttribute('data-entity-id'));
        console.log('🚀 DEBUG: Got entity ID from button attribute:', entityId);
    }
    
    if (button.getAttribute('data-entity-type')) {
        entityType = button.getAttribute('data-entity-type');
        console.log('🚀 DEBUG: Got entity type from button attribute:', entityType);
    }
    
    // Fallback to detection functions if not found in attributes
    if (entityId === 0) {
        entityId = getEntityId();
        console.log('🚀 DEBUG: Fallback - got entity ID from getEntityId():', entityId);
    }
    
    if (!button.getAttribute('data-entity-type')) {
        entityType = getEntityTypeGood();
        console.log('🚀 DEBUG: Fallback - got entity type from getEntityTypeGood():', entityType);
    }
    
    console.log('🚀 DEBUG: Final entity values - ID:', entityId, 'Type:', entityType);
    
    // ✅ CRITICAL: Validate category name for new categories before making API calls
    if (entityType === 'category' && entityId === 0) {
        // This is a new category - check if name is provided
        const categoryNameInput = document.querySelector('input[name="tag-name"]') || document.querySelector('#tag-name');
        const categoryName = categoryNameInput ? categoryNameInput.value.trim() : '';
        
        if (!categoryName) {
            console.warn('❌ Category name is required before generating SEO suggestions');
            
            // Clear progress timers
            progressTimers.forEach(timer => clearTimeout(timer));
            
            // 🔓 RE-ENABLE ALL RELEVANT BUTTONS (early exit case)
            enableAllRelevantButtons();
            
            // Reset button
            button.disabled = false;
            button.innerHTML = `
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle;">
                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                </svg>
                Generate SEO Suggestions
            `;
            if (spinner) spinner.classList.remove('is-active');
            
            showToast('Please enter a category name first before generating SEO suggestions.', 'error');
            
            // Focus and highlight the name field
            if (categoryNameInput) {
                categoryNameInput.focus();
                categoryNameInput.style.borderColor = '#dc3545';
                categoryNameInput.style.boxShadow = '0 0 0 0.2rem rgba(220, 53, 69, 0.25)';
                
                // Remove error styling after user starts typing
                categoryNameInput.addEventListener('input', function() {
                    this.style.borderColor = '';
                    this.style.boxShadow = '';
                }, { once: true });
            }
            
            return;
        }
        
        console.log('✅ Category name validated for SEO suggestions:', categoryName);
    }
    console.log('🚀 DEBUG: Entity ID:', entityId, 'Entity Type:', entityType);

    // Allow generation for new entities (ID = 0) as well
    if (entityId === null || entityId === undefined) {
        console.log('🚀 DEBUG: Entity ID is null/undefined, stopping execution');
        
        // Clear progress timers
        progressTimers.forEach(timer => clearTimeout(timer));
        
        if (typeof showToast === 'function') {
            showToast('Entity ID not found. Please save the entity first.', 'error');
        }
        
        // 🔓 RE-ENABLE ALL RELEVANT BUTTONS (early exit case)
        enableAllRelevantButtons();
        
        button.disabled = false;
        button.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle;">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
            </svg>
            Generate SEO Suggestions
        `;
        if (spinner) spinner.classList.remove('is-active');
        return;
    }
    
    if (entityId === 0) {
        console.log('🚀 DEBUG: Entity ID is 0 (new entity), allowing generation');
    }

    // Capture current data for versioning BEFORE suggestions are generated
    const preData = {
        metaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
        metaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
        metaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
        productDescription: '',
        productShortDescription: '',
        productPermalink: '',
        categoryName: '',
        categoryDescription: ''
    };

    if (entityType === 'Product') {
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
            preData.productDescription = tinyMCE.get('content').getContent();
        } else {
            preData.productDescription = document.getElementById('content')?.value || '';
        }

        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
            preData.productShortDescription = tinyMCE.get('excerpt').getContent();
        } else {
            preData.productShortDescription = document.getElementById('excerpt')?.value || document.getElementById('post_excerpt')?.value || document.querySelector('#postexcerpt textarea')?.value || '';
        }
        
        const permalinkField = document.getElementById('editable-post-name') || document.getElementById('editable-post-name-full') || document.querySelector('#edit-slug-box .editable-post-name');
        preData.productPermalink = permalinkField ? (permalinkField.textContent || permalinkField.value) : '';

    } else if (entityType === 'Category') {
        preData.categoryName = document.getElementById('name')?.value || '';
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
            preData.categoryDescription = tinyMCE.get('description').getContent();
        } else {
            preData.categoryDescription = document.getElementById('description')?.value || '';
        }
    }
    window.aysaPreSuggestionData = preData;
    console.log('AYSA Versioning: Stored pre-suggestion data:', window.aysaPreSuggestionData);


    // Get keyword
    let keyword = document.getElementById('aysa-entity-keyword')?.value?.trim() || '';
    const hasMainKeyword = keyword !== '';
    
    // Get entity name if it exists
    let entityName = '';
    
    // Try different methods to get the entity name/title
    // 1. For categories
    const categoryNameElement = document.getElementById('name');
    if (categoryNameElement) {
        entityName = categoryNameElement.value?.trim() || '';
    }
    
    // 2. For posts/pages - try classic editor first
    if (!entityName) {
        const postTitleElement = document.querySelector('input[name="post_title"]') || document.getElementById('title');
        if (postTitleElement) {
            entityName = postTitleElement.value?.trim() || '';
        }
    }
    
    // 3. For posts/pages - try Gutenberg editor
    if (!entityName && typeof wp !== 'undefined' && wp.data && wp.data.select) {
        try {
            const currentPost = wp.data.select('core/editor').getCurrentPost();
            if (currentPost && currentPost.title) {
                entityName = currentPost.title.trim();
                console.log('🚀 INFO: Got title from Gutenberg API:', entityName);
            }
        } catch (e) {
            console.warn('🚀 WARNING: Could not get title from Gutenberg API:', e);
        }
    }
    
    // 4. For posts/pages - try Gutenberg DOM elements
    if (!entityName) {
        const gutenbergTitleElement = document.querySelector('.editor-post-title__input') || 
                                    document.querySelector('textarea.editor-post-title__input') ||
                                    document.querySelector('[aria-label*="title" i]');
        if (gutenbergTitleElement) {
            entityName = gutenbergTitleElement.value?.trim() || gutenbergTitleElement.textContent?.trim() || '';
            if (entityName) {
                console.log('🚀 INFO: Got title from Gutenberg DOM:', entityName);
            }
        }
    }
    
    console.log('🚀 DEBUG: Entity name detection result:', entityName);
    console.log('🚀 DEBUG: Detection details:', {
        categoryName: document.getElementById('name')?.value || 'not found',
        classicTitle: (document.querySelector('input[name="post_title"]') || document.getElementById('title'))?.value || 'not found',
        gutenbergAPI: typeof wp !== 'undefined' && wp.data && wp.data.select ? 'available' : 'not available',
        gutenbergDOM: document.querySelector('.editor-post-title__input')?.value || document.querySelector('.editor-post-title__input')?.textContent || 'not found'
    });
    
    // Show message above button if no main keyword is set
    if (!hasMainKeyword) {
        showKeywordWarningMessage();
        console.log('🚀 WARNING: No main keyword found, using title as fallback');
    } else {
        hideKeywordWarningMessage();
    }
    
    // If keyword is empty, use entity name as fallback
    if (!keyword && entityName) {
        keyword = entityName;
        // Set it in the form field for reference
        const keywordInput = document.getElementById('aysa-entity-keyword');
        if (keywordInput) {
            keywordInput.value = keyword;
            // Add visual indication that this is auto-filled
            keywordInput.style.backgroundColor = '#fff3cd';
            keywordInput.title = 'Auto-filled from title - please set a proper main keyword';
        }
        console.log('🚀 INFO: Using title as keyword fallback:', keyword);
    }
    
    // Final validation - if still no keyword, stop execution
    if (!keyword) {
        // Clear progress timers and reset button
        progressTimers.forEach(timer => clearTimeout(timer));
        
        // 🔓 RE-ENABLE ALL RELEVANT BUTTONS (early exit case)
        enableAllRelevantButtons();
        
        button.disabled = false;
        button.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle;">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
            </svg>
            Generate SEO Suggestions
        `;
        if (spinner) spinner.classList.remove('is-active');
        
        // Show error message above button instead of alert
        showKeywordErrorMessage();
        return;
    } else {
        hideKeywordErrorMessage();
    }
    
    console.log('Using keyword for SEO suggestions:', keyword);
    console.log('Main keyword was provided:', hasMainKeyword);

    // Save the current permalink values before generating suggestions
    const permalinkInputs = [
        document.getElementById('post_name'),
        document.getElementById('slug'),
        document.querySelector('input[name="post_name"]'),
        document.querySelector('input[name="slug"]'),
        document.querySelector('.editor-post-slug__input')
    ].filter(el => el); // Filter out null values
    
    // Store original permalink values for comparison after generating suggestions
    const originalPermalinks = {};
    
    permalinkInputs.forEach((input, index) => {
        if (input && input.value) {
            originalPermalinks[`input_${index}`] = input.value;
            // Also store in dataset for reference
            input.dataset.originalBeforeSeo = input.value;
            console.log(`Saved original permalink for input ${index}:`, input.value);
        }
    });
    
    console.log('Original permalinks before SEO generation:', originalPermalinks);
    
    // ✅ REMOVED: Redirect tracking is now handled by PHP hooks
    // window.aysaRedirectCreated = false;
    console.log('🚀 DEBUG: Redirect tracking moved to PHP - no longer needed in JavaScript');
    
    // Get the website name for context
    const websiteName = document.querySelector('meta[property="og:site_name"]')?.content || 
                       document.title.split(' - ')[1] || 
                       'WordPress';
    
    // Get language from metabox or global settings
    const language = getLanguageOptimizeValue();
    
    // Add timeout to ensure button doesn't get stuck - increase to 3 minutes for slow APIs
    const buttonResetTimeout = setTimeout(() => {
        // Clear progress timers
        progressTimers.forEach(timer => clearTimeout(timer));
        
        // 🔓 RE-ENABLE ALL RELEVANT BUTTONS (timeout case)
        enableAllRelevantButtons();
        
        button.disabled = false;
        button.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle;">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
            </svg>
            Generate SEO Suggestions
        `;
        if (spinner) spinner.classList.remove('is-active');
        if (typeof showToast === 'function') {
            showToast('Suggestion generation timed out after 3 minutes. Some APIs are slow - try again.', 'warning');
        }
    }, 180000); // 3 minutes timeout (180 seconds)

    // ✅ SMART SECONDARY KEYWORDS LOGIC
    console.log('🧠 SMART SECONDARY KEYWORDS: Checking if we need to generate new ones...');
    
    // Check if we have existing secondary keywords
    const existingSecondaryKeywords = document.getElementById('aysa-entity-second-keyword')?.value?.trim() || '';
    
    // Get the previously stored keyword for comparison (stored in a data attribute)
    const keywordInput = document.getElementById('aysa-entity-keyword');
    const previousKeyword = keywordInput?.dataset.previousKeyword || '';
    
    // Store current keyword for future comparisons
    if (keywordInput) {
        keywordInput.dataset.previousKeyword = keyword;
    }
    
    // Check if user wants to force regenerate secondary keywords
    const forceRegenerateCheckbox = document.getElementById('aysa-force-regenerate-secondary');
    const forceRegenerate = forceRegenerateCheckbox?.checked || false;
    
    // Decide if we need to generate new secondary keywords
    const shouldGenerateSecondaryKeywords = 
        !existingSecondaryKeywords || // No existing secondary keywords
        (existingSecondaryKeywords && previousKeyword && keyword !== previousKeyword) || // Keyword changed
        forceRegenerate; // User explicitly wants to regenerate
        
    console.log('🧠 SMART LOGIC DECISION:');
    console.log('  - Current keyword:', keyword);
    console.log('  - Previous keyword:', previousKeyword);
    console.log('  - Existing secondary keywords:', existingSecondaryKeywords ? 'YES' : 'NO');
    console.log('  - Force regenerate checked:', forceRegenerate);
    console.log('  - Should generate new secondary keywords:', shouldGenerateSecondaryKeywords);
    
    let secondKeyword = '';
    
    if (shouldGenerateSecondaryKeywords) {
        console.log('🧹 CLEARING EXISTING SECONDARY KEYWORDS AND GENERATING NEW ONES...');
        
        // Set global flag to indicate force regeneration mode
        window.aysaForceRegeneratedSecondary = forceRegenerate;
        console.log('🔄 Set force regeneration flag:', forceRegenerate);
        
        // Reset the force regenerate checkbox after use
        if (forceRegenerateCheckbox && forceRegenerate) {
            forceRegenerateCheckbox.checked = false;
            console.log('🔄 Reset force regenerate checkbox');
        }
        
        try {
            await clearExistingSecondaryKeywords(entityId, entityType);
            console.log('🧹✅ SECONDARY KEYWORDS CLEARING COMPLETED');
        } catch (error) {
            console.warn('🧹⚠️ SECONDARY KEYWORDS CLEARING FAILED, BUT CONTINUING:', error);
            // Continue execution even if clearing fails
        }
        
        // Use deterministic local fallback keywords here.
        // The optional secondary-keyword and keyword-clustering endpoints are noisy
        // and non-critical for Generate SEO, while the main content/meta flow works
        // correctly without them.
        console.log('🔄 Using static secondary keyword fallback for Generate SEO.');
        secondKeyword = generateFallbackKeywords(keyword, getEntityTypeGood());
        console.log('🔄 STATIC FALLBACK: Generated keywords:', secondKeyword);
        
        // Set secondary keywords in the form for use in subsequent API calls
        if (secondKeyword) {
            const secondKeywordInput = document.getElementById('aysa-entity-second-keyword');
            if (secondKeywordInput) {
                secondKeywordInput.value = secondKeyword;
                console.log('✅ Secondary keywords set in form for subsequent API calls:', secondKeyword);
            }
        }
    } else {
        console.log('🧠 KEEPING EXISTING SECONDARY KEYWORDS - no changes needed');
        // Use existing secondary keywords for API calls
        secondKeyword = existingSecondaryKeywords;
    }
    
    // ✅ THEN: Prepare promises for remaining API calls (now with secondary keywords available)
    const promises = [];
    
    // Fetch main suggestions with reasonable timeouts
    console.log('🚀 DEBUG: Adding main API calls...');
    promises.push(fetchSuggestionWithTimeout('meta-title', keyword, language, websiteName, 30000)); // 30 seconds  
    promises.push(fetchSuggestionWithTimeout('meta-keywords', keyword, language, websiteName, 30000)); // 30 seconds
    promises.push(fetchSuggestionWithTimeout('meta-description', keyword, language, websiteName, 30000)); // 30 seconds
    
    // For product, use seo-optimized-content for productDescription (not product-description)
    if (entityType === 'Product') {
        console.log('🚀 DEBUG: Adding Product-specific API calls (may be slow)...');
        promises.push(fetchSuggestionWithTimeout('product-or-category-title', keyword, language, 'product', 30000)); // 30 seconds for title
        promises.push(fetchSuggestionWithTimeout('seo-optimized-content', keyword, language, websiteName, 120000)); // 2 minutes for content - NOW WITH SECONDARY KEYWORDS
        promises.push(fetchSuggestionWithTimeout('product-short-description', keyword, language, websiteName, 60000)); // 1 minute for short content
        promises.push(fetchSuggestionWithTimeout('product-permalink', keyword, language, websiteName, 30000)); // 30 seconds for permalink
    } else if (entityType === 'Category') {
        // For category, fetch title, description and permalink
        console.log('🚀 DEBUG: Adding Category title, description and permalink API calls (may be slow)...');
        promises.push(fetchSuggestionWithTimeout('product-or-category-title', keyword, language, 'category', 30000)); // 30 seconds for title
        promises.push(fetchSuggestionWithTimeout('seo-optimized-content', keyword, language, websiteName, 120000)); // 2 minutes for content - NOW WITH SECONDARY KEYWORDS
        promises.push(fetchSuggestionWithTimeout('category-permalink', keyword, language, websiteName, 30000)); // 30 seconds for permalink
    } else {
        // For pages/posts, fetch seo-optimized-content for page description
        console.log('🚀 DEBUG: Adding Page/Post SEO content API calls (may be slow)...');
        promises.push(fetchSuggestionWithTimeout('seo-optimized-content', keyword, language, websiteName, 120000)); // 2 minutes for content - NOW WITH SECONDARY KEYWORDS
    }

    console.log(`Prepared ${promises.length} promises for API calls.`);
    
    // Track promises for debugging and ensuring all complete
    const trackedPromises = promises.map((p, index) => {
        return p.catch(error => {
            console.error(`API call ${index} failed:`, error);
            // Return a specific error object or null to indicate failure
            return { error: true, message: error.message || 'Unknown error' };
        });
    });
    
    console.log('🚀 DEBUG: About to execute API promises:', trackedPromises.length);
    
    // Execute all appropriate API calls based on entity type using allSettled for partial failures
    Promise.allSettled(promises)
    .then((settledResults) => {
        // Clear timeout and progress timers
        clearTimeout(buttonResetTimeout);
        progressTimers.forEach(timer => clearTimeout(timer));
        
        console.log('🚀 DEBUG: All API promises settled, results array length:', settledResults.length);
        console.log('🚀 DEBUG: Settled results array:', settledResults);
        console.log('🚀 DEBUG: Entity type for processing results:', entityType);
        
        // Extract values and track success/failure
        const results = [];
        let successCount = 0;
        let failureCount = 0;
        
        settledResults.forEach((result, index) => {
            if (result.status === 'fulfilled') {
                results.push(result.value);
                successCount++;
                console.log(`🚀 DEBUG: API call ${index} succeeded:`, result.value);
            } else {
                results.push(''); // Empty string for failed calls
                failureCount++;
                console.warn(`🚀 DEBUG: API call ${index} failed:`, result.reason);
            }
        });
        
        console.log(`🚀 DEBUG: API Summary - Success: ${successCount}, Failures: ${failureCount}`);
        
        // Show appropriate toast message based on results
        if (typeof showToast === 'function') {
            if (failureCount === 0) {
                showToast('SEO suggestions generated successfully!', 'success');
            } else if (successCount > 0) {
                showToast(`APIs partially completed (${successCount} success, ${failureCount} failed). Fallbacks for empty fields.`, 'warning');
            } else {
                showToast('All APIs failed. Using local fallbacks.', 'info');
            }
        }
        
        // ⚡ CRITICAL FIX: Update fields IMMEDIATELY with extracted results
        console.log('🚀 DEBUG: Updating fields with processed results...');
        console.log('🔥🔥🔥 CRITICAL: Results received:', results);
        console.log('🔥🔥🔥 CRITICAL: EntityType:', entityType);
        
        if (entityType === 'Product') {
            const [metaTitle, metaKeywords, metaDescription, productTitle, productDescription, shortProductDescription, productPermalink] = results;
            
            updateSuggestedField('aysa-entity-meta-title', metaTitle);
            updateSuggestedField('aysa-entity-meta-keywords', metaKeywords);
            updateSuggestedField('aysa-entity-meta-description', metaDescription);
            updateSuggestedField('aysa-entity-product-title', productTitle);
            updateSuggestedField('aysa-entity-product-description', productDescription);
            updateSuggestedField('aysa-entity-product-short-description', shortProductDescription);
            updateSuggestedField('aysa-entity-product-permalink', productPermalink);
            
            updateSuggestionFields({
                secondKeyword,
                metaTitle,
                metaKeywords,
                metaDescription,
                productTitle,
                productDescription,
                shortProductDescription,
                productPermalink
            });
        } else if (entityType === 'Category') {
            console.log('🔥🔥🔥 CRITICAL: CATEGORY PROCESSING STARTED');
            const [metaTitle, metaKeywords, metaDescription, categoryTitle, categoryDescription, categoryPermalink] = results;
            
            updateSuggestedField('aysa-entity-meta-title', metaTitle);
            updateSuggestedField('aysa-entity-meta-keywords', metaKeywords);
            updateSuggestedField('aysa-entity-meta-description', metaDescription);
            updateSuggestedField('aysa-entity-category-title', categoryTitle);
            updateSuggestedField('aysa-entity-category-description', categoryDescription);
            updateSuggestedField('aysa-entity-category-permalink', categoryPermalink);
            
            console.log('🔥🔥🔥 CRITICAL: About to call updateSuggestionFields');
            updateSuggestionFields({
                secondKeyword,
                metaTitle,
                metaKeywords,
                metaDescription,
                categoryTitle,
                categoryDescription,
                categoryPermalink
            });
            console.log('🔥🔥🔥 CRITICAL: updateSuggestionFields called');
        } else {
            const [metaTitle, metaKeywords, metaDescription, pageContent] = results;
            

            updateSuggestedField('aysa-entity-meta-title', metaTitle);
            updateSuggestedField('aysa-entity-meta-keywords', metaKeywords);
            updateSuggestedField('aysa-entity-meta-description', metaDescription);
            updateSuggestedField('aysa-entity-content', pageContent);
            

            console.log('🚀 DEBUG: Rezultate API pentru Page/Post:', {
                secondKeyword,
                metaTitle,
                metaKeywords,
                metaDescription,
                pageContent
            });
            
            console.log('🚀 DEBUG: DETAILED PAGE CONTENT ANALYSIS:', {
                pageContentExists: !!pageContent,
                pageContentType: typeof pageContent,
                pageContentLength: pageContent ? pageContent.length : 0,
                pageContentIsString: typeof pageContent === 'string',
                pageContentTrimmed: pageContent && typeof pageContent === 'string' ? pageContent.trim() : 'N/A',
                pageContentTrimmedLength: pageContent && typeof pageContent === 'string' ? pageContent.trim().length : 0,
                pageContentHasError: pageContent && pageContent.error,
                pageContentPreview: pageContent && typeof pageContent === 'string' ? pageContent.substring(0, 200) + '...' : pageContent
            });
            
            updateSuggestionFields({
                secondKeyword,
                metaTitle,
                metaKeywords,
                metaDescription,
                pageContent
            });
        }
        
        // Function to handle the actual versioning after service is ready
        const performVersioning = (service) => {
            console.log('AYSA Versioning Service is ready, performing versioning.', service);
            if (entityType === 'Product') {
                if (service?.logSeoSuggestions) {
                    console.log('Attempting to record SEO suggestions for Product');
                    const versioningData = {
                        idIntern: entityId.toString(),
                        entityType: 'Product',
                        oldData: window.aysaPreSuggestionData || {},
                        newData: {
                            metaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
                            metaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
                            metaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
                            productDescription: document.getElementById('content')?.value || '',
                            shortProductDescription: document.getElementById('excerpt')?.value || '',
                            productPermalink: document.getElementById('editable-post-name')?.textContent || ''
                        },
                        projectId
                    };
                    console.log('Versioning data prepared for Product:', versioningData);
                    try {
                        service.logSeoSuggestions(versioningData);
                        console.log('Successfully called logSeoSuggestions for Product');
                    } catch (error) {
                        console.error('Error calling logSeoSuggestions for Product:', error);
                    }
                } else {
                    console.warn('Versioning service or logSeoSuggestions method not found for Product after event.');
                }
            } else if (entityType === 'Category') {
                if (service?.logSeoSuggestions) {
                    console.log('Attempting to record SEO suggestions for Category');
                    const versioningData = {
                        idIntern: entityId.toString(),
                        entityType: 'Category',
                        oldData: window.aysaPreSuggestionData || {},
                        newData: {
                            metaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
                            metaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
                            metaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
                            description: document.getElementById('description')?.value || ''
                        },
                        projectId
                    };
                    console.log('Versioning data prepared for Category:', versioningData);
                    try {
                        service.logSeoSuggestions(versioningData);
                        console.log('Successfully called logSeoSuggestions for Category');
                    } catch (error) {
                        console.error('Error calling logSeoSuggestions for Category:', error);
                    }
                } else {
                    console.warn('Versioning service or logSeoSuggestions method not found for Category after event.');
                }
            } else { // Other entity types
                if (service?.logSeoSuggestions) {
                    console.log('Attempting to record SEO suggestions for', entityType);
                    const versioningData = {
                        idIntern: entityId.toString(),
                        entityType,
                        oldData: window.aysaPreSuggestionData || {},
                        newData: {
                            metaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
                            metaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
                            metaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || ''
                        },
                        projectId
                    };
                    console.log('Versioning data prepared for', entityType, ':', versioningData);
                    try {
                        service.logSeoSuggestions(versioningData);
                        console.log('Successfully called logSeoSuggestions for', entityType);
                    } catch (error) {
                        console.error('Error calling logSeoSuggestions for', entityType, ':', error);
                    }
                } else {
                    console.warn('Versioning service or logSeoSuggestions method not found for', entityType, 'after event.');
                }
            }
            // Clear pre-suggestion data after versioning
            window.aysaPreSuggestionData = {};
            
            // ✅ SAVE KEYWORDS TO WORDPRESS: Save main keyword and secondary keywords after SEO generation
            console.log('💾 Saving keywords to WordPress after SEO generation...');
            const mainKeyword = document.getElementById('aysa-entity-keyword')?.value.trim() || keyword || '';
            const secondaryKeywordsValue = document.getElementById('aysa-entity-second-keyword')?.value || '';
            
            if (mainKeyword || secondaryKeywordsValue) {
                console.log('💾 Keywords to save:', {
                    entityId,
                    entityType,
                    mainKeyword,
                    secondaryKeywords: secondaryKeywordsValue
                });
                
                // Save keywords using the existing saveToWordPress function
                saveToWordPress(entityId, entityType, mainKeyword, secondaryKeywordsValue);
            } else {
                console.log('💾 No keywords to save');
            }
        };

        // Check if service is already available
        if (window.aysaVersioningService && typeof window.aysaVersioningService.logSeoSuggestions === 'function') {
            performVersioning(window.aysaVersioningService);
        } else {
            // Wait for the service to be ready
            console.log('AYSA Versioning Service not immediately available. Waiting for aysaVersioningServiceReady event...');
            document.addEventListener('aysaVersioningServiceReady', function onServiceReady(event) {
                performVersioning(event.detail);
                // Remove the listener after it has been called to avoid multiple executions
                document.removeEventListener('aysaVersioningServiceReady', onServiceReady);
            }, { once: true }); // Ensure the listener is called only once

            // Fallback timeout if the event is never dispatched (e.g., script loading error)
            setTimeout(() => {
                if (!(window.aysaVersioningService && typeof window.aysaVersioningService.logSeoSuggestions === 'function')) {
                    console.error('Timeout: AYSA Versioning Service did not become available.');
                    
                    // Still save keywords even if versioning failed
                    console.log('💾 Saving keywords to WordPress (versioning timeout fallback)...');
                    const mainKeyword = document.getElementById('aysa-entity-keyword')?.value.trim() || keyword || '';
                    const secondaryKeywordsValue = document.getElementById('aysa-entity-second-keyword')?.value || '';
                    
                    if (mainKeyword || secondaryKeywordsValue) {
                        saveToWordPress(entityId, entityType, mainKeyword, secondaryKeywordsValue);
                    }
                }
            }, 10000); // 10 seconds timeout
        }
    })
    .catch(error => {
        console.error('Error fetching suggestions:', error);
        if (typeof showToast === 'function') {
            showToast('Error generating suggestions. See console for details.', 'error');
        }
        
        // Still try to save keywords even if generation failed
        console.log('💾 Saving keywords to WordPress (error fallback)...');
        const mainKeyword = document.getElementById('aysa-entity-keyword')?.value.trim() || keyword || '';
        const secondaryKeywordsValue = document.getElementById('aysa-entity-second-keyword')?.value || '';
        
        if (mainKeyword || secondaryKeywordsValue) {
            saveToWordPress(entityId, entityType, mainKeyword, secondaryKeywordsValue);
        }
    })
    .finally(() => {
        // Clear progress timers and reset button state
        progressTimers.forEach(timer => clearTimeout(timer));
        
        // Reset force regeneration flag
        if (window.aysaForceRegeneratedSecondary !== undefined) {
            console.log('🔄 Resetting force regeneration flag');
            delete window.aysaForceRegeneratedSecondary;
        }
        
        // 🔓 RE-ENABLE ALL RELEVANT BUTTONS after SEO generation completes
        enableAllRelevantButtons();
        
        button.disabled = false;
        button.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle;">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
            </svg>
            Generate SEO Suggestions
        `;
        if (spinner) spinner.classList.remove('is-active');
        console.log('Generate Suggestions button reset.');
    });
}

/**
 * Fetch a suggestion with individual timeout
 * @param {string} type - Type of suggestion
 * @param {string} keyword - Main keyword
 * @param {string} language - Language code
 * @param {string} brandName - Brand name
 * @param {number} timeoutMs - Timeout in milliseconds
 * @returns {Promise<string>} The suggested text
 */
function fetchSuggestionWithTimeout(type, keyword, language, brandName, timeoutMs = 60000) {
    console.log(`🚀 DEBUG: fetchSuggestionWithTimeout called for ${type} with ${timeoutMs}ms timeout`);
    
    return Promise.race([
        fetchSuggestion(type, keyword, language, brandName),
        new Promise((_, reject) => {
            setTimeout(() => {
                console.warn(`⏰ API call for ${type} timed out after ${timeoutMs}ms`);
                reject(new Error(`Timeout after ${timeoutMs}ms for ${type}`));
            }, timeoutMs);
        })
    ]).catch(error => {
        console.warn(`⚠️ API call for ${type} failed:`, error.message);
        // Return empty string instead of throwing to allow other APIs to continue
        return '';
    });
}

/**
 * Fetch a suggestion from the API
 * @param {string} type - Type of suggestion (second-keyword, meta-title, etc.)
 * @param {string} keyword - Main keyword
 * @param {string} language - Language code
 * @param {string} brandName - Optional brand name for meta keywords
 * @returns {Promise<string>} The suggested text
 */
async function fetchSuggestion(type, keyword, language, brandName) {
    console.log(`DEBUG fetchSuggestion - Starting fetch for type: ${type}, keyword: ${keyword}`);
    
    // Get project ID for API calls using robust function
    const projectId = getProjectId();
    
    // Get additional data from database for enhanced payloads
    const generalInfo = await getGeneralInformation();
    const toneOfVoice = await getToneOfVoice();
    const publicUrl = getEntityPublicUrl();
    
    console.log('📊 Enhanced payload data:');
    console.log('  - General info:', generalInfo);
    console.log('  - Tone of voice:', toneOfVoice);
    console.log('  - Public URL:', publicUrl);
    
    let data = null;

    // Build broker payload by suggestion type
    switch (type) {
        case 'second-keyword':
            data = {
                location_code: 2642,
                language_code: (language || 'ro').toLowerCase(),
                seed_keywords: [keyword]
            };
            break;
        case 'meta-title':
            data = {
                language: language || 'en',
                pageType: getEntityTypeGood() || 'product',
                domain: window.location.origin,
                primaryKeyword: keyword,
                secondaryKeywords: getSecondaryKeywords(),
                relatedKeywords: [],
                targetAudience: document.getElementById('targeted_se')?.value || '',
                searchIntent: document.getElementById('update_frequency')?.value || '',
                city: document.getElementById('targeted_city')?.value || '',
                brandName: (generalInfo?.brand) || brandName || document.title.split(' | ')[1] || '',
                projectId: projectId
            };
            break;
        case 'meta-keywords':
            data = {
                language: language || 'en',
                pageType: getEntityTypeGood() || 'product',
                domain: window.location.origin,
                primaryKeyword: keyword,
                secondaryKeywords: getSecondaryKeywords(),
                relatedKeywords: [],
                projectId: projectId
            };
            break;
        case 'meta-description':
            data = {
                language: language || 'en',
                pageType: getEntityTypeGood() || 'product',
                domain: window.location.origin,
                primaryKeyword: keyword,
                secondaryKeywords: getSecondaryKeywords(),
                relatedKeywords: [],
                targetAudience: document.getElementById('targeted_se')?.value || '',
                searchIntent: document.getElementById('update_frequency')?.value || '',
                city: document.getElementById('targeted_city')?.value || '',
                brandName: (generalInfo?.brand) || brandName || document.title.split(' | ')[1] || '',
                projectId: projectId
            };
            break;
        case 'seo-optimized-content':
            const secondaryKeywordsForContent = getSecondaryKeywords();
            console.log('🚀 DEBUG: Secondary keywords for seo-optimized-content:', secondaryKeywordsForContent);
            data = {
                language: language || 'en',
                pageType: getEntityTypeGood() || 'product',
                domain: window.location.origin,
                primaryKeyword: keyword,
                secondaryKeywords: secondaryKeywordsForContent,
                relatedKeywords: [],
                minimumWordCount: 300,
                documentOutline: [],
                includeTldr: false,
                numberOfImages: 0,
                city: document.getElementById('targeted_city')?.value || '',
                paymentMethods: generalInfo?.paymentMethods ? generalInfo.paymentMethods.split(',').map(p => p.trim()).filter(p => p) : [],
                deliveryMethods: generalInfo?.shippingOptions ? generalInfo.shippingOptions.split(',').map(d => d.trim()).filter(d => d) : [],
                tone: toneOfVoice || '',
                targetAudience: document.getElementById('targeted_se')?.value || '',
                searchIntent: document.getElementById('update_frequency')?.value || '',
                existingPageContent: false,
                pageUrl: publicUrl,
                websiteContext: document.title || '',
                brandName: (generalInfo?.brand) || brandName || document.title.split(' | ')[1] || '',
                includeFaq: true,
                includeFaqSchema: true,
                competitorUrls: [],
                projectId: projectId
            };
            
            // Add attributes for product pages only
            console.log('🔍 [DEBUG] Entity type check:', getEntityTypeGood());
            if (getEntityTypeGood() === 'Product') {
                const attributes = getProductAttributes();
                data.attributes = attributes;
                console.log('✅ Added product attributes to seo-optimized-content request:', attributes);
                console.log('✅ Full data object with attributes:', data);
            } else {
                console.log('❌ Not a product page, skipping attributes');
            }
            
            console.log('🚀 DEBUG: Using seo-optimized-content endpoint with secondary keywords:', secondaryKeywordsForContent);
            break;
        case 'product-description':
            data = {
                language: language || 'en',
                pageType: getEntityTypeGood() || 'product',
                domain: window.location.origin,
                primaryKeyword: keyword,
                secondaryKeywords: getSecondaryKeywords(),
                relatedKeywords: [],
                minimumWordCount: 300,
                documentOutline: [],
                includeTldr: false,
                numberOfImages: 0,
                city: document.getElementById('targeted_city')?.value || '',
                paymentMethods: [],
                deliveryMethods: [],
                tone: '',
                targetAudience: document.getElementById('targeted_se')?.value || '',
                searchIntent: document.getElementById('update_frequency')?.value || '',
                existingPageContent: false,
                pageUrl: window.location.href,
                websiteContext: document.title || '',
                brandName: brandName || document.title.split(' | ')[1] || '',
                includeFaq: true,
                includeFaqSchema: true,
                competitorUrls: [],
                projectId: projectId
            };
            console.log('🔍 [DEBUG] Entity type check for product-description:', getEntityTypeGood());
            if (getEntityTypeGood() === 'Product') {
                const attributes = getProductAttributes();
                data.attributes = attributes;
                console.log('✅ Added product attributes to product-description request:', attributes);
                console.log('✅ Full data object with attributes:', data);
            } else {
                console.log('❌ Not a product page, skipping attributes for product-description');
            }
            break;
        case 'product-short-description':
            data = {
                language: language || 'en',
                pageType: getEntityTypeGood() || 'product',
                domain: window.location.origin,
                primaryKeyword: keyword,
                secondaryKeywords: getSecondaryKeywords(),
                relatedKeywords: [],
                city: document.getElementById('targeted_city')?.value || '',
                tone: toneOfVoice || '',
                targetAudience: document.getElementById('targeted_se')?.value || '',
                searchIntent: document.getElementById('update_frequency')?.value || '',
                existingPageContent: false,
                pageUrl: publicUrl,
                websiteContext: document.title || '',
                brandName: (generalInfo?.brand) || brandName || document.title.split(' | ')[1] || '',
                projectId: projectId
            };
            console.log('🔍 [DEBUG] Entity type check for product-short-description:', getEntityTypeGood());
            if (getEntityTypeGood() === 'Product') {
                const attributes = getProductAttributes();
                data.attributes = attributes;
                console.log('✅ Added product attributes to product-short-description request:', attributes);
                console.log('✅ Full data object with attributes:', data);
            } else {
                console.log('❌ Not a product page, skipping attributes for product-short-description');
            }
            break;
        case 'product-permalink':
            data = {
                language: language || 'ro',
                pageType: 'product',
                domain: window.location.origin,
                primaryKeyword: keyword,
                projectId: projectId
            };
            break;
        case 'category-permalink':
            data = {
                language: language || 'ro',
                pageType: 'category',
                domain: window.location.origin,
                primaryKeyword: keyword,
                projectId: projectId
            };
            break;
        case 'product-or-category-title':
            const pageType = brandName || 'product'; // brandName is used to pass page_type
            data = {
                language: language || 'ro',
                pageType: pageType,
                domain: window.location.origin,
                primaryKeyword: keyword,
                projectId: projectId
            };
            break;
        default:
            console.warn(`DEBUG fetchSuggestion - Unknown suggestion type: ${type}`);
            return Promise.resolve('');
    }

    // Helper function to get secondary keywords
    function getSecondaryKeywords() {
        const secondKeywordInput = document.getElementById('aysa-entity-second-keyword');
        if (secondKeywordInput && secondKeywordInput.value) {
            return secondKeywordInput.value.split(',').map(k => k.trim()).filter(k => k);
        }
        return [];
    }

    const ajaxUrl = (typeof aysaParams !== 'undefined' && aysaParams.ajax_url) ? aysaParams.ajax_url : (window.ajaxurl || '/wp-admin/admin-ajax.php');
    const nonce = (typeof aysaParams !== 'undefined' && aysaParams.nonce) ? aysaParams.nonce : '';

    const postAjax = async (params) => {
        const body = new URLSearchParams(params);
        const response = await fetch(ajaxUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            body: body.toString(),
            credentials: 'same-origin'
        });
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        const result = await response.json();
        if (!result || !result.success) {
            throw new Error((result && result.data && (result.data.message || result.data)) ? String(result.data.message || result.data) : 'Metabox async request failed');
        }
        return result.data;
    };

    const pollAsync = async (task, runId, tries = 40) => {
        const status = await postAjax({
            action: 'aysa_metabox_async_status',
            nonce,
            task,
            run_id: runId || ''
        });
        if (status && status.status === 'completed' && status.result) {
            return status.result;
        }
        if (status && status.status === 'failed') {
            throw new Error(String(status.error || 'Metabox worker failed.'));
        }
        if (tries <= 0) {
            throw new Error('Metabox worker timed out.');
        }
        await new Promise((resolve) => window.setTimeout(resolve, 2000));
        return pollAsync(task, runId, tries - 1);
    };

    const form = new URLSearchParams();
    form.append('action', 'aysa_metabox_async_start');
    form.append('nonce', nonce);
    form.append('task', 'seo_suggestion');
    form.append('type', type);
    form.append('keyword', keyword || '');
    form.append('language', language || 'ro');
    form.append('brand_name', (generalInfo?.brand) || brandName || '');
    form.append('project_id', String(projectId || 0));
    form.append('payload', JSON.stringify(data || {}));

    try {
        const started = await postAjax(Object.fromEntries(form.entries()));
        const result = (started && started.status === 'completed' && started.result)
            ? started.result
            : await pollAsync('seo_suggestion', started && started.run_id ? started.run_id : '');

        if (result && typeof result.suggestion === 'string') {
            return result.suggestion;
        }

        if (result && result.response) {
            return processApiResponse(type, result.response);
        }

        return '';
    } catch (error) {
        console.error(`Error fetching ${type} via metabox async ajax:`, error);
        return '';
    }
}

/**
 * Process API response based on type
 * @param {string} type - Type of suggestion (meta-title, meta-description, etc.)
 * @param {object} response - API response
 * @returns {string} Processed response value
 */
function processApiResponse(type, response) {
    console.log(`Processing API response for ${type}:`, response);
    
    // For new POST-based ChatGPT endpoints
    if (type === 'meta-title' || type === 'meta-description' || type === 'meta-keywords') {
        console.log(`Processing ${type} response:`, response);
        
        // Check if we have a valid response
        if (!response) return '';
        
        // Handle the new response structure
        if (typeof response === 'object') {
            // For new ChatGPT endpoints
            switch (type) {
                case 'meta-title':
                    return response.seoMetaTitle || '';
                case 'meta-description':
                    return response.seoMetaDescription || '';
                case 'meta-keywords':
                    return response.seoMetaKeywords || '';
                default:
                    return '';
            }
        } else if (typeof response === 'string') {
            // Fall back to string response if that's what we get
            return response;
        }
        
        return '';
    }
    
    // Handle product-or-category-title response
    if (type === 'product-or-category-title') {
        console.log(`🔥 Processing ${type} response:`, response);
        
        if (!response) {
            console.warn(`🔥 No response for ${type}`);
            return '';
        }
        
        if (typeof response === 'object') {
            // Try to extract the title from various possible response properties
            if (response.title) {
                console.log(`🔥 Found title in ${type} response:`, response.title);
                return response.title;
            } else if (response.productTitle) {
                console.log(`🔥 Found productTitle in ${type} response:`, response.productTitle);
                return response.productTitle;
            } else if (response.categoryTitle) {
                console.log(`🔥 Found categoryTitle in ${type} response:`, response.categoryTitle);
                return response.categoryTitle;
            } else if (response.name) {
                console.log(`🔥 Found name in ${type} response:`, response.name);
                return response.name;
            } else {
                // Try to stringify the object if we can't find expected properties
                console.warn(`🔥 No recognized properties in ${type} response object:`, Object.keys(response));
                const jsonString = JSON.stringify(response);
                if (jsonString && jsonString !== '{}' && jsonString !== '[]') {
                    console.log(`🔥 Using JSON string for ${type}:`, jsonString);
                    return jsonString;
                }
            }
        } else if (typeof response === 'string' && response.trim() !== '') {
            // Fall back to string response if that's what we get
            console.log(`🔥 String response for ${type}:`, response);
            return response.trim();
        }
        
        console.warn(`🔥 Could not extract valid title from ${type} response`);
        return '';
    }
    
    // Handle full product description from seo-optimized-content endpoint
    if (type === 'product-description' || type === 'seo-optimized-content') {
        console.log(`Processing ${type} response:`, response);
        
        if (!response) return '';
        
        let contentToProcess = '';
        
        if (typeof response === 'object') {
            // Extract the optimized content from the response
            if (response.seoOptimizedContent) {
                console.log('Found seoOptimizedContent in response');
                contentToProcess = response.seoOptimizedContent;
            } else if (response.content || response.htmlContent) {
                console.log('Found content/htmlContent in response');
                contentToProcess = response.content || response.htmlContent;
            } else {
                // Try to stringify the object if we can't find expected properties
                console.log('No recognized properties in seo-optimized-content response, using JSON.stringify');
                const jsonString = JSON.stringify(response);
                if (jsonString && jsonString !== '{}' && jsonString !== '[]') {
                    contentToProcess = jsonString;
                }
            }
        } else if (typeof response === 'string') {
            // Fall back to string response if that's what we get
            console.log('String response for seo-optimized-content:', response);
            contentToProcess = response;
        }
        
        if (contentToProcess) {
            // For seo-optimized-content, return raw content with H1 intact
            // The updateSuggestionFields function will extract H1 for product title
            // and then remove H1 tags from the content before updating description fields
            if (type === 'seo-optimized-content') {
                console.log('Returning raw seo-optimized-content with H1 intact for title extraction');
                return contentToProcess;
            } else {
                // For other types, remove h1 tags from the content
                return removeH1Tags(contentToProcess);
            }
        }
        
        console.warn('Could not extract valid content from seo-optimized-content response');
        return '';
    }
    
    // Handle short-optimized-content response
    if (type === 'product-short-description') {
        console.log(`Processing ${type} response:`, response);
        
        if (!response) return '';
        
        let contentToProcess = '';
        
        if (typeof response === 'object') {
            // Extract the short optimized content from the response
            if (response.shortOptimizedContent) {
                console.log('Found shortOptimizedContent in response:', response.shortOptimizedContent);
                contentToProcess = response.shortOptimizedContent;
            } else if (response.content) {
                console.log('Found content in response:', response.content);
                contentToProcess = response.content;
            } else {
                // Try to stringify the object if we can't find expected properties
                console.log('No recognized properties in short-optimized-content response, using JSON.stringify');
                const jsonString = JSON.stringify(response);
                if (jsonString && jsonString !== '{}' && jsonString !== '[]') {
                    contentToProcess = jsonString;
                }
            }
        } else if (typeof response === 'string') {
            // Fall back to string response if that's what we get
            console.log('String response for short-optimized-content:', response);
            contentToProcess = response;
        }
        
        if (contentToProcess) {
            // Remove h1 tags from the content
            return removeH1Tags(contentToProcess);
        }
        
        console.warn('Could not extract valid content from short-optimized-content response');
        return '';
    }
    

    
    // Handle both product and category permalinks from the seo-friendly-url endpoint
    if (type === 'product-permalink' || type === 'category-permalink') {
        console.log(`Processing ${type} response:`, response);
        
        if (!response) return '';
        
        if (typeof response === 'object') {
            // Extract the SEO friendly URL from the response
            if (response.seoFriendlyUrl) {
                console.log(`Found seoFriendlyUrl in ${type} response:`, response.seoFriendlyUrl);
                return response.seoFriendlyUrl;
            } else if (response.slug) {
                console.log(`Found slug in ${type} response:`, response.slug);
                return response.slug;
            } else {
                // Try to stringify the object if we can't find expected properties
                console.log(`No recognized properties in ${type} response object, using JSON.stringify`);
                const jsonString = JSON.stringify(response);
                if (jsonString && jsonString !== '{}' && jsonString !== '[]') {
                    return jsonString;
                }
            }
        } else if (typeof response === 'string') {
            // Fall back to string response if that's what we get
            console.log(`String response for ${type}:`, response);
            return response;
        }
        
        console.warn(`Could not extract valid permalink from ${type} response`);
        return '';
    }
    
    // For existing GET-based endpoints
    return response;
}

/**
 * Remove h1 tags from content with their text completely
 * @param {string} content - The HTML content to process
 * @returns {string} Content with h1 tags and their content completely removed
 */
function removeH1Tags(content) {
    if (!content || typeof content !== 'string') {
        console.log('🔥 removeH1Tags: Invalid content provided:', { content, type: typeof content });
        return content;
    }
    
    console.log('🔥 removeH1Tags: Starting H1 removal process');
    console.log('🔥 removeH1Tags: Original content length:', content.length);
    console.log('🔥 removeH1Tags: Original content preview:', content.substring(0, 200) + '...');
    
    // ✅ FIRST: Remove H1 blocks from Gutenberg editor if present
    removeGutenbergH1Blocks();
    
    // ✅ ENHANCED: Multiple regex patterns for robust H1 removal
    let processedContent = content;
    
    // Pattern 1: Complete H1 tags with all their content (most common)
    processedContent = processedContent.replace(/<h1[^>]*>.*?<\/h1>/gis, '');
    console.log('🔥 removeH1Tags: After pattern 1 (complete H1 tags)');
    
    // Pattern 2: Remove any remaining H1 opening tags
    processedContent = processedContent.replace(/<h1[^>]*>/gi, '');
    console.log('🔥 removeH1Tags: After pattern 2 (remaining opening tags)');
    
    // Pattern 3: Remove any remaining H1 closing tags
    processedContent = processedContent.replace(/<\/h1>/gi, '');
    console.log('🔥 removeH1Tags: After pattern 3 (remaining closing tags)');
    
    // Pattern 4: Clean up empty lines and extra whitespace
    processedContent = processedContent.replace(/\n\s*\n\s*\n/g, '\n\n');
    processedContent = processedContent.replace(/^\s*\n+/, '');
    processedContent = processedContent.replace(/\n+\s*$/, '');
    processedContent = processedContent.trim();
    
    console.log('🔥 removeH1Tags: After cleanup - final content length:', processedContent.length);
    console.log('🔥 removeH1Tags: Final content preview:', processedContent.substring(0, 200) + '...');
    
    // ✅ VALIDATION: Final check for any remaining H1 tags
    const stillHasH1 = processedContent.includes('<h1') || processedContent.includes('</h1>');
    
    if (stillHasH1) {
        console.error('🔥❌ removeH1Tags: H1 still present! Applying emergency removal...');
        
        // Emergency: remove any line containing H1
        const lines = processedContent.split('\n');
        const cleanLines = lines.filter(line => !line.includes('<h1') && !line.includes('</h1>'));
        processedContent = cleanLines.join('\n').trim();
        
        console.log('🔥🚨 removeH1Tags: Emergency line removal applied');
        console.log('🔥 removeH1Tags: Final emergency content length:', processedContent.length);
    } else {
        console.log('🔥✅ removeH1Tags: H1 successfully removed');
    }
    
    return processedContent;
}

/**
 * Remove H1 blocks from Gutenberg editor
 */
function removeGutenbergH1Blocks() {
    console.log('🔥 removeGutenbergH1Blocks: Starting Gutenberg H1 block removal');
    
    try {
        // Method 1: Use WordPress Block Editor API if available
        if (typeof wp !== 'undefined' && wp.data && wp.data.select && wp.data.dispatch) {
            const blocks = wp.data.select('core/block-editor').getBlocks();
            const h1Blocks = blocks.filter(block => block.name === 'core/heading' && block.attributes.level === 1);
            
            if (h1Blocks.length > 0) {
                console.log('🔥 removeGutenbergH1Blocks: Found', h1Blocks.length, 'H1 blocks via WordPress API');
                
                h1Blocks.forEach(block => {
                    console.log('🔥 removeGutenbergH1Blocks: Removing H1 block with clientId:', block.clientId);
                    wp.data.dispatch('core/block-editor').removeBlocks([block.clientId]);
                });
                
                showToast('H1 blocks removed from content', 'success');
                return true;
            }
        }
        
        // Method 2: Direct DOM manipulation for Gutenberg H1 elements
        const gutenbergH1Elements = document.querySelectorAll([
            'h1[data-type="core/heading"]',
            'h1.wp-block-heading',
            'h1.block-editor-rich-text__editable',
            '.wp-block-heading h1',
            '[data-type="core/heading"] h1'
        ].join(', '));
        
        if (gutenbergH1Elements.length > 0) {
            console.log('🔥 removeGutenbergH1Blocks: Found', gutenbergH1Elements.length, 'H1 elements via DOM');
            
            gutenbergH1Elements.forEach((h1Element, index) => {
                console.log('🔥 removeGutenbergH1Blocks: Processing H1 element', index + 1);
                
                // Find the parent block container
                let blockContainer = h1Element.closest([
                    '[data-type="core/heading"]',
                    '.wp-block-heading',
                    '.block-editor-block-list__block'
                ].join(', '));
                
                if (blockContainer) {
                    console.log('🔥 removeGutenbergH1Blocks: Removing H1 block container');
                    blockContainer.remove();
                } else {
                    console.log('🔥 removeGutenbergH1Blocks: Removing H1 element directly');
                    h1Element.remove();
                }
            });
            
            showToast('H1 elements removed from content', 'success');
            return true;
        }
        
        // Method 3: Check for contenteditable H1 elements (like the one from the user)
        const contentEditableH1 = document.querySelectorAll('h1[contenteditable="true"]');
        if (contentEditableH1.length > 0) {
            console.log('🔥 removeGutenbergH1Blocks: Found', contentEditableH1.length, 'contenteditable H1 elements');
            
            contentEditableH1.forEach((h1Element, index) => {
                console.log('🔥 removeGutenbergH1Blocks: Removing contenteditable H1 element', index + 1);
                
                // Find parent block
                let parentBlock = h1Element.closest('.wp-block, .block-editor-block-list__block');
                if (parentBlock) {
                    parentBlock.remove();
                } else {
                    h1Element.remove();
                }
            });
            
            showToast('Contenteditable H1 elements removed', 'success');
            return true;
        }
        
        console.log('🔥 removeGutenbergH1Blocks: No H1 blocks found in editor');
        return false;
        
    } catch (error) {
        console.error('🔥❌ removeGutenbergH1Blocks: Error removing H1 blocks:', error);
        showToast('Error removing H1 blocks: ' + error.message, 'error');
        return false;
    }
}

/**
 * Update the suggested secondary keywords field and properly handle errors
 * @param {string} fieldId - Element ID to update
 * @param {string} value - Value to set
 */
function updateSuggestedField(fieldId, value) {
    console.log(`DEBUG: updateSuggestedField called for field ${fieldId} with value:`, value);
    
    // For backward compatibility, convert ID format if needed
    const actualFieldId = fieldId.startsWith('aysa-entity-suggested-') 
        ? fieldId.replace('aysa-entity-suggested-', 'aysa-entity-')
        : fieldId;
    
    console.log(`DEBUG: Looking for field with ID: ${actualFieldId}`);
    const field = document.getElementById(actualFieldId);
    
    if (!field) {
        console.error(`DEBUG: Could not find field with ID: ${actualFieldId}`);
        console.log('DEBUG: Available form fields in DOM:', 
            Array.from(document.querySelectorAll('input, textarea, select')).map(el => ({
                id: el.id,
                name: el.name,
                type: el.type || el.tagName
            }))
        );
        return;
    }
    
    console.log(`DEBUG: Found field ${actualFieldId}, current value: "${field.value}"`);
    console.log(`DEBUG: About to set new value: "${value}"`);
    
    
    // Clear any existing error messages
    field.classList.remove('has-error');
    const errorMsgEl = field.parentNode.querySelector('.error-message');
    if (errorMsgEl) {
        errorMsgEl.remove();
    }
    
    // If value is empty string, show a better message in the field
    if (!value || value.trim() === '') {
        // IMPORTANT: Clear the field instead of showing the error message
        field.value = '';
        field.classList.add('has-error');
        
        // Add a more helpful error message below the field
        const errorMsg = document.createElement('div');
        errorMsg.className = 'error-message';
        errorMsg.style.color = '#d63638';
        errorMsg.style.fontSize = '12px';
        errorMsg.style.marginTop = '5px';
        
        // For secondary keywords specifically, add some fallback directly
        if (actualFieldId === 'aysa-entity-second-keyword') {
            // Hide the error container completely for secondary keywords
            field.parentNode.style.position = 'relative';
            
            // Create a special message for secondary keywords
            errorMsg.innerHTML = 'Generating alternative keywords...';
            
            // We'll generate and add some fallback keywords directly
            const entityType = getEntityTypeGood();
            const keyword = document.getElementById('aysa-entity-keyword').value;
            
            // Generate fallback keywords asynchronously
            setTimeout(() => {
                const fallbackKeywords = generateFallbackKeywords(keyword, entityType);
                
                // Update the message to indicate we're using generated keywords
                errorMsg.innerHTML = 'Using automatically generated keywords';
                
                // Process the keywords with proper modal support
                const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
                if (secondaryKeywordInput) {
                    secondaryKeywordInput.value = fallbackKeywords;
                    
                    // Use proper rendering function with modal support
                    if (typeof window.renderSecondaryKeywordTags === 'function') {
                        console.log('🔥 Fallback: Using window.renderSecondaryKeywordTags (WITH MODAL SUPPORT)');
                        window.renderSecondaryKeywordTags();
                    } else if (typeof renderSecondaryKeywordTags === 'function') {
                        console.log('🔥 Fallback: Using global renderSecondaryKeywordTags (WITH MODAL SUPPORT)');
                        renderSecondaryKeywordTags();
                    } else {
                        console.log('🔥 Fallback: renderSecondaryKeywordTags not available, using manual function');
                        renderSecondaryKeywordTagsManually(fallbackKeywords);
                    }
                }
            }, 500);
        } else {
            // For other fields, show a generic message
            errorMsg.textContent = 'Nu există sugestii disponibile pentru acest câmp.';
        }
        
        field.parentNode.appendChild(errorMsg);
    } else {
        // Normal case - set the value
        field.value = value;
        console.log(`DEBUG: Successfully set field ${actualFieldId} value to: "${value}"`);
        console.log(`DEBUG: Field value after setting: "${field.value}"`);
        
        // Highlight the field to draw attention
        field.style.backgroundColor = '#f7ffde';
        setTimeout(() => {
            field.style.backgroundColor = '';
        }, 1500);
    }
}



/**
 * Update suggestion fields in the form
 * @param {Object} suggestions - Object containing suggestion fields
 */
function updateSuggestionFields(suggestions) {
    console.log("🚀 DEBUG: updateSuggestionFields CALLED with suggestions:", suggestions);
    console.log("🔥🔥🔥 CRITICAL: updateSuggestionFields ENTRY POINT");
    
    const { 
        secondKeyword, 
        metaTitle, 
        metaKeywords, 
        metaDescription,
        productTitle, // Product title from new API
        productDescription,
        shortProductDescription,
        categoryTitle, // Category title from new API
        categoryDescription, // Added for category
        categoryPermalink, // Added for category permalink
        productPermalink,
        pageContent // Added for pages/posts content
    } = suggestions;
    
    // Debug entity type and category description
    const entityType = getEntityTypeGood();
    console.log("🔥 DEBUG: Entity type detected:", entityType);
    console.log("🔥 DEBUG: Category description data:", {
        hasCategoryDescription: !!categoryDescription,
        categoryDescriptionType: typeof categoryDescription,
        categoryDescriptionLength: categoryDescription ? categoryDescription.length : 0,
        categoryDescriptionValue: categoryDescription ? categoryDescription.substring(0, 100) + '...' : 'null/undefined'
    });
    
    // Debug which condition we'll enter for categories
    if (entityType === 'Category') {
        console.log("🔥 DEBUG: We are in Category mode");
        if (categoryDescription && typeof categoryDescription === 'string' && categoryDescription.trim() !== '' && !categoryDescription.error) {
            console.log("🔥 DEBUG: Will enter main category processing (has content)");
        } else if (categoryDescription && categoryDescription.error) {
            console.log("🔥 DEBUG: Will enter category error fallback");
        } else {
            console.log("🔥 DEBUG: Will enter category no-content fallback");
        }
    }
    
    console.log("🚀 DEBUG: Destructured values:", {
        secondKeyword, 
        metaTitle, 
        metaKeywords, 
        metaDescription,
        productDescription,
        shortProductDescription,
        categoryDescription,
        categoryPermalink,
        productPermalink 
    });
    
    console.log("🚀 DEBUG: Starting field updates...");
    console.log("🚀 DEBUG: Available DOM fields check:");
    console.log("- aysa-entity-second-keyword:", document.getElementById('aysa-entity-second-keyword') ? "FOUND" : "NOT FOUND");
    console.log("- aysa-entity-meta-title:", document.getElementById('aysa-entity-meta-title') ? "FOUND" : "NOT FOUND");
    console.log("- aysa-entity-meta-keywords:", document.getElementById('aysa-entity-meta-keywords') ? "FOUND" : "NOT FOUND");
    console.log("- aysa-entity-meta-description:", document.getElementById('aysa-entity-meta-description') ? "FOUND" : "NOT FOUND");

    // ✅ FIX: Declare newKeywords at function scope to avoid ReferenceError
    let newKeywords = [];

    // Update second keyword field
    if (secondKeyword && typeof secondKeyword === 'string' && secondKeyword.trim() !== '' && !secondKeyword.error) {
        console.log('DEBUG: Processing secondKeyword:', secondKeyword);
        
        // ✅ FIX: Check if we should replace or merge secondary keywords
        const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
        if (secondaryKeywordInput) {
            // Check if force regenerate was used (checkbox was checked during generation)
            const wasForceRegenerated = window.aysaForceRegeneratedSecondary || false;
            
            // Get existing keywords (only needed for merge mode)
            const existingKeywordsStr = secondaryKeywordInput.value.trim();
            const existingKeywords = wasForceRegenerated ? [] : 
                (existingKeywordsStr ? existingKeywordsStr.split(',').map(k => k.trim()).filter(k => k !== '') : []);
            
            // Get new suggested keywords
            const suggestedKeywords = secondKeyword.split(',')
                .map(k => k.trim())
                .filter(k => k !== '');
            
            // Get main keyword to exclude from secondary keywords
            const mainKeyword = document.getElementById('aysa-entity-keyword')?.value.trim() || '';
            
            // Filter out main keyword and (if merging) duplicates
            if (wasForceRegenerated) {
                // Replace mode: only filter out main keyword
                newKeywords = suggestedKeywords.filter(k => k !== mainKeyword);
                console.log('DEBUG: Force regenerate 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('DEBUG: Merge mode - adding new keywords to existing ones');
            }
            
            // Combine keywords based on mode
            const allKeywords = wasForceRegenerated ? newKeywords : [...existingKeywords, ...newKeywords];
            const finalKeywords = allKeywords.join(', ');
            
            console.log('DEBUG: Was force regenerated:', wasForceRegenerated);
            console.log('DEBUG: Existing secondary keywords:', existingKeywords);
            console.log('DEBUG: New suggested keywords:', suggestedKeywords);
            console.log('DEBUG: Keywords being processed:', newKeywords);
            console.log('DEBUG: Final keywords:', finalKeywords);
            
            // Update the field with final keywords
            secondaryKeywordInput.value = finalKeywords;
            
            // Show user feedback based on mode
            if (newKeywords.length > 0) {
                if (typeof showToast === 'function') {
                    if (wasForceRegenerated) {
                        showToast(`Replaced all secondary keywords with ${newKeywords.length} new ones.`, 'success');
                    } else {
                        showToast(`Added ${newKeywords.length} new secondary keywords. Existing keywords preserved.`, 'success');
                    }
                }
            } else {
                if (typeof showToast === 'function') {
                    showToast('All suggested secondary keywords already exist.', 'info');
                }
            }
            
            // ✅ CRITICAL FIX: Always render visual tags after keyword processing, regardless of new/existing status
            console.log('🔥 ENSURING VISUAL TAGS ARE RENDERED after keyword merge...');
            if (secondaryKeywordInput && secondaryKeywordInput.value.trim()) {
                console.log('🔥 Keywords to render visually:', secondaryKeywordInput.value.trim());
                
                // Try to use proper rendering function first (with modal support)
                if (typeof window.renderSecondaryKeywordTags === 'function') {
                    console.log('🔥 Using window.renderSecondaryKeywordTags (WITH MODAL SUPPORT)');
                    window.renderSecondaryKeywordTags();
                } else if (typeof renderSecondaryKeywordTags === 'function') {
                    console.log('🔥 Using global renderSecondaryKeywordTags (WITH MODAL SUPPORT)');
                    renderSecondaryKeywordTags();
                } else {
                    console.log('🔥 Using manual rendering fallback');
                    renderSecondaryKeywordTagsManually(secondaryKeywordInput.value.trim());
                }
            } else {
                console.log('🔥 No keywords to render visually');
            }
        } else {
            // Fallback to original behavior if input not found
            updateSuggestedField('aysa-entity-second-keyword', secondKeyword);
        }
        
        // ✅ REMOVED: No longer needed - visual rendering is handled above consistently
        // The old logic was unreliable and sometimes failed to render tags
    } else if (secondKeyword && secondKeyword.error) {
        console.warn("Failed to fetch second keyword:", secondKeyword.message);
    } else {
        console.log('DEBUG: secondKeyword is empty, null, or invalid:', secondKeyword, typeof secondKeyword);
        // Generate fallback secondary keywords if no valid API response
        const keyword = document.getElementById('aysa-entity-keyword')?.value;
        if (keyword) {
            const fallbackKeywords = generateFallbackKeywords(keyword, getEntityTypeGood());
            console.log('DEBUG: Using fallback secondary keywords:', fallbackKeywords);
            
            // ✅ FIX: Also merge fallback keywords with existing ones
            const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
            newKeywords = []; // Reset newKeywords for use later
            if (secondaryKeywordInput) {
                const existingKeywordsStr = secondaryKeywordInput.value.trim();
                const existingKeywords = existingKeywordsStr ? 
                    existingKeywordsStr.split(',').map(k => k.trim()).filter(k => k !== '') : 
                    [];
                
                const suggestedKeywords = fallbackKeywords.split(',')
                    .map(k => k.trim())
                    .filter(k => k !== '');
                
                const mainKeyword = document.getElementById('aysa-entity-keyword')?.value.trim() || '';
                newKeywords = suggestedKeywords.filter(k => 
                    k !== mainKeyword && !existingKeywords.includes(k)
                );
                
                const allKeywords = [...existingKeywords, ...newKeywords];
                secondaryKeywordInput.value = allKeywords.join(', ');
            } else {
                updateSuggestedField('aysa-entity-second-keyword', fallbackKeywords);
            }
            
            // Also render the fallback keywords as tags
            // ✅ FIX: Always render tags even if no new fallback keywords were added
            console.log('🔥 USING PROPER RENDER FUNCTION for fallback keywords with modal support');
            if (secondaryKeywordInput) {
                const finalKeywordsStr = secondaryKeywordInput.value.trim();
                if (finalKeywordsStr) {
                    // Use proper rendering function with modal support
                    if (typeof window.renderSecondaryKeywordTags === 'function') {
                        console.log('🔥 Fallback tags: Using window.renderSecondaryKeywordTags (WITH MODAL SUPPORT)');
                        window.renderSecondaryKeywordTags();
                    } else if (typeof renderSecondaryKeywordTags === 'function') {
                        console.log('🔥 Fallback tags: Using global renderSecondaryKeywordTags (WITH MODAL SUPPORT)');
                        renderSecondaryKeywordTags();
                    } else {
                        console.log('🔥 Fallback tags: renderSecondaryKeywordTags not available, using manual function');
                        renderSecondaryKeywordTagsManually(finalKeywordsStr);
                    }
                } else {
                    console.log('🔥 No fallback keywords to render');
                }
            } else {
                console.log('🔥 No secondary keyword input found for fallback');
            }
        }
    }

    // Update meta title field
    if (metaTitle && typeof metaTitle === 'string' && metaTitle.trim() !== '' && !metaTitle.error) {
        console.log('DEBUG: Processing metaTitle:', metaTitle);
        updateSuggestedField('aysa-entity-meta-title', metaTitle);
        
        // ✅ FIXED: DO NOT update product title with meta title - they are separate fields!
        // Meta title is for SEO, product title is the actual product name in WordPress
        console.log('DEBUG: Meta title updated - NOT affecting product title');
    } else if (metaTitle && metaTitle.error) {
        console.warn("Failed to fetch meta title:", metaTitle.message);
    } else {
        console.log('DEBUG: metaTitle is empty, null, or invalid:', metaTitle, typeof metaTitle);
        console.warn('Skipping static fallback for meta title. Keeping existing value when API has no valid response.');
    }

    // Update meta keywords field
    if (metaKeywords && typeof metaKeywords === 'string' && metaKeywords.trim() !== '' && !metaKeywords.error) {
        console.log('DEBUG: Processing metaKeywords:', metaKeywords);
        updateSuggestedField('aysa-entity-meta-keywords', metaKeywords);
    } else if (metaKeywords && metaKeywords.error) {
        console.warn("Failed to fetch meta keywords:", metaKeywords.message);
    } else {
        console.log('DEBUG: metaKeywords is empty, null, or invalid:', metaKeywords, typeof metaKeywords);
        console.warn('Skipping static fallback for meta keywords. Keeping existing value when API has no valid response.');
    }
    
    // Update meta description field
    if (metaDescription && typeof metaDescription === 'string' && metaDescription.trim() !== '' && !metaDescription.error) {
        console.log('DEBUG: Processing metaDescription:', metaDescription);
        updateSuggestedField('aysa-entity-meta-description', metaDescription);
    } else if (metaDescription && metaDescription.error) {
        console.warn("Failed to fetch meta description:", metaDescription.message);
    } else {
        console.log('DEBUG: metaDescription is empty, null, or invalid:', metaDescription, typeof metaDescription);
        console.warn('Skipping static fallback for meta description. Keeping existing value when API has no valid response.');
    }

    // entityType is already declared above
    
    // Update product title if available from dedicated API
    if (entityType === 'Product' && productTitle && typeof productTitle === 'string' && productTitle.trim() !== '' && !productTitle.error) {
        console.log('🔥 PRODUCT TITLE: Using title from API:', productTitle);
        updateProductTitle(productTitle);
        
        // ✅ ENHANCED: Only update meta title with product title IF meta title is empty
        const metaTitleInput = document.getElementById('aysa-entity-meta-title');
        if (metaTitleInput && !metaTitleInput.value.trim()) {
            console.log('🔥 PRODUCT TITLE: Meta title is empty, updating it with product title');
            updateSuggestedField('aysa-entity-meta-title', productTitle);
        } else {
            console.log('🔥 PRODUCT TITLE: Meta title already has value, not overwriting');
        }
    } else if (entityType === 'Product') {
        console.log('🔥 PRODUCT TITLE: No valid title from API, using fallback');
        console.warn('Skipping static fallback for product title. Keeping existing product title when API has no valid response.');
    }

    // Update product full description if available
    if (entityType === 'Product' && productDescription && typeof productDescription === 'string' && productDescription.trim() !== '' && !productDescription.error) {
        console.log('🔥 PRODUCT DESCRIPTION PROCESSING: Starting with content length:', productDescription.length);
        console.log('🔥 PRODUCT DESCRIPTION CONTENT (first 300 chars):', productDescription.substring(0, 300));
        
        // Now sanitize content and remove H1 tags for description fields
        const sanitizedContent = sanitizeContent(productDescription);
        console.log('🔥 SANITIZED CONTENT (first 300 chars):', sanitizedContent.substring(0, 300));
        
        // Remove H1 tags from the content before updating description fields
        const contentWithoutH1 = removeH1Tags(sanitizedContent);
        console.log('🔥 CONTENT WITHOUT H1 (first 300 chars):', contentWithoutH1.substring(0, 300));
            
        // For WooCommerce main product description (content) - use content without H1
        updateWooCommerceDescription(contentWithoutH1);
        
        // For classic WordPress editor
        updateClassicEditorContent(contentWithoutH1);
        
        // For Gutenberg block editor
        updateGutenbergContent(contentWithoutH1);
    } else if (productDescription && productDescription.error) {
         console.warn("Failed to fetch product description:", productDescription.message);
    } else {
        console.log('🔥 NO PRODUCT DESCRIPTION TO PROCESS:', {
            entityType,
            hasProductDescription: !!productDescription,
            productDescriptionType: typeof productDescription,
            productDescriptionLength: productDescription ? productDescription.length : 0,
            hasError: productDescription && productDescription.error
        });
    }
    
    // Update short product description if available
    if (entityType === 'Product' && shortProductDescription && typeof shortProductDescription === 'string' && shortProductDescription.trim() !== '' && !shortProductDescription.error) {
        console.log('Updating product short description with:', 
            typeof shortProductDescription === 'string' ? shortProductDescription.substring(0, 100) + '...' : 'object');
            
        // For WooCommerce short description
        updateWooCommerceShortDescription(shortProductDescription);
        
        // For classic WordPress editor excerpt
        updateClassicEditorExcerpt(shortProductDescription);
        
        // For Gutenberg excerpt
        updateGutenbergExcerpt(shortProductDescription);
    } else if (shortProductDescription && shortProductDescription.error) {
        console.warn("Failed to fetch short product description:", shortProductDescription.message);
    }

    // Update category title if available from dedicated API
    console.log('🔥🔥🔥 CATEGORY TITLE SECTION - DETAILED DEBUG:');
    console.log('🔥 entityType:', entityType);
    console.log('🔥 categoryTitle:', categoryTitle);
    console.log('🔥 categoryTitle type:', typeof categoryTitle);
    console.log('🔥 categoryTitle length:', categoryTitle ? categoryTitle.length : 'N/A');
    console.log('🔥 categoryTitle trimmed:', categoryTitle ? categoryTitle.trim() : 'N/A');
    console.log('🔥 categoryTitle has error:', categoryTitle ? categoryTitle.error : 'N/A');
    
    // Enhanced debugging for category title issues
    console.log('🔥🔥🔥 CATEGORY TITLE DEBUGGING - API Response Analysis:');
    console.log('🔥 Raw categoryTitle value:', JSON.stringify(categoryTitle));
    console.log('🔥 Is categoryTitle truthy?', !!categoryTitle);
    console.log('🔥 Is categoryTitle string?', typeof categoryTitle === 'string');
    console.log('🔥 Is categoryTitle not empty after trim?', categoryTitle && typeof categoryTitle === 'string' ? categoryTitle.trim() !== '' : false);
    console.log('🔥 Does categoryTitle have error property?', categoryTitle && categoryTitle.error);
    
    if (entityType === 'Category' && categoryTitle && typeof categoryTitle === 'string' && categoryTitle.trim() !== '' && !categoryTitle.error) {
        console.log('🔥✅ CATEGORY TITLE: Conditions met, calling updateCategoryName with:', categoryTitle);
        updateCategoryName(categoryTitle);
        console.log('🔥✅ CATEGORY TITLE: updateCategoryName called successfully');
    } else if (entityType === 'Category') {
        console.log('🔥⚠️ CATEGORY TITLE: Conditions not met, using fallback');
        console.log('🔥 Condition checks:');
        console.log('🔥   - entityType === "Category":', entityType === 'Category');
        console.log('🔥   - categoryTitle exists:', !!categoryTitle);
        console.log('🔥   - categoryTitle is string:', typeof categoryTitle === 'string');
        console.log('🔥   - categoryTitle not empty:', categoryTitle ? categoryTitle.trim() !== '' : false);
        console.log('🔥   - categoryTitle no error:', categoryTitle ? !categoryTitle.error : true);
        
        const keyword = document.getElementById('aysa-entity-keyword')?.value || '';
        if (keyword) {
            console.log('🔥⚠️ CATEGORY TITLE: Using keyword fallback:', keyword);
            updateCategoryName(keyword);
        }
    } else {
        console.log('🔥❌ CATEGORY TITLE: Not category entity type, skipping');
    }

    // Update category description if available
    console.log('🔥🔥🔥 CHECKING CATEGORY DESCRIPTION CONDITIONS:');
    console.log('🔥 entityType === "Category":', entityType === 'Category');
    console.log('🔥 categoryDescription exists:', !!categoryDescription);
    console.log('🔥 categoryDescription type:', typeof categoryDescription);
    console.log('🔥 categoryDescription length:', categoryDescription ? categoryDescription.length : 'N/A');
    console.log('🔥 categoryDescription trim not empty:', categoryDescription ? categoryDescription.trim() !== '' : false);
    console.log('🔥 categoryDescription no error:', categoryDescription ? !categoryDescription.error : true);
    
    if (entityType === 'Category' && categoryDescription && typeof categoryDescription === 'string' && categoryDescription.trim() !== '' && !categoryDescription.error) {
        console.log('🔥✅ CATEGORY DESCRIPTION CONDITIONS MET!');
        console.log('🔥 CATEGORY DESCRIPTION PROCESSING: Starting with content length:', categoryDescription.length);
        console.log('🔥 CATEGORY DESCRIPTION CONTENT (first 300 chars):', categoryDescription.substring(0, 300));

        // First, sanitize the content
        const sanitizedContent = sanitizeContent(categoryDescription);
        console.log('🔥 SANITIZED CONTENT (first 300 chars):', sanitizedContent.substring(0, 300));
        
        // Extract H1 from content for category title BEFORE removing H1 tags
        const extractedH1 = extractH1FromContent(sanitizedContent);
        console.log('🔥 EXTRACTED H1 FROM CATEGORY CONTENT:', extractedH1);
        
        // If we found an H1 and no category title was provided from API, use the extracted H1 for category title
        if (extractedH1 && (!categoryTitle || categoryTitle.error)) {
            console.log('🔥✅ CATEGORY TITLE: Using extracted H1 from content:', extractedH1);
            updateCategoryName(extractedH1);
        }
        
        // Now remove H1 tags from the content before updating description fields
        const contentWithoutH1 = removeH1Tags(sanitizedContent);
        console.log('🔥 CONTENT WITHOUT H1 (first 300 chars):', contentWithoutH1.substring(0, 300));

        // Update description field (handles TinyMCE and standard textarea) - use content without H1
        console.log('🔥🔥🔥 CATEGORY DESCRIPTION UPDATE SECTION');
        
        // Try multiple selectors for category description field
        const descriptionById = document.getElementById('description');
        const descriptionByName = document.querySelector('textarea[name="description"]');
        const tagDescriptionField = document.getElementById('tag-description');
        const descriptionTextarea = document.querySelector('#description textarea');
        const descriptionTextarea2 = document.querySelector('textarea#description');
        const categoryDescField = document.querySelector('.term-description-wrap textarea');
        const wpDescriptionField = document.querySelector('textarea[name="tag-description"]');
        const categoryForm = document.querySelector('#edittag textarea[name="description"]');
        const termDescField = document.querySelector('.form-field.term-description-wrap textarea');
        
        console.log('🔥 Category description field search results:');
        console.log('🔥   - getElementById("description"):', descriptionById);
        console.log('🔥   - querySelector("textarea[name=description]"):', descriptionByName);
        console.log('🔥   - getElementById("tag-description"):', tagDescriptionField);
        console.log('🔥   - querySelector("#description textarea"):', descriptionTextarea);
        console.log('🔥   - querySelector("textarea#description"):', descriptionTextarea2);
        console.log('🔥   - querySelector(".term-description-wrap textarea"):', categoryDescField);
        console.log('🔥   - querySelector("textarea[name=tag-description]"):', wpDescriptionField);
        console.log('🔥   - querySelector("#edittag textarea[name=description]"):', categoryForm);
        console.log('🔥   - querySelector(".form-field.term-description-wrap textarea"):', termDescField);
        
        // Select the first valid textarea (prioritize actual textareas)
        const descriptionField = descriptionTextarea2 || descriptionByName || wpDescriptionField || categoryForm || termDescField || tagDescriptionField || categoryDescField || descriptionTextarea;
        console.log('🔥 Selected description field:', descriptionField);
        console.log('🔥 Selected field tag name:', descriptionField ? descriptionField.tagName : 'N/A');
        console.log('🔥 Selected field type:', descriptionField ? descriptionField.type : 'N/A');
        console.log('🔥 Selected field name:', descriptionField ? descriptionField.name : 'N/A');
        console.log('🔥 TinyMCE available:', typeof tinyMCE !== 'undefined');
        console.log('🔥 TinyMCE description editor available:', typeof tinyMCE !== 'undefined' && tinyMCE.get('description'));
        
        if (descriptionField && descriptionField.tagName === 'TEXTAREA') {
            console.log('🔥✅ Found valid TEXTAREA for description');
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
                console.log('🔥✅ Using TinyMCE for category description');
                console.log('🔥 Setting content:', contentWithoutH1.substring(0, 200) + '...');
                
                // Use raw format to preserve HTML
                tinyMCE.get('description').setContent(contentWithoutH1, {format: 'raw'});
                console.log('🔥✅ Updated category description in TinyMCE editor with preserved HTML');
                
                // Configure TinyMCE to allow all HTML tags
                try {
                    const editor = tinyMCE.get('description');
                    if (editor && editor.settings) {
                        editor.settings.verify_html = false;
                        editor.settings.extended_valid_elements = '*[*]';
                        editor.settings.valid_children = '+body[style],+body[script],+div[*],+h2[div],+h3[div]';
                    }
                    console.log('🔥✅ TinyMCE configuration applied');
                } catch (e) {
                    console.error('🔥❌ Error configuring TinyMCE for category description:', e);
                }
            } else {
                console.log('🔥✅ Using textarea for category description');
                console.log('🔥 Current value:', descriptionField.value);
                console.log('🔥 Setting content:', contentWithoutH1.substring(0, 200) + '...');
                
                descriptionField.value = contentWithoutH1;
                console.log('🔥 Value after setting:', descriptionField.value);
                
                descriptionField.dispatchEvent(new Event('change'));
                descriptionField.dispatchEvent(new Event('input'));
                console.log('🔥✅ Updated category description in textarea field with events');
            }
        } else {
            if (descriptionField) {
                console.warn('🔥❌ Found description field but it is not a TEXTAREA:', descriptionField.tagName);
                console.log('🔥❌ Element details:', {
                    tagName: descriptionField.tagName,
                    id: descriptionField.id,
                    className: descriptionField.className,
                    element: descriptionField
                });
            } else {
                console.warn('🔥❌ Could not find any category description field to update');
            }
            
            console.log('🔥❌ Available textarea fields on page:');
            const allTextareas = document.querySelectorAll('textarea');
            allTextareas.forEach((textarea, index) => {
                console.log(`🔥   Textarea ${index}:`, {
                    element: textarea,
                    id: textarea.id,
                    name: textarea.name,
                    className: textarea.className
                });
            });
        }
    } else if (categoryDescription && categoryDescription.error) {
        console.warn("Failed to fetch category description:", categoryDescription.message);
        console.warn('Skipping static fallback for category description. Keeping existing content when API has no valid response.');
    } else {
        console.log('🔥 NO CATEGORY DESCRIPTION TO PROCESS:', {
            entityType,
            hasCategoryDescription: !!categoryDescription,
            categoryDescriptionType: typeof categoryDescription,
            categoryDescriptionLength: categoryDescription ? categoryDescription.length : 0,
            hasError: categoryDescription && categoryDescription.error
        });
        console.warn('Skipping static fallback for category description when API returns no content.');
    }
    
    // Update page/post content if available (for pages/posts only)
    console.log('🚀 DEBUG: Checking page content conditions for non-Product/Category types');
    console.log('🚀 DEBUG: PAGE CONTENT CONDITIONS CHECK:', {
        entityType: entityType,
        isNotProduct: entityType !== 'Product',
        isNotCategory: entityType !== 'Category',
        hasPageContent: !!pageContent,
        pageContentType: typeof pageContent,
        pageContentLength: pageContent ? pageContent.length : 0,
        pageContentTrimNotEmpty: pageContent && typeof pageContent === 'string' ? pageContent.trim() !== '' : false,
        pageContentNoError: pageContent ? !pageContent.error : true,
        pageContentFirstChars: pageContent && typeof pageContent === 'string' ? pageContent.substring(0, 100) : 'N/A'
    });
    
    // 🧪 TEMPORARY DEBUG: Force test page content update for debugging
    if (entityType !== 'Product' && entityType !== 'Category') {
        console.log('🧪 DEBUG: FORCE TESTING PAGE CONTENT UPDATE FOR DEBUGGING');
        
        const testContent = pageContent && typeof pageContent === 'string' && pageContent.trim() !== '' && !pageContent.error 
            ? pageContent 
            : '<h2>Test Content from AYSA</h2><p>This is a test content update to verify that the WordPress editor update mechanism works. Original keyword: ' + (document.getElementById('aysa-entity-keyword')?.value || 'no keyword') + '</p>';
            
        console.log('🧪 DEBUG: Using test content:', testContent.substring(0, 200) + '...');
        
        // Test all editor update methods
        console.log('🧪 DEBUG: Testing Elementor integration...');
        if (checkElementorIntegration()) {
            console.log('🧪 DEBUG: Elementor detected, testing update');
            testElementorContentUpdate(testContent);
        } else {
            console.log('🧪 DEBUG: Elementor not detected');
        }
        
        console.log('🧪 DEBUG: Testing Gutenberg integration...');
        if (typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor')) {
            console.log('🧪 DEBUG: Gutenberg detected, testing update');
            updateGutenbergContent(testContent);
        } else {
            console.log('🧪 DEBUG: Gutenberg not detected');
        }
        
        console.log('🧪 DEBUG: Testing Classic Editor integration...');
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
            console.log('🧪 DEBUG: Classic TinyMCE detected, testing update');
            updateClassicEditorContent(testContent);
        } else {
            console.log('🧪 DEBUG: Classic TinyMCE not detected');
        }
        
        console.log('🧪 DEBUG: Testing textarea fallback...');
        const contentTextarea = document.getElementById('content') || document.querySelector('textarea[name="content"]');
        if (contentTextarea) {
            console.log('🧪 DEBUG: Textarea found, testing update');
            contentTextarea.value = testContent;
            contentTextarea.dispatchEvent(new Event('change'));
            contentTextarea.dispatchEvent(new Event('input'));
            console.log('🧪 DEBUG: Textarea updated successfully');
        } else {
            console.log('🧪 DEBUG: No textarea found for fallback');
        }
    }
    
    if (entityType !== 'Product' && entityType !== 'Category' && pageContent && typeof pageContent === 'string' && pageContent.trim() !== '' && !pageContent.error) {
        console.log('🚀 DEBUG: PAGE CONTENT PROCESSING: Starting with content length:', pageContent.length);
        console.log('🚀 DEBUG: PAGE CONTENT (first 300 chars):', pageContent.substring(0, 300));

        // ✅ ENHANCED: Extract H1 from content for page title BEFORE removing H1 tags
        const extractedH1 = extractH1FromContent(pageContent);
        console.log('🔥 PAGE H1 EXTRACTION:', {
            found: !!extractedH1,
            h1Text: extractedH1,
            h1Length: extractedH1 ? extractedH1.length : 0,
            contentHasH1: pageContent.includes('<h1'),
            entityType: entityType
        });

        // ✅ ENHANCED: Update page title with extracted H1 (same logic as categories)
        if (extractedH1 && extractedH1.trim() !== '') {
            console.log('🔥✅ PAGE TITLE: Using extracted H1 from content:', extractedH1);
            updatePageTitle(extractedH1.trim());
            
            // Show informative toast
            if (typeof showToast === 'function') {
                showToast('Page title updated from H1 in content', 'success');
            }
        } else {
            console.log('🔥⚠️ PAGE TITLE: No H1 found in content, using keyword fallback');
            const keyword = document.getElementById('aysa-entity-keyword')?.value || '';
            if (keyword && keyword.trim()) {
                console.log('🔥⚠️ PAGE TITLE: Using keyword fallback for page title:', keyword);
                updatePageTitle(keyword.trim());
                
                // Show informative toast
                if (typeof showToast === 'function') {
                    showToast('Page title updated from keyword (no H1 found)', 'info');
                }
            } else {
                console.log('🔥❌ PAGE TITLE: No keyword available for fallback');
                
                // Show warning toast
                if (typeof showToast === 'function') {
                    showToast('No H1 found in content and no keyword available', 'warning');
                }
            }
        }

        // ✅ ENHANCED: Sanitize content and remove H1 tags for page content  
        const sanitizedContent = sanitizeContent(pageContent);
        console.log('🔥 SANITIZED PAGE CONTENT (first 300 chars):', sanitizedContent.substring(0, 300));
        
        // ✅ ENHANCED: Remove H1 tags from the content before updating content fields
        console.log('🔥🔥🔥 H1 REMOVAL PROCESS FOR PAGE CONTENT:');
        console.log('🔥 Content BEFORE H1 removal:', {
            length: sanitizedContent.length,
            hasH1: sanitizedContent.includes('<h1'),
            h1Count: (sanitizedContent.match(/<h1[^>]*>/gi) || []).length,
            preview: sanitizedContent.substring(0, 300) + '...'
        });
        
        const contentWithoutH1 = removeH1Tags(sanitizedContent);
        
        console.log('🔥 Content AFTER H1 removal:', {
            length: contentWithoutH1.length,
            hasH1: contentWithoutH1.includes('<h1'),
            h1Count: (contentWithoutH1.match(/<h1[^>]*>/gi) || []).length,
            preview: contentWithoutH1.substring(0, 300) + '...',
            lengthDifference: sanitizedContent.length - contentWithoutH1.length
        });
        
        // ✅ ENHANCED: Validate H1 removal success
        const h1RemovalSuccess = sanitizedContent.includes('<h1') && !contentWithoutH1.includes('<h1');
        if (h1RemovalSuccess) {
            console.log('🔥✅ H1 REMOVAL: Successfully removed H1 from page content');
            if (typeof showToast === 'function') {
                showToast('H1 successfully removed from page content', 'success');
            }
        } else if (sanitizedContent.includes('<h1')) {
            console.log('🔥❌ H1 REMOVAL: Failed to remove H1 from page content');
            if (typeof showToast === 'function') {
                showToast('Warning: H1 removal may have failed', 'warning');
            }
        } else {
            console.log('🔥ℹ️ H1 REMOVAL: No H1 found to remove from page content');
        }

        // ✅ ENHANCED: Update page content - try different WordPress editor types
        console.log('🔥🔥🔥 PAGE CONTENT UPDATE PROCESS:');
        console.log('🔥 Attempting to update page content in WordPress editor');
        
        // Debug available editor types
        console.log('🔥 EDITOR DETECTION CHECK:', {
            hasElementor: !!checkElementorIntegration(),
            hasGutenberg: typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor'),
            hasTinyMCE: typeof tinyMCE !== 'undefined' && tinyMCE.get('content'),
            hasContentTextarea: !!(document.getElementById('content') || document.querySelector('textarea[name="content"]')),
            wpExists: typeof wp !== 'undefined',
            wpDataExists: typeof wp !== 'undefined' && wp.data,
            tinyMCEExists: typeof tinyMCE !== 'undefined',
            tinyMCEContentExists: typeof tinyMCE !== 'undefined' && tinyMCE.get('content')
        });

        // Check for Elementor first
        if (checkElementorIntegration()) {
            console.log('🔥✅ PAGE CONTENT UPDATE: Elementor detected, updating via Elementor API');
            testElementorContentUpdate(contentWithoutH1);
            if (typeof showToast === 'function') {
                showToast('Page content updated via Elementor', 'success');
            }
        } 
        // Check for Gutenberg/Block editor
        else if (typeof wp !== 'undefined' && wp.data && wp.data.select('core/editor')) {
            console.log('🔥✅ PAGE CONTENT UPDATE: Gutenberg editor detected, updating content');
            updateGutenbergContent(contentWithoutH1);
            if (typeof showToast === 'function') {
                showToast('Page content updated via Gutenberg editor', 'success');
            }
        }
        // Check for Classic Editor
        else if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
            console.log('🔥✅ PAGE CONTENT UPDATE: Classic TinyMCE editor detected, updating content');
            updateClassicEditorContent(contentWithoutH1);
            if (typeof showToast === 'function') {
                showToast('Page content updated via Classic editor', 'success');
            }
        }
        // Fallback to textarea
        else {
            console.log('🔥⚠️ PAGE CONTENT UPDATE: Using fallback textarea method for page content');
            const contentTextarea = document.getElementById('content') || document.querySelector('textarea[name="content"]');
            console.log('🔥 Content textarea found:', !!contentTextarea);
            if (contentTextarea) {
                console.log('🔥 Setting textarea value to:', contentWithoutH1.substring(0, 100) + '...');
                contentTextarea.value = contentWithoutH1;
                contentTextarea.dispatchEvent(new Event('change'));
                contentTextarea.dispatchEvent(new Event('input'));
                console.log('🔥✅ PAGE CONTENT UPDATE: Page content updated via textarea fallback - new value length:', contentTextarea.value.length);
                if (typeof showToast === 'function') {
                    showToast('Page content updated via textarea fallback', 'success');
                }
            } else {
                console.warn('🔥❌ PAGE CONTENT UPDATE: Could not find content field for page content update');
                console.log('🔥 Available content fields check:', {
                    contentById: !!document.getElementById('content'),
                    contentByName: !!document.querySelector('textarea[name="content"]'),
                    allTextareas: document.querySelectorAll('textarea').length,
                    allInputs: document.querySelectorAll('input[type="text"]').length
                });
                if (typeof showToast === 'function') {
                    showToast('Could not find content field for page update', 'error');
                }
            }
        }
         } else if (entityType !== 'Product' && entityType !== 'Category' && pageContent && pageContent.error) {
         console.warn("🚀 DEBUG: Failed to fetch page content:", pageContent.message);
     } else if (entityType !== 'Product' && entityType !== 'Category') {
         console.log('🚀 DEBUG: No valid page content received for pages/posts:', {
             entityType,
             hasPageContent: !!pageContent,
             pageContentType: typeof pageContent,
             pageContentLength: pageContent ? pageContent.length : 0,
             hasError: pageContent && pageContent.error,
             pageContentValue: pageContent
         });
     } else {
         console.log('🚀 DEBUG: Page content update skipped because entity is Product or Category:', {
             entityType,
             isProduct: entityType === 'Product',
             isCategory: entityType === 'Category'
         });
     }
    
    // Update product permalink if available
    if (entityType === 'Product' && productPermalink && typeof productPermalink === 'string' && productPermalink.trim() !== '' && !productPermalink.error) {
        console.log('Updating product permalink with:', productPermalink);
        updateProductPermalink(productPermalink); 
    } else if (productPermalink && productPermalink.error) {
        console.warn("Failed to fetch product permalink:", productPermalink.message);
    }
    
    // Update category permalink if available
    if (entityType === 'Category' && categoryPermalink && typeof categoryPermalink === 'string' && categoryPermalink.trim() !== '' && !categoryPermalink.error) {
        console.log('Updating category permalink with:', categoryPermalink);
        updateCategoryPermalink(categoryPermalink); 
    } else if (categoryPermalink && categoryPermalink.error) {
        console.warn("Failed to fetch category permalink:", categoryPermalink.message);
    }

    // After all fields are updated, record the change for versioning
    if (window.aysaVersioningService && typeof window.aysaVersioningService.recordChange === 'function') {
        const entityId = getEntityId();
        const oldData = window.aysaPreSuggestionData;
        
        const newData = {
            metaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
            metaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
            metaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
            productDescription: '',
            productShortDescription: '',
            productPermalink: '',
            categoryName: '',
            categoryDescription: ''
        };

        if (entityType === 'Product') {
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                newData.productDescription = tinyMCE.get('content').getContent();
            } else {
                newData.productDescription = document.getElementById('content')?.value || '';
            }
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
                newData.productShortDescription = tinyMCE.get('excerpt').getContent();
            } else {
                newData.productShortDescription = document.getElementById('excerpt')?.value || document.getElementById('post_excerpt')?.value || document.querySelector('#postexcerpt textarea')?.value || '';
            }
            const permalinkFieldNew = document.getElementById('editable-post-name') || document.getElementById('editable-post-name-full') || document.querySelector('#edit-slug-box .editable-post-name');
            newData.productPermalink = permalinkFieldNew ? (permalinkFieldNew.textContent || permalinkFieldNew.value) : '';


        } else if (entityType === 'Category') {
            newData.categoryName = document.getElementById('name')?.value || '';
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
                newData.categoryDescription = tinyMCE.get('description').getContent();
            } else {
                newData.categoryDescription = document.getElementById('description')?.value || '';
            }
        }

        // Only record if there are actual changes
        // Simple stringify comparison, consider a more robust deep comparison if needed
        if (JSON.stringify(oldData) !== JSON.stringify(newData)) {
            window.aysaVersioningService.recordChange({
                entityId: entityId,
                entityType: entityType, // Versioning service might determine this too
                section: 'seoSuggestions',
                oldData: oldData,
                newData: newData,
                changeType: 'suggestion_applied', // Custom change type
                metadata: {
                    trigger: 'generateSuggestionsButton'
                }
            }).then(response => {
                if (response.success) {
                    console.log('AYSA Versioning: SEO suggestions change recorded.', response);
                } else {
                    console.warn('AYSA Versioning: Failed to record SEO suggestions change.', response);
                }
            });
        } else {
            console.log('AYSA Versioning: No changes detected after applying SEO suggestions. Skipping recordChange.');
        }
        // Clear the pre-suggestion data
        window.aysaPreSuggestionData = {}; 
    } else {
        console.warn('AYSA VersioningService not available or recordChange is not a function.');
    }

    // Show success toast
    if (typeof showToast === 'function') {
        showToast('SEO suggestions generated and applied!', 'success');
    }
    
    // Final verification
    console.log("🚀 DEBUG: updateSuggestionFields COMPLETED - Final field values:");
    console.log("- aysa-entity-second-keyword:", document.getElementById('aysa-entity-second-keyword')?.value || "EMPTY");
    console.log("- aysa-entity-meta-title:", document.getElementById('aysa-entity-meta-title')?.value || "EMPTY");
    console.log("- aysa-entity-meta-keywords:", document.getElementById('aysa-entity-meta-keywords')?.value || "EMPTY");
    console.log("- aysa-entity-meta-description:", document.getElementById('aysa-entity-meta-description')?.value || "EMPTY");
    
    // 💾 CRITICAL: Save secondary keywords to database after updating UI
    if (newKeywords && newKeywords.length > 0) {
        console.log('💾 SAVING NEW SECONDARY KEYWORDS TO DATABASE:', newKeywords);
        
        const entityId = getEntityId();
        const entityType = getEntityTypeGood();
        const projectId = getProjectId();
        
        if (entityId && entityType && projectId) {
            // Save secondary keywords using the same logic as handleEditSnippet
            processSecondaryKeywordsForSuggestions(entityId, entityType, projectId, newKeywords)
                .then(results => {
                    console.log('✅ Secondary keywords saved successfully:', results);
                    if (typeof showToast === 'function') {
                        showToast(`${newKeywords.length} secondary keywords saved to database`, 'success');
                    }
                })
                .catch(error => {
                    console.error('❌ Error saving secondary keywords:', error);
                    if (typeof showToast === 'function') {
                        showToast('Error saving secondary keywords to database', 'error');
                    }
                });
        } else {
            console.warn('⚠️ Cannot save secondary keywords - missing entity info:', {
                entityId, entityType, projectId
            });
        }
    } else {
        console.log('📝 No new secondary keywords to save to database');
    }
}

/**
 * Process secondary keywords for SEO suggestions (simplified version of processSecondaryKeywordsAfterUpsert)
 * @param {number} entityId - Entity ID
 * @param {string} entityType - Entity type (Product, Category, Page)
 * @param {number} projectId - Project ID
 * @param {Array<string>} secondaryKeywords - Array of secondary keywords
 * @returns {Promise<Array>} Results from bulk insert
 */
async function processSecondaryKeywordsForSuggestions(entityId, entityType, projectId, secondaryKeywords) {
    console.log('💾 Processing secondary keywords for suggestions:', {
        entityId, entityType, projectId, secondaryKeywords
    });
    
    // Get main keyword and entity details for association data
    const mainKeyword = document.getElementById('aysa-entity-keyword')?.value || '';
    const entityName = getEntityName();
    const entityUrl = getEntityPublicUrl();
    
    // Prepare associations array for bulk insert
    const associationsArray = secondaryKeywords
        .map((keyword, index) => {
            if (!keyword || keyword.trim() === '') return null;
            
            const secondaryAssociationData = {
                IdIntern: entityId,
                AssociatedOn: entityType,
                Value: entityName || '',
                Link: entityUrl || window.location.href,
                Keyword: keyword.trim(),
                ProjectId: projectId,
                IsMain: false, // Secondary keywords are not main
                
                // Copy basic SEO settings from form if available
                MetaTitle: '',
                MetaDescription: '',
                MetaKeywords: '',
                
                // Copy SEO settings from form
                TargetedSearchEngine: document.getElementById('targeted_se')?.value || '',
                TargetedCountry: document.getElementById('targeted_country')?.value || '',
                TargetedRegion: document.getElementById('targeted_region')?.value || '',
                TargetedCity: document.getElementById('targeted_city')?.value || '',
                UpdateFrequency: document.getElementById('update_frequency')?.value || '',
                LanguageOptimize: document.getElementById('language_optimize')?.value || '',
                DeviceOptimize: document.getElementById('device_optimize')?.value || '',
                
                // Default advanced settings
                Index: true,
                NoFollow: false,
                NoArchive: false,
                NoImageIndex: false,
                NoSnippet: false,
                MaxSnippet: -1,
                MaxVideoPreview: -1,
                MaxImagePreview: 'large',
                CanonicalUrl: ''
            };
            
            console.log(`💾 Preparing secondary association ${index + 1}:`, secondaryAssociationData);
            return secondaryAssociationData;
        })
        .filter(assoc => assoc !== null);
    
    if (associationsArray.length === 0) {
        console.log('💾 No valid secondary keywords to process');
        return [];
    }
    
    try {
        console.log('💾 Using bulk insert for secondary keywords from suggestions:', associationsArray);
        
        const apiUrl = `${getAysaApiBaseUrl()}/api/Association/insertmany`;
        
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            body: JSON.stringify(associationsArray),
            mode: 'cors'
        });
        
        if (!response.ok) {
            throw new Error(`Bulk insert API error: ${response.status} - ${response.statusText}`);
        }
        
        const results = await response.json();
        console.log('✅ All secondary keywords from suggestions processed successfully:', results);
        return results;
        
    } catch (error) {
        console.error('❌ Error processing secondary keywords from suggestions:', error);
        throw error;
    }
}

/**
 * Get entity name for association data
 * @returns {string} Entity name
 */
function getEntityName() {
    // Try different selectors based on entity type
    const nameSelectors = [
        '#title',           // WordPress post/page title
        '#name',            // Category name
        'input[name="post_title"]',
        'input[name="name"]',
        '#post_title',
        '.editor-post-title__input'  // Gutenberg editor
    ];
    
    for (const selector of nameSelectors) {
        const element = document.querySelector(selector);
        if (element && element.value) {
            return element.value.trim();
        }
    }
    
    // Fallback to document title
    return document.title.split(' - ')[0] || '';
}

/**
 * Extract H1 heading from HTML content
 * @param {string} content - HTML content to extract H1 from
 * @returns {string|null} - The extracted H1 text or null if not found
 */
function extractH1FromContent(content) {
    if (!content || typeof content !== 'string') {
        console.log('🔥 extractH1FromContent: No content provided or content is not a string');
        return null;
    }
    
    console.log('🔥 extractH1FromContent: Starting H1 extraction process');
    console.log('🔥 extractH1FromContent: Content length:', content.length);
    console.log('🔥 extractH1FromContent: Content has H1 tags:', content.includes('<h1'));
    
    // Method 1: Use DOM parsing as the primary method for reliability
    try {
        console.log('🔥 extractH1FromContent: Trying DOM parsing method...');
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = content;
        const h1Element = tempDiv.querySelector('h1');
        
        if (h1Element && h1Element.textContent && h1Element.textContent.trim()) {
            const extractedText = h1Element.textContent.trim();
            console.log('🔥✅ extractH1FromContent: Found H1 via DOM parsing:', extractedText);
            console.log('🔥 extractH1FromContent: H1 length:', extractedText.length);
            return extractedText;
        } else {
            console.log('🔥 extractH1FromContent: DOM parsing found H1 element but no valid text content');
        }
    } catch (e) {
        console.log('🔥❌ extractH1FromContent: DOM parsing failed:', e);
    }
    
    // Method 2: Fallback to regex if DOM parsing fails
    console.log('🔥 extractH1FromContent: Trying regex fallback method...');
    const match = content.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);
    
    if (match && match[1]) {
        const rawContent = match[1];
        console.log('🔥 extractH1FromContent: Raw H1 content found:', rawContent.substring(0, 100) + '...');
        
        // Clean up the content by removing HTML tags and normalizing whitespace
        const cleaned = rawContent
            .replace(/<[^>]*>/g, '') // Remove HTML tags
            .replace(/\s+/g, ' ')    // Normalize whitespace
            .trim();                 // Remove leading/trailing whitespace
            
        if (cleaned && cleaned.length > 0) {
            console.log('🔥✅ extractH1FromContent: Found H1 via regex fallback:', cleaned);
            console.log('🔥 extractH1FromContent: H1 length:', cleaned.length);
            return cleaned;
        } else {
            console.log('🔥 extractH1FromContent: Regex found H1 but content was empty after cleaning');
        }
    } else {
        console.log('🔥 extractH1FromContent: No H1 pattern matched with regex');
    }
    
    // Method 3: Try case-insensitive search for any h1 variations
    console.log('🔥 extractH1FromContent: Trying case-insensitive search...');
    const caseInsensitiveMatch = content.match(/<h1[^>]*>([\s\S]*?)<\/h1>/gi);
    
    if (caseInsensitiveMatch && caseInsensitiveMatch.length > 0) {
        console.log('🔥 extractH1FromContent: Found', caseInsensitiveMatch.length, 'H1 tag(s) with case-insensitive search');
        
        // Take the first H1 found
        const firstH1 = caseInsensitiveMatch[0];
        const contentMatch = firstH1.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);
        
        if (contentMatch && contentMatch[1]) {
            const cleaned = contentMatch[1].replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
            if (cleaned && cleaned.length > 0) {
                console.log('🔥✅ extractH1FromContent: Found H1 via case-insensitive search:', cleaned);
                return cleaned;
            }
        }
    }
    
    console.log('🔥❌ extractH1FromContent: No H1 found with any method');
    return null;
}

/**
 * Update product title with extracted H1
 * @param {string} title - The title text to set
 */
function updateProductTitle(title) {
    if (!title) {
        console.warn('🔥 updateProductTitle: No title provided to update product title');
        return false;
    }
    
    // ✅ ENHANCED LOGGING: Track when page title is changed instead of adding H1
    const entityType = getEntityTypeGood()
    const currentTitleValue = document.getElementById('post_title')?.value || document.querySelector('input[name="post_title"]')?.value || '';
    
    console.log('🔥 PAGE_TITLE_CHANGE_LOG: Page title update initiated:', {
        entityType: entityType,
        newTitle: title,
        currentTitle: currentTitleValue,
        titleChanged: currentTitleValue !== title,
        reason: 'H1_EXTRACTED_FROM_CONTENT',
        timestamp: new Date().toISOString()
    });
    
    // ✅ PROTECTION: Add warning when this function is called to help debug
    console.log('🔥 updateProductTitle: Updating WORDPRESS PRODUCT TITLE with:', title);
    console.log('🔥 updateProductTitle: ⚠️ This should ONLY be called with actual product titles, NOT meta titles!');
    
    // Find the title input field - try various selectors for product edit pages
    const titleInput = 
                      document.getElementById('post_title') ||
                      document.querySelector('input[name="post_title"]');
    
    if (titleInput) {
        // Clear any placeholder text first
        if (titleInput.placeholder) {
            titleInput.placeholder = '';
        }
        
        // Remove placeholder class if it exists
        titleInput.classList.remove('has-placeholder');
        
        // ✅ ENHANCED LOGGING: Log before title change
        console.log('🔥 PAGE_TITLE_CHANGE_LOG: Before title update:', {
            fieldFound: true,
            fieldId: titleInput.id,
            fieldName: titleInput.name,
            oldValue: titleInput.value,
            newValue: title
        });
        
        // Set the new title value
        titleInput.value = title;
        
        // ✅ ENHANCED LOGGING: Log after title change
        console.log('🔥 PAGE_TITLE_CHANGE_LOG: After title update:', {
            success: true,
            finalValue: titleInput.value,
            valueMatches: titleInput.value === title
        });
        
        // Focus and blur to trigger WordPress title update mechanisms
        titleInput.focus();
        titleInput.blur();
        
        // Dispatch multiple events to ensure WordPress recognizes the change
        titleInput.dispatchEvent(new Event('input', { bubbles: true }));
        titleInput.dispatchEvent(new Event('change', { bubbles: true }));
        titleInput.dispatchEvent(new Event('keyup', { bubbles: true }));
        
        // Update the permalink sample if it exists
        const permalinkSample = document.getElementById('sample-permalink');
        if (permalinkSample) {
            // Trigger WordPress permalink update
            if (typeof wp !== 'undefined' && wp.ajax) {
                wp.ajax.post('sample-permalink', {
                    data: {
                        post_id: getEntityId(),
                        new_title: title,
                        samplepermalinknonce: document.getElementById('samplepermalinknonce')?.value
                    }
                }).done(function(response) {
                    if (response) {
                        const permalink = document.getElementById('sample-permalink');
                        if (permalink) {
                            permalink.innerHTML = response;
                        }
                    }
                });
            }
        }
        
        console.log('Updated product title in input field and triggered WordPress events');
        
        // Show success message
        if (typeof showToast === 'function') {
            showToast('Product title updated from H1 in content', 'success');
        }
        return true;
    } else {
        console.warn('Could not find product title input field to update');
        return false;
    }
}

/**
 * Update category name with extracted H1
 * @param {string} name - The name text to set
 */
function updateCategoryName(name) {
    console.log('🔥🔥🔥 updateCategoryName CALLED with:', name);
    
    if (!name) {
        console.warn('🔥❌ updateCategoryName: No name provided or invalid type:', { name, type: typeof name });
        return;
    }
    
    console.log('🔥 updateCategoryName: Processing name:', name);
    
    // Find the name input field - try various selectors for category edit pages
    console.log('🔥 updateCategoryName: Searching for name input fields...');
    
    const nameById = document.getElementById('name');
    const tagNameById = document.getElementById('tag-name');
    const nameBySelector = document.querySelector('input[name="name"]');
    const categoryNameField = document.querySelector('#edittag input[name="name"]');
    const termNameField = document.querySelector('.form-field.term-name-wrap input');
    const wpCategoryName = document.querySelector('input[name="tag-name"]');
    
    console.log('🔥 updateCategoryName: Field search results:');
    console.log('🔥   - document.getElementById("name"):', nameById);
    console.log('🔥   - document.getElementById("tag-name"):', tagNameById);
    console.log('🔥   - document.querySelector("input[name=\\"name\\"]"):', nameBySelector);
    console.log('🔥   - document.querySelector("#edittag input[name=\\"name\\"]"):', categoryNameField);
    console.log('🔥   - document.querySelector(".form-field.term-name-wrap input"):', termNameField);
    console.log('🔥   - document.querySelector("input[name=\\"tag-name\\"]"):', wpCategoryName);
    
    // Also check all available input fields
    console.log('🔥 updateCategoryName: All input fields on page:');
    const allInputs = document.querySelectorAll('input[type="text"], input:not([type])');
    allInputs.forEach((input, index) => {
        console.log(`🔥   Input ${index}:`, {
            element: input,
            id: input.id,
            name: input.name,
            value: input.value,
            className: input.className,
            tagName: input.tagName,
            type: input.type
        });
    });
    
    const nameInput = categoryNameField || termNameField || nameBySelector || wpCategoryName || nameById || tagNameById;
    console.log('🔥 updateCategoryName: Selected nameInput:', nameInput);
    console.log('🔥 updateCategoryName: Selected input details:', {
        tagName: nameInput ? nameInput.tagName : 'N/A',
        type: nameInput ? nameInput.type : 'N/A',
        id: nameInput ? nameInput.id : 'N/A',
        name: nameInput ? nameInput.name : 'N/A',
        className: nameInput ? nameInput.className : 'N/A'
    });
    
    if (nameInput && nameInput.tagName === 'INPUT') {
        console.log('🔥✅ updateCategoryName: Found valid INPUT field, current value:', nameInput.value);
        console.log('🔥✅ updateCategoryName: Setting new value:', name);
        
        // Only update if the name input is found
        nameInput.value = name;
        console.log('🔥✅ updateCategoryName: Value set, new value is:', nameInput.value);
        
        nameInput.dispatchEvent(new Event('change'));
        console.log('🔥✅ updateCategoryName: Change event dispatched');
        
        // Also try input event
        nameInput.dispatchEvent(new Event('input'));
        console.log('🔥✅ updateCategoryName: Input event dispatched');
        
        // Focus and blur to trigger any additional handlers
        nameInput.focus();
        nameInput.blur();
        console.log('🔥✅ updateCategoryName: Focus/blur triggered');
        
        console.log('🔥✅ updateCategoryName: Final input value check:', nameInput.value);
        
        // Show success message
        if (typeof showToast === 'function') {
            showToast('Category name updated from API', 'success');
            console.log('🔥✅ updateCategoryName: Success toast shown');
        }
    } else {
        if (nameInput) {
            console.warn('🔥❌ updateCategoryName: Found name field but it is not an INPUT:', nameInput.tagName);
            console.log('🔥❌ updateCategoryName: Element details:', {
                tagName: nameInput.tagName,
                id: nameInput.id,
                className: nameInput.className,
                element: nameInput
            });
        } else {
            console.warn('🔥❌ updateCategoryName: Could not find any category name input field');
        }
    }
}

/**
 * Update page title (for WordPress pages)
 * @param {string} title - The title to set
 */
function updatePageTitle(title) {
    if (!title || typeof title !== 'string' || title.trim() === '') {
        console.warn('🔥 updatePageTitle: No title provided to update page title');
        return;
    }

    // ✅ ENHANCED LOGGING: Track when page title is changed instead of adding H1
    const timestamp = new Date().toISOString();
    const entityType = getEntityTypeGood()
    
    console.log('🔥 PAGE_TITLE_CHANGE_LOG: Page title update initiated:', {
        timestamp: timestamp,
        entityType: entityType,
        newTitle: title,
        titleLength: title.length,
        reason: 'H1_EXTRACTED_FROM_CONTENT',
        source: 'updatePageTitle_function'
    });

    console.log('🔥🔥🔥 updatePageTitle: STARTING PAGE TITLE UPDATE PROCESS');
    console.log('🔥 updatePageTitle: Updating WORDPRESS PAGE TITLE with:', title);
    console.log('🔥 updatePageTitle: Title length:', title.length);
    console.log('🔥 updatePageTitle: ⚠️ This should ONLY be called with actual page titles, NOT meta titles!');
    console.log('🔥 updatePageTitle: ⚠️ If you see this multiple times for the same title, there is a DUPLICATION BUG!');

    // ✅ ENHANCED: Detect editor type and find appropriate title field
    console.log('🔥 updatePageTitle: Detecting editor type and title field...');
    console.log('🔥 updatePageTitle: Editor detection:', {
        hasGutenberg: typeof wp !== 'undefined' && wp.data && wp.data.select && wp.data.select('core/editor'),
        hasClassicEditor: !!document.getElementById('title'),
        wpExists: typeof wp !== 'undefined',
        wpDataExists: typeof wp !== 'undefined' && wp.data
    });
    
    // Try Gutenberg first if available
    if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch && wp.data.select) {
        try {
            console.log('🔥 updatePageTitle: Trying Gutenberg editor API...');
            const editor = wp.data.dispatch('core/editor');
            if (editor && editor.editPost) {
                editor.editPost({ title: title });
                console.log('🔥✅ updatePageTitle: Successfully updated title via Gutenberg API');
                
                // Show success message
                if (typeof showToast === 'function') {
                    showToast('Page title updated from H1 in content', 'success');
                }
                return;
            }
        } catch (e) {
            console.error('🔥❌ updatePageTitle: Gutenberg API failed:', e);
        }
    }
    
    // Fallback to direct DOM manipulation
    console.log('🔥 updatePageTitle: Trying direct DOM manipulation...');
    const titleInput = document.getElementById('title') || 
                      document.querySelector('input[name="post_title"]') || 
                      document.querySelector('#title-prompt-text') ||
                      document.querySelector('.editor-post-title__input') ||
                      document.querySelector('input[id="title"]');
                      
    console.log('🔥 updatePageTitle: Title field search results:', {
        byId: !!document.getElementById('title'),
        byName: !!document.querySelector('input[name="post_title"]'),
        byPrompt: !!document.querySelector('#title-prompt-text'),
        byGutenberg: !!document.querySelector('.editor-post-title__input'),
        selectedField: !!titleInput,
        selectedFieldTag: titleInput ? titleInput.tagName : 'none'
    });

    if (titleInput && titleInput.tagName === 'INPUT') {
        console.log('🔥 PAGE_TITLE_CHANGE_LOG: Before title update:', {
            currentValue: titleInput.value,
            currentLength: titleInput.value ? titleInput.value.length : 0,
            newValue: title,
            newLength: title.length,
            fieldId: titleInput.id,
            fieldName: titleInput.name
        });

        titleInput.value = title;
        titleInput.dispatchEvent(new Event('change', { bubbles: true }));
        titleInput.dispatchEvent(new Event('input', { bubbles: true }));
        titleInput.dispatchEvent(new Event('keyup', { bubbles: true }));
        
        console.log('🔥 PAGE_TITLE_CHANGE_LOG: After title update:', {
            updatedValue: titleInput.value,
            updatedLength: titleInput.value ? titleInput.value.length : 0,
            updateSuccess: titleInput.value === title,
            timestamp: new Date().toISOString()
        });

        // Try to trigger WordPress-specific events
        if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch) {
            try {
                const editor = wp.data.dispatch('core/editor');
                if (editor && editor.editPost) {
                    editor.editPost({ title: title });
                    console.log('🔥 updatePageTitle: Updated title via WordPress editor API');
                }
            } catch (e) {
                console.error('🔥 updatePageTitle: Error updating via WP editor API:', e);
            }
        }

        // Show success message
        if (typeof showToast === 'function') {
            showToast('Page title updated from H1 in content', 'success');
        }
        
        console.log('🔥✅ updatePageTitle: Page title update completed successfully via DOM manipulation');
        console.log('🔥🔥🔥 updatePageTitle: PROCESS COMPLETED SUCCESSFULLY');
    } else {
        console.warn('🔥❌ updatePageTitle: Could not find page title input field');
        console.log('🔥❌ updatePageTitle: Available title-related fields:', {
            byId: !!document.getElementById('title'),
            byName: !!document.querySelector('input[name="post_title"]'),
            byPrompt: !!document.querySelector('#title-prompt-text'),
            byGutenberg: !!document.querySelector('.editor-post-title__input'),
            foundElement: titleInput,
            elementTag: titleInput ? titleInput.tagName : 'none'
        });
        
        // Show error message
        if (typeof showToast === 'function') {
            showToast('Could not find page title field to update', 'error');
        }
        
        console.log('🔥🔥🔥 updatePageTitle: PROCESS FAILED - NO TITLE FIELD FOUND');
    }
}

/**
 * Update WooCommerce product description (main content)
 * @param {string} content - The content to set
 */
function updateWooCommerceDescription(content) {
    console.log('🔄 AYSA: updateWooCommerceDescription called', {
        contentLength: content ? content.length : 0,
        contentPreview: content ? content.substring(0, 100) + '...' : 'empty',
        hasElementorHandler: !!window.aysaElementorHandler
    });
    
    // Sanitize content to remove any markdown code markers
    const sanitizedContent = sanitizeContent(content, true);
    
    // WooCommerce product description field
    const mainContentField = document.getElementById('content');
    if (mainContentField) {
        mainContentField.value = sanitizedContent;
        mainContentField.dispatchEvent(new Event('change'));
        console.log('✅ AYSA: Updated main content in #content field');
    }
    
    // TinyMCE editor for WooCommerce description
    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
        // Use the setContent method with format='raw' to preserve HTML
        tinyMCE.get('content').setContent(sanitizedContent, {format: 'raw'});
        console.log('Updated main content in TinyMCE editor with preserved HTML');
        
        // Configure TinyMCE to allow all HTML tags if needed
        try {
            const editor = tinyMCE.get('content');
            if (editor && editor.settings) {
                editor.settings.verify_html = false;
                editor.settings.extended_valid_elements = '*[*]';
                editor.settings.valid_children = '+body[style],+body[script],+div[*],+h2[div],+h3[div]';
            }
        } catch (e) {
            console.error('Error configuring TinyMCE:', e);
        }
    }
    
    // Also try to update using the WordPress editor API if available
    if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch && wp.data.select) {
        try {
            const editor = wp.data.dispatch('core/editor');
            if (editor && editor.editPost) {
                editor.editPost({ content: sanitizedContent });
                console.log('Updated content via WordPress editor API');
            }
        } catch (e) {
            console.error('Error updating via WP editor API:', e);
        }
    }
}

/**
 * Update WooCommerce product short description
 * @param {string} content - The content to set
 */
function updateWooCommerceShortDescription(content) {
    console.log('🔄 AYSA: updateWooCommerceShortDescription called', {
        contentLength: content ? content.length : 0,
        contentPreview: content ? content.substring(0, 50) + '...' : 'empty',
        hasElementorHandler: !!window.aysaElementorHandler
    });
    
    // Sanitize content to remove any markdown code markers while preserving HTML
    const sanitizedContent = sanitizeContent(content, true);
    
    // WooCommerce product short description field
    const excerptField = document.getElementById('excerpt');
    if (excerptField) {
        excerptField.value = sanitizedContent;
        excerptField.dispatchEvent(new Event('change'));
        console.log('✅ AYSA: Updated short description in #excerpt field');
    }
    
    // TinyMCE editor for WooCommerce short description
    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
        // Use raw format to preserve HTML
        tinyMCE.get('excerpt').setContent(sanitizedContent, {format: 'raw'});
        console.log('Updated short description in TinyMCE editor with preserved HTML');
        
        // Configure TinyMCE to allow all tags
        try {
            const editor = tinyMCE.get('excerpt');
            if (editor && editor.settings) {
                editor.settings.verify_html = false;
                editor.settings.extended_valid_elements = '*[*]';
                editor.settings.valid_children = '+body[style],+body[script],+div[*],+h2[div],+h3[div]';
            }
        } catch (e) {
            console.error('Error configuring TinyMCE for excerpt:', e);
        }
    }
    
    // Additional WooCommerce specific short description fields
    const wooShortDescField = document.getElementById('product_short_description') || 
                            document.querySelector('.woocommerce-product-short-description');
    if (wooShortDescField) {
        wooShortDescField.value = sanitizedContent;
        wooShortDescField.dispatchEvent(new Event('change'));
        console.log('Updated short description in WooCommerce specific field');
    }
}

/**
 * Update classic WordPress editor content
 * @param {string} content - The content to set
 */
function updateClassicEditorContent(content) {
    // Sanitize content to remove any markdown code markers while preserving HTML
    const sanitizedContent = sanitizeContent(content, true);
    
    // Try to update content field
    const classicEditor = document.getElementById('wp-content-editor-container');
    if (classicEditor) {
        const textarea = classicEditor.querySelector('textarea');
        if (textarea) {
            textarea.value = sanitizedContent;
            textarea.dispatchEvent(new Event('change'));
            console.log('Updated content in classic WordPress editor');
            
            // If TinyMCE is active and bound to this textarea
            if (typeof tinyMCE !== 'undefined') {
                const editorId = textarea.id;
                if (editorId && tinyMCE.get(editorId)) {
                    // Use raw format to preserve HTML
                    tinyMCE.get(editorId).setContent(sanitizedContent, {format: 'raw'});
                    console.log(`Updated content in TinyMCE editor ${editorId} with preserved HTML`);
                    
                    // Configure TinyMCE
                    try {
                        const editor = tinyMCE.get(editorId);
                        if (editor && editor.settings) {
                            editor.settings.verify_html = false;
                            editor.settings.extended_valid_elements = '*[*]';
                            editor.settings.valid_children = '+body[style],+body[script],+div[*],+h2[div],+h3[div]';
                        }
                    } catch (e) {
                        console.error('Error configuring TinyMCE for classic editor:', e);
                    }
                }
            }
        }
    }
}

/**
 * Update classic WordPress editor excerpt
 * @param {string} content - The content to set
 */
function updateClassicEditorExcerpt(content) {
    // Sanitize content to remove any markdown code markers while preserving HTML
    const sanitizedContent = sanitizeContent(content, true);
    
    // Try to update excerpt field
    const excerptEditor = document.getElementById('wp-excerpt-editor-container');
    if (excerptEditor) {
        const textarea = excerptEditor.querySelector('textarea');
        if (textarea) {
            textarea.value = sanitizedContent;
            textarea.dispatchEvent(new Event('change'));
            console.log('Updated excerpt in classic WordPress editor');
            
            // If TinyMCE is active and bound to this textarea
            if (typeof tinyMCE !== 'undefined') {
                const editorId = textarea.id;
                if (editorId && tinyMCE.get(editorId)) {
                    // Use raw format to preserve HTML
                    tinyMCE.get(editorId).setContent(sanitizedContent, {format: 'raw'});
                    console.log(`Updated excerpt in TinyMCE editor ${editorId} with preserved HTML`);
                    
                    // Configure TinyMCE
                    try {
                        const editor = tinyMCE.get(editorId);
                        if (editor && editor.settings) {
                            editor.settings.verify_html = false;
                            editor.settings.extended_valid_elements = '*[*]';
                            editor.settings.valid_children = '+body[style],+body[script],+div[*],+h2[div],+h3[div]';
                        }
                    } catch (e) {
                        console.error('Error configuring TinyMCE for excerpt editor:', e);
                    }
                }
            }
        }
    }
}

/**
 * Update Gutenberg block editor content
 * @param {string} content - The content to set
 */
function updateGutenbergContent(content) {
    // Sanitize content to remove any markdown code markers while preserving HTML
    const sanitizedContent = sanitizeContent(content, true);
    
    // For Gutenberg editor, we need to update via the editor API
    if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch && wp.data.select) {
        try {
            const editor = wp.data.dispatch('core/editor');
            if (editor && editor.editPost) {
                // For Gutenberg, we need to ensure the content is properly handled as HTML
                // Create blocks from the HTML content to preserve formatting
                if (typeof wp.blocks !== 'undefined' && wp.blocks.rawHandler) {
                    try {
                        const blocks = wp.blocks.rawHandler({ HTML: sanitizedContent });
                        if (blocks && blocks.length) {
                            // If we successfully parsed blocks, use them
                            editor.resetBlocks(blocks);
                            console.log('Updated content in Gutenberg editor with parsed blocks');
                            return;
                        }
                    } catch (blockError) {
                        console.error('Error parsing content into blocks:', blockError);
                    }
                }
                
                // Fallback to direct content update
                editor.editPost({ content: sanitizedContent });
                console.log('Updated content in Gutenberg editor');
            }
        } catch (e) {
            console.error('Error updating Gutenberg content:', e);
        }
    }
}

/**
 * Update Gutenberg block editor excerpt
 * @param {string} content - The content to set
 */
function updateGutenbergExcerpt(content) {
    // Sanitize content to remove any markdown code markers while preserving HTML
    const sanitizedContent = sanitizeContent(content, true);
    
    // For Gutenberg editor, we need to update via the editor API
    if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch && wp.data.select) {
        try {
            const editor = wp.data.dispatch('core/editor');
            if (editor && editor.editPost) {
                editor.editPost({ excerpt: sanitizedContent });
                console.log('Updated excerpt in Gutenberg editor');
            }
        } catch (e) {
            console.error('Error updating Gutenberg excerpt:', e);
        }
    }
}

/**
 * Process secondary keywords directly after generation (without intermediate step)
 * @param {string} secondaryKeywordsStr - String of comma-separated keywords
 */
function processSecondaryKeywordsDirectly(secondaryKeywordsStr) {
    if (!secondaryKeywordsStr || secondaryKeywordsStr.trim() === '') {
        console.log('No secondary keywords to process');
        return;
    }
    
    // Add styles for smaller keyword tags
    if (!document.getElementById('aysa-keyword-tags-style')) {
        const style = document.createElement('style');
        style.id = 'aysa-keyword-tags-style';
        style.textContent = `
            .aysa-keyword-tag {
                display: inline-flex;
                align-items: center;
                background: #f0f0f1;
                border: 1px solid #c3c4c7;
                border-radius: 3px;
                padding: 2px 6px;
                margin: 2px;
                font-size: 11px;
                line-height: 1.4;
                color: #50575e;
            }
            .aysa-keyword-tag .remove {
                margin-left: 4px;
                padding: 0 2px;
                font-size: 10px;
                color: #787c82;
                cursor: pointer;
            }
            .aysa-keyword-tag .remove:hover {
                color: #d63638;
            }
            #secondary-keywords-container {
                display: flex;
                flex-wrap: wrap;
                gap: 2px;
                padding: 4px;
                min-height: 30px;
                background: #fff;
                border: 1px solid #c3c4c7;
                border-radius: 3px;
            }
        `;
        document.head.appendChild(style);
    }
    
    // Obținem referința la câmpul principal
    const mainInput = document.getElementById('aysa-entity-second-keyword');
    if (!mainInput) {
        console.error('Secondary keywords field not found.');
        return;
    }
    
    // Obținem cuvintele cheie principale și secundare existente
    const mainKeyword = document.getElementById('aysa-entity-keyword')?.value.trim() || '';
    const existingKeywordsStr = mainInput.value.trim();
    const existingKeywords = existingKeywordsStr ? 
        existingKeywordsStr.split(',').map(k => k.trim()).filter(k => k !== '') : 
        [];
    
    // Procesăm cuvintele cheie sugerate
    const suggestedKeywords = secondaryKeywordsStr.split(',')
        .map(k => k.trim())
        .filter(k => k !== '' && k !== mainKeyword);
    
    if (suggestedKeywords.length === 0) {
        console.log('No valid keywords found in suggestions.');
        return;
    }
    
    // Înainte de a modifica UI-ul, verificăm ce cuvinte cheie sunt noi
    const newKeywords = suggestedKeywords.filter(k => !existingKeywords.includes(k));
    
    if (newKeywords.length === 0) {
        // Toate cuvintele cheie există deja, dar să renderizăm tag-urile existente
        console.log('🔥 All keywords exist, but ensuring they are rendered as tags');
        showToast('All suggested keywords already exist as secondary keywords.', 'info');
        
        // Renderizăm totuși keywords-urile existente ca tags
        setTimeout(() => {
                            if (typeof renderFallbackSecondaryKeywordTags === 'function') {
                    console.log('🔥 Calling renderFallbackSecondaryKeywordTags for existing keywords');
                    renderFallbackSecondaryKeywordTags();
                } else if (typeof window.renderFallbackSecondaryKeywordTags === 'function') {
                    console.log('🔥 Calling window.renderFallbackSecondaryKeywordTags for existing keywords');
                    window.renderFallbackSecondaryKeywordTags();
                                } else {
                    // Use our manual render function for existing keywords
                    console.log('🔥 Using renderSecondaryKeywordTagsManually for existing keywords');
                    const existingKeywordsStr = existingKeywords.join(', ');
                    renderSecondaryKeywordTagsManually(existingKeywordsStr);
                }
        }, 100);
        
        return;
    }
    
    // Adăugăm cuvintele cheie noi în UI
    const allKeywords = [...existingKeywords, ...newKeywords];
    mainInput.value = allKeywords.join(', ');
    
    // Afișăm un mesaj de debug
    console.log('DEBUG: Starting to process', newKeywords.length, 'new suggested keywords');
    console.log('DEBUG: New suggested keywords:', newKeywords);
    
    // Pregătim datele pentru bulk insert în loc de multiple cereri individuale
    prepareBulkInsertKeywords(newKeywords);
    
    // Actualizăm tag-urile în metabox - apelăm funcția corectă din aysa-keywords.js
    console.log('🔥 processSecondaryKeywordsDirectly: Attempting to render secondary keyword tags...');
    console.log('🔥 processSecondaryKeywordsDirectly: Secondary keywords field value:', mainInput.value);
    
    // Ensure the input field is updated before calling render function
    mainInput.dispatchEvent(new Event('input', { bubbles: true }));
    mainInput.dispatchEvent(new Event('change', { bubbles: true }));
    
    // Wait a moment for the DOM to update, then call render function
    setTimeout(() => {
        if (typeof window.renderSecondaryKeywordTags === 'function') {
            console.log('🔥 processSecondaryKeywordsDirectly: Using window.renderSecondaryKeywordTags');
            window.renderSecondaryKeywordTags();
            console.log('🔥 processSecondaryKeywordsDirectly: Called window.renderSecondaryKeywordTags successfully');
        } else if (typeof renderSecondaryKeywordTags === 'function') {
            console.log('🔥 processSecondaryKeywordsDirectly: Using global renderSecondaryKeywordTags');
            renderSecondaryKeywordTags();
            console.log('🔥 processSecondaryKeywordsDirectly: Called global renderSecondaryKeywordTags successfully');
        } else {
            console.log('🔥 processSecondaryKeywordsDirectly: renderSecondaryKeywordTags not found, manually creating tags...');
            
            // Manually create tags if the function is not available
            const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
            if (secondaryKeywordsContainer) {
                // Clear existing content
                secondaryKeywordsContainer.innerHTML = '';
                
                // Create tags for each keyword
                allKeywords.forEach(keyword => {
                    if (keyword && keyword.trim()) {
                        const tag = document.createElement('div');
                        tag.className = 'keyword-tag';
                        tag.innerHTML = `
                            <span class="tag-text">${keyword.trim()}</span>
                            <span class="tag-remove">×</span>
                        `;
                        
                        // Add remove functionality using the proper removeKeywordTag function if available
                        tag.querySelector('.tag-remove').addEventListener('click', function(e) {
                            e.stopPropagation();
                            
                            // Try to use the proper removeKeywordTag function from aysa-keywords.js if available
                            if (typeof window.removeKeywordTag === 'function') {
                                console.log('🔥 Using proper removeKeywordTag function with modal');
                                window.removeKeywordTag(tag, keyword.trim());
                            } else if (typeof removeKeywordTag === 'function') {
                                console.log('🔥 Using global removeKeywordTag function with modal');
                                removeKeywordTag(tag, keyword.trim());
                            } else {
                                console.log('🔥 Fallback: Using simple remove without modal');
                                // Fallback: Remove this keyword from the input and re-render
                                const currentKeywords = mainInput.value.split(',').map(k => k.trim()).filter(k => k !== keyword.trim());
                                mainInput.value = currentKeywords.join(', ');
                                tag.remove();
                            }
                        });
                        
                        secondaryKeywordsContainer.appendChild(tag);
                    }
                });
                
                console.log('🔥 processSecondaryKeywordsDirectly: Manually created', allKeywords.length, 'keyword tags');
            } else {
                console.error('🔥 processSecondaryKeywordsDirectly: secondary-keywords-container not found!');
            }
        }
    }, 100); // Wait 100ms for DOM updates
}

/**
 * Prepare and send bulk insert request for secondary keywords
 * @param {Array} keywords - Array of keywords to process
 */
// Function to determine keyword intent automatically  
function determineKeywordIntent(keyword) {
    const lowerKeyword = keyword.toLowerCase().trim();
    
    // Transactional intent keywords
    const transactionalPatterns = [
        'buy', 'purchase', 'order', 'shop', 'price', 'cost', 'deal', 'discount', 
        'sale', 'offer', 'coupon', 'cheap', 'affordable', 'best price', 'for sale',
        'online store', 'cart', 'checkout', 'payment', 'shipping'
    ];
    
    // Commercial investigation keywords
    const commercialPatterns = [
        'best', 'top', 'review', 'compare', 'vs', 'versus', 'alternative', 
        'recommendation', 'good', 'better', 'rating', 'testimonial', 'opinion',
        'pros and cons', 'which', 'should i', 'worth it'
    ];
    
    // Informational intent keywords
    const informationalPatterns = [
        'how to', 'what is', 'how do', 'why', 'when', 'where', 'guide', 'tutorial',
        'tips', 'learn', 'understand', 'explain', 'definition', 'meaning', 'help',
        'example', 'step by step', 'beginner', 'basics'
    ];
    
    // Navigational intent keywords
    const navigationalPatterns = [
        'login', 'sign in', 'official', 'website', 'homepage', 'contact', 'about',
        'support', 'customer service', 'headquarters', 'location', 'address'
    ];
    
    // Check patterns in order of specificity
    for (let pattern of transactionalPatterns) {
        if (lowerKeyword.includes(pattern)) {
            return 'transactional';
        }
    }
    
    for (let pattern of commercialPatterns) {
        if (lowerKeyword.includes(pattern)) {
            return 'commercial';
        }
    }
    
    for (let pattern of informationalPatterns) {
        if (lowerKeyword.includes(pattern)) {
            return 'informational';
        }
    }
    
    for (let pattern of navigationalPatterns) {
        if (lowerKeyword.includes(pattern)) {
            return 'navigational';
        }
    }
    
    // Default to informational if no pattern matches
    return 'informational';
}

function prepareBulkInsertKeywords(keywords) {
    // Preluăm informațiile necesare pentru API call
    const entityId = typeof getEntityId === 'function' ? getEntityId() : 0;
    const entityType = typeof getEntityType === 'function' ? getEntityType() : 'Unknown';
    
    // Verificăm dacă avem ID-ul entității
    if (entityId === 0) {
        console.error('Cannot identify entity ID');
        showToast('Error: Cannot identify entity ID', 'error');
        return;
    }
    
    // Obținem ID-ul proiectului
    let projectId = 0;
    if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
        projectId = parseInt(aysaParams.project_id);
    } else {
        const storedProjectId = localStorage.getItem('aysa_project_id');
        if (storedProjectId) {
            projectId = parseInt(storedProjectId);
        }
    }
    
    if (projectId === 0) {
        console.error('Cannot identify project ID');
        showToast('Error: Cannot identify project ID', 'error');
        return;
    }
    
    // Obținem numele entității
    const nameElement = document.getElementById('title') || 
                      document.querySelector('input[name="name"]') || 
                      document.getElementById('name') || 
                      document.querySelector('input[name="post_title"]');
    
    // Creăm array-ul de asocieri pentru toate cuvintele cheie
    const associationsArray = keywords.map(keyword => ({
        IdIntern: entityId,
        AssociatedOn: entityType,
        Value: nameElement ? nameElement.value : '',
        Link: window.location.href,
        Keyword: keyword,
        ProjectId: projectId,
        IsMain: false,
        SecondKeyword: '',
        Intent: determineKeywordIntent(keyword), // Add intent determination
        
        // Metadate
        MetaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
        MetaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
        MetaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
        
        // SEO settings
        TargetedSearchEngine: document.getElementById('targeted_se')?.value || '',
        TargetedCountry: document.getElementById('targeted_country')?.value || '',
        TargetedRegion: document.getElementById('targeted_region')?.value || '',
        TargetedCity: document.getElementById('targeted_city')?.value || '',
        UpdateFrequency: document.getElementById('update_frequency')?.value || '',
        LanguageOptimize: document.getElementById('language_optimize')?.value || '',
        DeviceOptimize: document.getElementById('device_optimize')?.value || '',
        
        // Advanced settings
        Index: document.getElementById('robots_index')?.checked || false,
        NoFollow: document.getElementById('robots_nofollow')?.checked || false,
        NoArchive: document.getElementById('robots_noarchive')?.checked || false,
        NoImageIndex: document.getElementById('robots_noimageindex')?.checked || false,
        NoSnippet: document.getElementById('robots_nosnippet')?.checked || false,
        MaxSnippet: parseInt(document.getElementById('max_snippet')?.value) || -1,
        MaxVideoPreview: parseInt(document.getElementById('max_video_preview')?.value) || -1,
        MaxImagePreview: document.getElementById('max_image_preview')?.value || 'small',
        CanonicalUrl: document.getElementById('canonical_url')?.value || ''
    }));
    
    console.log('DEBUG: Bulk insert payload:', associationsArray);
    showToast(`Sending ${associationsArray.length} secondary keywords for processing...`, 'info');
    
    // Facem cererea API pentru insertmany (endpoint optimizat pentru secondary keywords)
    fetch(`${getAysaApiBaseUrl()}/api/Association/insertmany`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Origin': window.location.origin
        },
        body: JSON.stringify(associationsArray),
        mode: 'cors'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('API response status: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('DEBUG: Bulk insert response:', data);
        
        // Verificăm dacă primim un array de asocieri create
        if (Array.isArray(data) && data.length > 0) {
            // Adăugăm tag-uri pentru fiecare asociere creată
            if (typeof window.createKeywordTag === 'function') {
                data.forEach(association => {
                    if (association && association.id && association.keyword) {
                        window.createKeywordTag(association.keyword, association.id);
                    }
                });
            }
            
            // Actualizăm UI-ul
            if (typeof window.renderSecondaryKeywordTags === 'function') {
                window.renderSecondaryKeywordTags();
            }
            
            // Afișăm un mesaj de succes
            showToast(`Added ${data.length} new secondary keywords successfully.`, 'success');
        } else {
            // Dacă nu primim un array valid, afișăm un mesaj generic
            showToast('Secondary keywords processed successfully.', 'success');
        }
    })
    .catch(error => {
        console.error('Error creating associations:', error);
        showToast(`Error adding keywords: ${error.message}`, 'error');
        
        // In case of error, we might want to try individual inserts as fallback
        if (confirm('Failed to add keywords in bulk. Try adding them individually?')) {
            processKeywordsSequentially(keywords);
        }
    });
}

/**
 * Process keywords sequentially with API calls when bulk insert fails
 * @param {Array} keywords - Array of keywords to process
 */
function processKeywordsSequentially(keywords) {
    let currentIndex = 0;
    let successCount = 0;
    let errorCount = 0;
    
    // Preluăm informațiile necesare pentru API call
    const entityId = typeof getEntityId === 'function' ? getEntityId() : 0;
    const entityType = typeof getEntityType === 'function' ? getEntityType() : 'Unknown';
    
    // Verificăm dacă avem ID-ul entității
    if (entityId === 0) {
        console.error('Cannot identify entity ID');
        showToast('Error: Cannot identify entity ID', 'error');
        return;
    }
    
    // Obținem ID-ul proiectului
    let projectId = 0;
    if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
        projectId = parseInt(aysaParams.project_id);
    } else {
        const storedProjectId = localStorage.getItem('aysa_project_id');
        if (storedProjectId) {
            projectId = parseInt(storedProjectId);
        }
    }
    
    if (projectId === 0) {
        console.error('Cannot identify project ID');
        showToast('Error: Cannot identify project ID', 'error');
        return;
    }
    
    // Obținem numele entității
    const nameElement = document.getElementById('title') || 
                      document.querySelector('input[name="name"]') || 
                      document.getElementById('name') || 
                      document.querySelector('input[name="post_title"]');
    
    // Show a progress indicator
    const progressContainer = document.createElement('div');
    progressContainer.id = 'aysa-keywords-progress';
    progressContainer.style.position = 'fixed';
    progressContainer.style.bottom = '20px';
    progressContainer.style.right = '20px';
    progressContainer.style.padding = '10px 15px';
    progressContainer.style.backgroundColor = '#f0f0f1';
    progressContainer.style.border = '1px solid #c3c4c7';
    progressContainer.style.borderRadius = '4px';
    progressContainer.style.boxShadow = '0 1px 2px rgba(0,0,0,0.1)';
    progressContainer.style.zIndex = '9999';
    progressContainer.innerHTML = `<div>Processing keywords: <span id="aysa-progress-count">0</span>/${keywords.length}</div>
                                 <div>Success: <span id="aysa-success-count">0</span> | Errors: <span id="aysa-error-count">0</span></div>`;
    document.body.appendChild(progressContainer);
    
    // Procesare secvențială a cuvintelor cheie
    function processNext() {
        if (currentIndex < keywords.length) {
            const keyword = keywords[currentIndex];
            console.log(`DEBUG: Processing keyword ${currentIndex + 1}/${keywords.length}: "${keyword}"`);
            
            // Update progress indicator
            document.getElementById('aysa-progress-count').textContent = currentIndex + 1;
            
            // Construim asocierea
            const newAssociation = {
                IdIntern: entityId,
                AssociatedOn: entityType,
                Value: nameElement ? nameElement.value : '',
                Link: window.location.href,
                Keyword: keyword,
                ProjectId: projectId,
                IsMain: false,
                SecondKeyword: '',
                
                // Metadate
                MetaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
                MetaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
                MetaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
                
                // SEO settings
                TargetedSearchEngine: document.getElementById('targeted_se')?.value || '',
                TargetedCountry: document.getElementById('targeted_country')?.value || '',
                TargetedRegion: document.getElementById('targeted_region')?.value || '',
                TargetedCity: document.getElementById('targeted_city')?.value || '',
                UpdateFrequency: document.getElementById('update_frequency')?.value || '',
                LanguageOptimize: document.getElementById('language_optimize')?.value || '',
                DeviceOptimize: document.getElementById('device_optimize')?.value || '',
                
                // Advanced settings
                Index: document.getElementById('robots_index')?.checked || false,
                NoFollow: document.getElementById('robots_nofollow')?.checked || false,
                NoArchive: document.getElementById('robots_noarchive')?.checked || false,
                NoImageIndex: document.getElementById('robots_noimageindex')?.checked || false,
                NoSnippet: document.getElementById('robots_nosnippet')?.checked || false,
                MaxSnippet: parseInt(document.getElementById('max_snippet')?.value) || -1,
                MaxVideoPreview: parseInt(document.getElementById('max_video_preview')?.value) || -1,
                MaxImagePreview: document.getElementById('max_image_preview')?.value || 'small',
                CanonicalUrl: document.getElementById('canonical_url')?.value || ''
            };
            
            console.log('DEBUG: API request payload:', newAssociation);
            
            // Facem apelul API
            handleKeywordConflictAndUpsert(`${getAysaApiBaseUrl()}/api/Association/upsert`, newAssociation)
            .then(response => {
                console.log(`DEBUG: API response status for keyword "${keyword}":`, response.status);
                
                if (!response.ok) {
                    throw new Error('API response status: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                console.log(`DEBUG: API response for keyword "${keyword}":`, data);
                
                successCount++;
                document.getElementById('aysa-success-count').textContent = successCount;
                
                // Adăugăm tag-ul dacă avem funcția disponibilă
                if (typeof window.createKeywordTag === 'function' && data && data.id) {
                    window.createKeywordTag(keyword, data.id);
                }
            })
            .catch(error => {
                console.error(`Error creating association for "${keyword}":`, error);
                errorCount++;
                document.getElementById('aysa-error-count').textContent = errorCount;
            })
            .finally(() => {
                currentIndex++;
                
                // Continuăm cu următorul cuvânt cheie după o pauză
                setTimeout(processNext, 500);
            });
        } else {
            // Am terminat procesarea, arătăm un mesaj final
            console.log(`DEBUG: Finished processing with ${successCount} successful associations and ${errorCount} errors`);
            
            // Remove progress indicator
            if (progressContainer.parentNode) {
                progressContainer.parentNode.removeChild(progressContainer);
            }
            
            // Actualizăm UI-ul dacă avem funcția disponibilă
            if (typeof window.renderSecondaryKeywordTags === 'function') {
                window.renderSecondaryKeywordTags();
            }
            
            // Afișăm un mesaj de succes final
            showToast(`Added ${successCount} new secondary keywords successfully. Errors: ${errorCount}`, 
                      errorCount > 0 ? 'warning' : 'success');
        }
    }
    
    // Începem procesarea
    processNext();
}

/**
 * Bind all event listeners
 */
function bindEventListeners() {
    if (window.AYSA_DEBUG === true) {
        console.log('Running bindEventListeners in aysa-actions.js');
    }
    
    // Clear any existing errors first
    clearExistingErrors();
    
    // Expose functions to global scope for cross-file access
    window.handleGenerateSuggestions = handleGenerateSuggestions;
    window.updateSuggestionFields = updateSuggestionFields;
    
    // ✅ Expose message functions globally for use in templates
    window.showKeywordWarningMessage = showKeywordWarningMessage;
    window.hideKeywordWarningMessage = hideKeywordWarningMessage;
    window.showKeywordErrorMessage = showKeywordErrorMessage;
    window.hideKeywordErrorMessage = hideKeywordErrorMessage;
    
    // ✅ Global function to update all button states and messages
    window.updateAllButtonStates = function() {
        console.log('🔄 MANUAL: Updating all button states and messages...');
        
        const keywordInput = document.getElementById('aysa-entity-keyword');
        const keyword = keywordInput ? keywordInput.value?.trim() : '';
        const hasMainKeyword = keyword !== '';
        
        console.log('🔄 Current keyword state:', {
            keyword: keyword || 'empty',
            hasMainKeyword: hasMainKeyword
        });
        
        if (!hasMainKeyword) {
            showKeywordWarningMessage();
            console.log('🔄 Showing warning messages for all buttons');
        } else {
            hideKeywordWarningMessage();
            console.log('🔄 Hiding warning messages for all buttons');
        }
        
        return {
            keyword,
            hasMainKeyword,
            buttonsFound: Array.from(document.querySelectorAll('button')).filter(btn => {
                return btn.textContent && btn.textContent.includes('Generate SEO');
            }).length
        };
    };
    
    // ✅ Global function to manually connect sidebar buttons (for debugging)
    window.connectSidebarButtons = function() {
        console.log('🚀 MANUAL: Manual connection requested...');
        
        const allButtons = Array.from(document.querySelectorAll('button'));
        console.log('🚀 MANUAL: Found', allButtons.length, 'total buttons');
        
        const generateButtons = allButtons.filter(btn => {
            return btn.textContent && btn.textContent.includes('Generate SEO');
        });
        
        console.log('🚀 MANUAL: Found', generateButtons.length, 'Generate SEO buttons:');
        let connectedCount = 0;
        
        generateButtons.forEach((btn, index) => {
            console.log('  Button #' + index + ':', {
                text: btn.textContent.trim(),
                id: btn.id || 'no id',
                className: btn.className || 'no class',
                hasListener: !!btn._hasAysaActionsListener
            });
            
            if (!btn._hasAysaActionsListener) {
                console.log('  → Connecting button #' + index);
                btn.addEventListener('click', handleGenerateSuggestions);
                btn._hasAysaActionsListener = true;
                btn.style.opacity = '1';
                btn.style.pointerEvents = 'auto';
                btn.disabled = false;
                btn.title = 'Click to generate automated SEO suggestions (Manual)';
                connectedCount++;
            } else {
                console.log('  → Button #' + index + ' already connected');
            }
        });
        
        console.log('🚀 MANUAL: Connected', connectedCount, 'new buttons');
        return connectedCount;
    };
    window.processApiResponse = processApiResponse;
    window.fetchSuggestion = fetchSuggestion;
    window.getEntityType = getEntityTypeGood;
    window.getEntityId = getEntityId;
    window.generateFallbackTitle = generateFallbackTitle;
    window.generateFallbackDescription = generateFallbackDescription;
    window.generateFallbackKeywords = generateFallbackKeywords;
    window.generateFallbackMetaKeywords = generateFallbackMetaKeywords;
    
    // Note: Edit Snippet, Get SEO, and Accept buttons were removed, so don't bind events for them
    
    // Generate Suggestions button - Main metabox button
    const generateSuggestionsBtn = document.getElementById('generate-suggestions-btn');
    if (window.AYSA_DEBUG === true) {
        console.log('🚀 DEBUG: Looking for generate-suggestions-btn, found:', generateSuggestionsBtn);
    }
    
    if (generateSuggestionsBtn && !generateSuggestionsBtn._hasAysaActionsListener) {
        console.log('🚀 DEBUG: Adding primary event listener to generate suggestions button');
        generateSuggestionsBtn.addEventListener('click', handleGenerateSuggestions);
        generateSuggestionsBtn._hasAysaActionsListener = true;
        
        // Add visual feedback to show the button is ready
        generateSuggestionsBtn.style.opacity = '1';
        generateSuggestionsBtn.style.pointerEvents = 'auto';
        
        // Add a tooltip to show the button is ready
        generateSuggestionsBtn.title = 'Click to generate automated SEO suggestions';
        
        console.log('🚀 SUCCESS: "Generate SEO Suggestions" button has been initialized and is functional');
    } else if (!generateSuggestionsBtn) {
        if (window.AYSA_DEBUG === true) {
            console.warn('🚀 AYSA: Generate Suggestions button not found in DOM');
            console.log('🚀 DEBUG: Available buttons:', Array.from(document.querySelectorAll('button')).map(b => ({id: b.id, class: b.className, text: b.textContent})));
        }
    } else {
        console.log('🚀 AYSA: Generate Suggestions button already has actions listener');
    }
    
    // ✅ SIDEBAR BUTTONS: Connect all sidebar "Generate SEO Suggestions" buttons
    const connectSidebarButtons = () => {
        console.log('🚀 SIDEBAR: Looking for sidebar Generate SEO buttons...');
        
        // Look for sidebar buttons by class and text content
        const sidebarButtons = Array.from(document.querySelectorAll('button')).filter(btn => {
            return (
                // By class name
                btn.classList.contains('aysa-sidebar-generate-btn') ||
                btn.classList.contains('aysa-sidebar-seo-button') ||
                // By text content
                (btn.textContent && btn.textContent.includes('Generate SEO')) ||
                // By ID pattern
                (btn.id && btn.id.includes('aysa-sidebar-generate'))
            ) && btn !== generateSuggestionsBtn; // Exclude main button
        });
        
        console.log('🚀 SIDEBAR: Found', sidebarButtons.length, 'sidebar Generate SEO buttons');
        
        sidebarButtons.forEach((btn, index) => {
            if (!btn._hasAysaActionsListener) {
                console.log('🚀 SIDEBAR: Connecting button #' + index + ':', {
                    text: btn.textContent?.trim(),
                    id: btn.id || 'no id',
                    className: btn.className || 'no class',
                    location: btn.closest('.aysa-sidebar-seo-button-container') ? 'sidebar container' : 'other'
                });
                
                // Add event listener with form submission prevention
                btn.addEventListener('click', function(e) {
                    console.log('🚀 SIDEBAR: Button clicked, preventing form submission');
                    e.preventDefault();
                    e.stopPropagation();
                    e.stopImmediatePropagation();
                    
                    // Prevent any parent form from submitting
                    const parentForm = btn.closest('form');
                    if (parentForm) {
                        console.log('🚀 SIDEBAR: Found parent form, preventing submission');
                        const originalOnSubmit = parentForm.onsubmit;
                        parentForm.onsubmit = function(formEvent) {
                            formEvent.preventDefault();
                            console.log('🚀 SIDEBAR: Form submission prevented');
                            return false;
                        };
                    }
                    
                    // Call the main AYSA function
                    handleGenerateSuggestions(e);
                    
                    return false;
                });
                btn._hasAysaActionsListener = true;
                
                // Ensure button is visible and clickable
                btn.style.opacity = '1';
                btn.style.pointerEvents = 'auto';
                btn.disabled = false;
                
                // Add tooltip
                btn.title = 'Click to generate automated SEO suggestions (Sidebar)';
                
                console.log('🚀 SUCCESS: Sidebar button #' + index + ' connected successfully');
            } else {
                console.log('🚀 SIDEBAR: Button #' + index + ' already connected');
            }
        });
        
        return sidebarButtons.length;
    };
    
    // Connect sidebar buttons immediately
    const connectedCount = connectSidebarButtons();
    
    // ✅ FLOATING BUTTONS: Connect floating buttons for pages
    const connectFloatingButtons = () => {
        const floatingButtons = document.querySelectorAll('#aysa-floating-seo-button');
        console.log('🚀 FLOATING: Found', floatingButtons.length, 'floating buttons');
        
        floatingButtons.forEach((btn, index) => {
            if (!btn._hasAysaActionsListener) {
                console.log('🚀 FLOATING: Connecting floating button #' + index);
                btn.addEventListener('click', handleGenerateSuggestions);
                btn._hasAysaActionsListener = true;
                btn.title = 'Click to generate automated SEO suggestions (Floating)';
                console.log('🚀 SUCCESS: Floating button #' + index + ' connected');
            }
        });
    };
    
    // Connect floating buttons
    connectFloatingButtons();
    
    // ✅ DYNAMIC DETECTION: Set up periodic check only when this page actually contains AYSA action buttons.
    const hasActionButtons = !!generateSuggestionsBtn ||
        connectedCount > 0 ||
        !!document.querySelector('#aysa-floating-seo-button, .aysa-sidebar-generate-btn, .aysa-sidebar-seo-button');

    if (!hasActionButtons) {
        return;
    }

    const checkForNewButtons = () => {
        const newSidebarCount = connectSidebarButtons();
        connectFloatingButtons();
        
        // Also check for any new buttons with Generate SEO text
        const allButtons = Array.from(document.querySelectorAll('button')).filter(btn => {
            return btn.textContent && 
                   btn.textContent.includes('Generate SEO') && 
                   !btn._hasAysaActionsListener;
        });
        
        if (allButtons.length > 0) {
            console.log('🚀 DYNAMIC: Found', allButtons.length, 'new Generate SEO buttons');
            allButtons.forEach((btn, index) => {
                console.log('🚀 DYNAMIC: Connecting new button #' + index + ':', btn.textContent?.trim());
                btn.addEventListener('click', handleGenerateSuggestions);
                btn._hasAysaActionsListener = true;
                btn.style.opacity = '1';
                btn.style.pointerEvents = 'auto';
                btn.disabled = false;
                btn.title = 'Click to generate automated SEO suggestions';
            });
        }
    };
    
    // Check for new buttons every 3 seconds
    setInterval(checkForNewButtons, 3000);
    
    // Also check when DOM changes (for dynamic content like Gutenberg)
    if (typeof MutationObserver !== 'undefined') {
        const observer = new MutationObserver((mutations) => {
            let shouldCheck = false;
            mutations.forEach((mutation) => {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                    // Check if any new nodes contain buttons
                    mutation.addedNodes.forEach(node => {
                        if (node.nodeType === 1) { // Element node
                            const hasButtons = node.querySelector && node.querySelector('button');
                            if (hasButtons || node.tagName === 'BUTTON') {
                                shouldCheck = true;
                            }
                        }
                    });
                }
            });
            if (shouldCheck) {
                setTimeout(checkForNewButtons, 500);
            }
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        
        console.log('🚀 SUCCESS: MutationObserver set up for dynamic button detection');
    }
    
    console.log('🚀 SUCCESS: All Generate SEO buttons connected - Main:', !!generateSuggestionsBtn, 'Sidebar:', connectedCount);
    
    // ✅ NEW: Add keyword input validation and visual feedback
    setupKeywordValidation();
    
    // Revert Permalink button
    const revertPermalinkBtn = document.getElementById('aysa-revert-permalink');
    if (revertPermalinkBtn && !revertPermalinkBtn._hasRevertListener) {
        revertPermalinkBtn.addEventListener('click', function(e) {
            e.preventDefault();
            
            const permalinkInput = document.getElementById('post_name') || document.getElementById('slug');
            if (permalinkInput && permalinkInput.dataset.originalValue) {
                permalinkInput.value = permalinkInput.dataset.originalValue;
                permalinkInput.dispatchEvent(new Event('change'));
                showToast('Permalink reverted to original value', 'info');
            } else {
                showToast('No original permalink found to revert to', 'error');
            }
        });
        revertPermalinkBtn._hasRevertListener = true;
        console.log('DEBUG: Added event listener to Revert Permalink button');
    } else if (!revertPermalinkBtn) {
        // Încearcă să adauge butonul de revert dacă nu există
        addPermalinkRevertButton();
    }
    
    // Note: Accept buttons are no longer needed since we directly update fields
}

/**
 * ✅ NEW: Setup keyword validation and visual feedback
 */
function setupKeywordValidation() {
    const keywordInput = document.getElementById('aysa-entity-keyword');
    const generateBtn = document.getElementById('generate-suggestions-btn');
    
    if (!keywordInput || !generateBtn) {
        console.log('🔍 Keyword input or generate button not found, skipping validation setup');
        return;
    }
    
    console.log('🔍 Setting up keyword validation and visual feedback');
    
    // Function to validate and update button state
    const updateButtonState = () => {
        // ✅ Safe check for keywordInput existence
        if (!keywordInput) {
            console.warn('🔍 ⚠️ Keyword input not found, skipping validation');
            return;
        }
        
        const keyword = keywordInput.value ? keywordInput.value.trim() : '';
        const entityName = getEntityName();
        
        // ✅ Safe check for generateBtn existence
        if (!generateBtn) {
            console.warn('🔍 ⚠️ Generate button not found, skipping button state update');
            return;
        }
        
        // Check if we have a keyword or can use entity name
        const hasValidKeyword = keyword || entityName;
        const hasMainKeyword = keyword !== '';
        
        // Always keep button enabled as per request
        generateBtn.disabled = false;
        generateBtn.classList.add('keyword-ready');
        
        if (hasValidKeyword) {
            // Show appropriate title and hide messages
            generateBtn.title = keyword ? 
                `✅ Generate SEO suggestions for "${keyword}"` : 
                `✅ Generate SEO suggestions for "${entityName}"`;
            
            // Update keyword input visual state
            if (keyword) {
                keywordInput.classList.add('has-value');
            } else {
                keywordInput.classList.remove('has-value');
            }
            
            // Show/hide warning message based on main keyword
            if (!hasMainKeyword) {
                showKeywordWarningMessage();
            } else {
                hideKeywordWarningMessage();
            }
            
            console.log('🔍 ✅ Button enabled - keyword:', keyword || `entity: ${entityName}`);
        } else {
            // Keep button enabled but show warning instead of error
            generateBtn.title = '⚠️ Will try to use title as keyword when clicked';
            keywordInput.classList.remove('has-value');
            
            // Show warning message instead of error message
            showKeywordWarningMessage();
            
            console.log('🔍 ⚠️ No keyword or entity name available - will try to detect on click');
        }
    };
    
    // Function to get entity name from various possible inputs
    const getEntityName = () => {
        let entityName = '';
        
        // 1. For categories
        const categoryNameElement = document.getElementById('name');
        if (categoryNameElement && categoryNameElement.value) {
            entityName = categoryNameElement.value.trim();
        }
        
        // 2. For posts/pages - try classic editor first
        if (!entityName) {
            const postTitleElement = document.querySelector('input[name="post_title"]') || document.getElementById('title');
            if (postTitleElement && postTitleElement.value) {
                entityName = postTitleElement.value.trim();
            }
        }
        
        // 3. For posts/pages - try Gutenberg editor API
        if (!entityName && typeof wp !== 'undefined' && wp.data && wp.data.select) {
            try {
                const currentPost = wp.data.select('core/editor').getCurrentPost();
                if (currentPost && currentPost.title) {
                    entityName = currentPost.title.trim();
                }
            } catch (e) {
                // Silently fail, try other methods
            }
        }
        
        // 4. For posts/pages - try Gutenberg DOM elements
        if (!entityName) {
            const gutenbergTitleElement = document.querySelector('.editor-post-title__input') || 
                                        document.querySelector('textarea.editor-post-title__input') ||
                                        document.querySelector('[aria-label*="title" i]');
            if (gutenbergTitleElement) {
                entityName = gutenbergTitleElement.value?.trim() || gutenbergTitleElement.textContent?.trim() || '';
            }
        }
        
        return entityName;
    };
    
    // Add event listeners for real-time validation
    if (keywordInput && typeof keywordInput.addEventListener === 'function') {
        try {
            keywordInput.addEventListener('input', updateButtonState);
            keywordInput.addEventListener('blur', updateButtonState);
            keywordInput.addEventListener('focus', updateButtonState);
            console.log('🔍 ✅ Added event listeners to keyword input');
        } catch (error) {
            console.warn('🔍 ⚠️ Failed to add event listeners to keyword input:', error);
        }
    } else {
        console.warn('🔍 ⚠️ Keyword input not found or not valid');
    }
    
    // Also listen to entity name changes
    const entityNameInputs = [
        document.getElementById('name'),
        document.querySelector('input[name="post_title"]'),
        document.getElementById('title')
    ].filter(el => el);
    
    // ✅ Safe event listener attachment
    entityNameInputs.forEach(input => {
        if (input && typeof input.addEventListener === 'function') {
            try {
                input.addEventListener('input', updateButtonState);
                input.addEventListener('blur', updateButtonState);
                console.log('🔍 ✅ Added event listeners to:', input.id || input.name || 'unnamed input');
            } catch (error) {
                console.warn('🔍 ⚠️ Failed to add event listeners to input:', error);
            }
        }
    });
    
    // Initial validation on page load
    updateButtonState();
    
    // Additional check after DOM is fully loaded
    setTimeout(updateButtonState, 1000);
    
    // For Gutenberg, also listen to wp.data changes and add more delays
    if (typeof wp !== 'undefined' && wp.data && wp.data.subscribe) {
        try {
            wp.data.subscribe(() => {
                // Delay the update to allow Gutenberg to finish updating
                setTimeout(updateButtonState, 100);
            });
            console.log('🔍 ✅ Subscribed to Gutenberg data changes');
            
            // Additional delayed validation for Gutenberg (title might not be available immediately)
            setTimeout(() => {
                console.log('🔍 Running delayed Gutenberg validation...');
                updateButtonState();
            }, 2000);
            
            setTimeout(() => {
                console.log('🔍 Running final Gutenberg validation...');
                updateButtonState();
            }, 5000);
        } catch (e) {
            console.warn('🔍 Could not subscribe to Gutenberg data changes:', e);
        }
    }
    
    // ✅ Show success message when system is ready
    setTimeout(() => {
        if (keywordInput && keywordInput.value) {
            const keyword = keywordInput.value.trim();
            if (keyword) {
                console.log('🔍 ✅ Keyword validation system ready - detected existing keyword:', keyword);
                // Toast removed - visual feedback is sufficient
            }
        }
    }, 1500);
    
    console.log('🔍 ✅ Keyword validation setup complete');
}

/**
 * Show warning message above Generate SEO Suggestions button(s)
 */
function showKeywordWarningMessage() {
    // Find all Generate SEO Suggestions buttons - including floating button by ID and class
    const buttons = [];
    
    // 1. Find buttons by text content
    const textButtons = Array.from(document.querySelectorAll('button')).filter(btn => {
        return btn.textContent && btn.textContent.includes('Generate SEO');
    });
    buttons.push(...textButtons);
    
    // 2. Find floating button specifically by ID
    const floatingButton = document.getElementById('aysa-floating-seo-button');
    if (floatingButton && !buttons.includes(floatingButton)) {
        buttons.push(floatingButton);
    }
    
    // 3. Find sidebar buttons by class
    const sidebarButtons = Array.from(document.querySelectorAll('.aysa-sidebar-generate-btn')).filter(btn => {
        return !buttons.includes(btn);
    });
    buttons.push(...sidebarButtons);
    
    console.log('🚀 WARNING: Showing warning message above', buttons.length, 'buttons (text:', textButtons.length, ', floating:', floatingButton ? 1 : 0, ', sidebar:', sidebarButtons.length, ')');
    
    buttons.forEach((button, index) => {
        if (!button || !button.parentNode) return;
        
        // For floating button, we need to handle the fixed positioning differently
        const isFloatingButton = button.id === 'aysa-floating-seo-button';
        
        // Check if warning already exists for this button
        const existingWarning = isFloatingButton ? 
            document.querySelector('.aysa-keyword-warning-floating-' + index) :
            button.parentNode.querySelector('.aysa-keyword-warning-' + index);
        if (existingWarning) return;
        
        // Create warning message
        const warningDiv = document.createElement('div');
        warningDiv.className = isFloatingButton ? 
            'aysa-keyword-warning aysa-keyword-warning-floating-' + index :
            'aysa-keyword-warning aysa-keyword-warning-' + index;
        
        if (isFloatingButton) {
            // Special styling for floating button warning
            warningDiv.style.cssText = `
                position: fixed;
                top: calc(50% - 60px);
                left: 20px;
                z-index: 999998;
                background: #fff3cd;
                color: #856404;
                border: 1px solid #ffeaa7;
                border-radius: 4px;
                padding: 8px 12px;
                font-size: 13px;
                display: flex;
                align-items: center;
                gap: 8px;
                max-width: 200px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                animation: aysa-slide-in 0.5s ease-out;
            `;
        } else {
            // Normal styling for other buttons
            warningDiv.style.cssText = `
                background: #fff3cd;
                color: #856404;
                border: 1px solid #ffeaa7;
                border-radius: 4px;
                padding: 8px 12px;
                margin-bottom: 10px;
                font-size: 13px;
                display: flex;
                align-items: center;
                gap: 8px;
            `;
        }
        
        warningDiv.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
            </svg>
            Please setup the Main keyword before
        `;
        
        // Insert warning message
        if (isFloatingButton) {
            // For floating button, add to body
            document.body.appendChild(warningDiv);
        } else {
            // For other buttons, insert before button
            button.parentNode.insertBefore(warningDiv, button);
        }
        
        console.log('🚀 WARNING: Added warning message above button #' + index + (isFloatingButton ? ' (floating)' : ''));
    });
}

/**
 * Hide warning message above Generate SEO Suggestions button(s)
 */
function hideKeywordWarningMessage() {
    // Remove all warning messages (including floating ones)
    const existingWarnings = document.querySelectorAll('.aysa-keyword-warning');
    console.log('🚀 WARNING: Hiding', existingWarnings.length, 'warning messages');
    
    existingWarnings.forEach((warning, index) => {
        const isFloating = warning.className.includes('floating');
        console.log('🚀 WARNING: Removing warning message #' + index + (isFloating ? ' (floating)' : ''));
        warning.remove();
    });
}

/**
 * Show error message above Generate SEO Suggestions button(s)
 */
function showKeywordErrorMessage() {
    // Remove existing messages first
    hideKeywordWarningMessage();
    hideKeywordErrorMessage();
    
    // Find all Generate SEO Suggestions buttons - including floating button by ID and class
    const buttons = [];
    
    // 1. Find buttons by text content
    const textButtons = Array.from(document.querySelectorAll('button')).filter(btn => {
        return btn.textContent && btn.textContent.includes('Generate SEO');
    });
    buttons.push(...textButtons);
    
    // 2. Find floating button specifically by ID
    const floatingButton = document.getElementById('aysa-floating-seo-button');
    if (floatingButton && !buttons.includes(floatingButton)) {
        buttons.push(floatingButton);
    }
    
    // 3. Find sidebar buttons by class
    const sidebarButtons = Array.from(document.querySelectorAll('.aysa-sidebar-generate-btn')).filter(btn => {
        return !buttons.includes(btn);
    });
    buttons.push(...sidebarButtons);
    
    console.log('🚀 ERROR: Showing error message above', buttons.length, 'buttons');
    
    buttons.forEach((button, index) => {
        if (!button || !button.parentNode) return;
        
        // For floating button, we need to handle the fixed positioning differently
        const isFloatingButton = button.id === 'aysa-floating-seo-button';
        
        // Create error message
        const errorDiv = document.createElement('div');
        errorDiv.className = isFloatingButton ? 
            'aysa-keyword-error aysa-keyword-error-floating-' + index :
            'aysa-keyword-error aysa-keyword-error-' + index;
        
        if (isFloatingButton) {
            // Special styling for floating button error
            errorDiv.style.cssText = `
                position: fixed;
                top: calc(50% - 60px);
                left: 20px;
                z-index: 999998;
                background: #f8d7da;
                color: #721c24;
                border: 1px solid #f5c6cb;
                border-radius: 4px;
                padding: 8px 12px;
                font-size: 13px;
                display: flex;
                align-items: center;
                gap: 8px;
                max-width: 200px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                animation: aysa-slide-in 0.5s ease-out;
            `;
        } else {
            // Normal styling for other buttons
            errorDiv.style.cssText = `
                background: #f8d7da;
                color: #721c24;
                border: 1px solid #f5c6cb;
                border-radius: 4px;
                padding: 8px 12px;
                margin-bottom: 10px;
                font-size: 13px;
                display: flex;
                align-items: center;
                gap: 8px;
            `;
        }
        
        errorDiv.innerHTML = `
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
            </svg>
            Cannot generate SEO suggestions without a keyword or title
        `;
        
        // Insert error message
        if (isFloatingButton) {
            // For floating button, add to body
            document.body.appendChild(errorDiv);
        } else {
            // For other buttons, insert before button
            button.parentNode.insertBefore(errorDiv, button);
        }
        
        console.log('🚀 ERROR: Added error message above button #' + index + (isFloatingButton ? ' (floating)' : ''));
    });
}

/**
 * Hide error message above Generate SEO Suggestions button(s)
 */
function hideKeywordErrorMessage() {
    // Remove all error messages (including floating ones)
    const existingErrors = document.querySelectorAll('.aysa-keyword-error');
    console.log('🚀 ERROR: Hiding', existingErrors.length, 'error messages');
    
    existingErrors.forEach((error, index) => {
        const isFloating = error.className.includes('floating');
        console.log('🚀 ERROR: Removing error message #' + index + (isFloating ? ' (floating)' : ''));
        error.remove();
    });
}

/**
 * Handle Get SEO button click
 * Loads SEO data from API
 */
function handleGetSeo(e) {
    e.preventDefault();
    
    const button = this;
    const originalText = button.textContent;
    
    // Show loading state
    button.disabled = true;
    button.innerHTML = '<svg class="spin" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill="none" d="M0 0h24v24H0z"/><path d="M5.463 4.433A9.961 9.961 0 0 1 12 2c5.523 0 10 4.477 10 10-2 0-2-2-4-2-2 0-2 2-4 2s-2-2-4-2c-2 0-2 2-4 2v7c0 .557-.347 1.008-1 1.5v.5h-1a1 1 0 0 1-1-1v-9l-.967-1.796C4.33 7.884 4 9.89 4 12c0 4.418 3.582 8 8 8s8-3.582 8-8c0-4.418-3.582-8-8-8-3.244 0-6.137 2.025-7.537 5.077" fill="currentColor"/></svg> Loading...';
    
    // Add a style tag for the spinning animation if it doesn't exist
    if (!document.getElementById('spin-animation-style')) {
        const style = document.createElement('style');
        style.id = 'spin-animation-style';
        style.textContent = `
            @keyframes spin {
                from {
                    transform: rotate(0deg);
                }
                to {
                    transform: rotate(360deg);
                }
            }
            .spin {
                animation: spin 1.5s linear infinite;
            }
        `;
        document.head.appendChild(style);
    }
    
    // Call loadDataFromAPI if it exists, otherwise show an error
    if (typeof loadDataFromAPI === 'function') {
        loadDataFromAPI();
        
        // Reset button after 2 seconds
        setTimeout(() => {
            button.disabled = false;
            button.innerHTML = originalText;
        }, 2000);
    } else {
        if (window.AYSA_DEBUG === true) {
            console.warn('loadDataFromAPI function not found in this editor context.');
        }
        button.disabled = false;
        button.innerHTML = originalText;
    }
}

/**
 * Generate fallback keywords when API fails
 * @param {string} keyword - Main keyword
 * @param {string} entityType - Entity type (Product, Page, Category)
 * @returns {string} Comma-separated keywords
 */
 function generateFallbackKeywords(keyword, entityType) {
     console.log('Using fallback keywords for', keyword, entityType);
     
     // Base variations
     let variations = [
         keyword + ' online',
         keyword + ' pret',
         keyword + ' romania',
         'cel mai bun ' + keyword,
         keyword + ' ieftin',
         keyword + ' calitate'
     ];
     
     // Add type-specific variations
     if (entityType === 'Product') {
         variations = variations.concat([
             'cumpara ' + keyword,
             keyword + ' review',
             keyword + ' shop',
             keyword + ' magazin',
             keyword + ' reducere'
         ]);
     } else if (entityType === 'Category') {
         variations = variations.concat([
             keyword + ' categorii',
             keyword + ' tipuri',
             keyword + ' modele',
             keyword + ' catalog',
             keyword + ' exemple'
         ]);
     } else { // Page or default
         variations = variations.concat([
             keyword + ' informatii',
             keyword + ' ghid',
             keyword + ' sfaturi',
             keyword + ' beneficii',
             keyword + ' caracteristici'
         ]);
     }
     
     // Return a random selection of 5-8 keywords
     const shuffled = variations.sort(() => 0.5 - Math.random());
     const selected = shuffled.slice(0, Math.floor(Math.random() * 3) + 5);
     
     console.log('Generated fallback keywords:', selected.join(', '));
     return selected.join(', ');
 }

/**
 * Get general information from database
 * @returns {Promise<Object>} General information object
 */
async function getGeneralInformation() {
    try {
        const projectId = getProjectId();
        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
 * @returns {Promise<string>} Tone of voice
 */
async function getToneOfVoice() {
    try {
        const projectId = getProjectId();
        if (!projectId) {
            console.warn('No project ID found for tone of voice');
            return '';
        }

        const url = `${getAysaApiBaseUrl()}/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.selectedTone || '';
        } else {
            console.warn('⚠️ Failed to fetch tone of voice:', response.status);
            return '';
        }
    } catch (error) {
        console.warn('⚠️ Error fetching tone of voice:', error);
        return '';
    }
}

/**
 * Get the actual public URL for the current entity being edited
 * This extracts the real product/page URL, not the admin edit URL
 * @returns {string} Public URL
 */
function getEntityPublicUrl() {
    try {
        console.log('🔍 Detecting entity public URL...');
        const baseUrl = window.location.origin;
        
        // Method 1: Try to get permalink from WordPress admin interface (most reliable)
        const permalinkEl = document.querySelector('#sample-permalink a');
        if (permalinkEl && permalinkEl.href && !permalinkEl.href.includes('/wp-admin/')) {
            console.log('📄 Found WordPress permalink:', permalinkEl.href);
            return cleanUrl(permalinkEl.href);
        }
        
        // Method 2: Try to get from "View" or "Preview" buttons
        const viewPostLink = document.querySelector('#view-post-btn a, .preview, a[href*="preview=true"]');
        if (viewPostLink && viewPostLink.href && !viewPostLink.href.includes('/wp-admin/')) {
            const cleanedUrl = viewPostLink.href
                .replace(/[?&]preview=true/g, '')
                .replace(/[?&]preview_id=\d+/g, '')
                .replace(/[?&]preview_nonce=[^&]+/g, '');
            console.log('📄 Found view/preview link:', cleanedUrl);
            return cleanUrl(cleanedUrl);
        }
        
        // Method 3: Try to construct from post data
        const postId = getPostId();
        if (postId > 0) {
            const contentType = getEntityTypeGood();
            const slug = getEntitySlug();
            
            if (slug) {
                let constructedUrl = baseUrl;
                
                // Get WordPress site structure hints
                const siteUrl = getSiteUrlFromDOM();
                if (siteUrl && siteUrl !== baseUrl) {
                    constructedUrl = siteUrl;
                }
                
                if (contentType === 'Product') {
                    // Try to detect WooCommerce shop base
                    const shopBase = getWooCommerceProductBase();
                    constructedUrl += shopBase + slug + '/';
                } else if (contentType === 'Page') {
                    // For pages, they're usually at root level unless there's a page hierarchy
                    const parentPageSlug = getParentPageSlug();
                    if (parentPageSlug) {
                        constructedUrl += '/' + parentPageSlug + '/' + slug + '/';
                    } else {
                        constructedUrl += '/' + slug + '/';
                    }
                } else {
                    // Default for posts
                    constructedUrl += '/' + slug + '/';
                }
                
                console.log('📄 Constructed URL:', constructedUrl);
                return cleanUrl(constructedUrl);
            }
        }
        
        // Fallback to current page URL cleaned up
        const fallbackUrl = window.location.href.replace(/\/wp-admin\/.*$/, '/');
        console.log('📄 Using fallback URL:', fallbackUrl);
        return fallbackUrl;
        
    } catch (error) {
        console.warn('⚠️ Error getting entity public URL:', error);
        return window.location.origin;
    }
}

/**
 * Helper function to clean URL
 */
function cleanUrl(url) {
    return url.replace(/[?&]preview=true/g, '')
              .replace(/[?&]preview_id=\d+/g, '')
              .replace(/[?&]preview_nonce=[^&]+/g, '')
              .replace(/\/+$/, '') + '/';
}

/**
 * Get entity slug from various sources
 */
function getEntitySlug() {
    // Try to get from permalink field
    const permalinkField = document.querySelector('#post_name, #slug, input[name="slug"]');
    if (permalinkField && permalinkField.value) {
        return permalinkField.value;
    }
    
    // Try to get from sample permalink
    const samplePermalink = document.getElementById('sample-permalink');
    if (samplePermalink) {
        const permalinkText = samplePermalink.textContent;
        const slugMatch = permalinkText.match(/\/([^\/]+)\/?$/);
        if (slugMatch && slugMatch[1]) {
            return slugMatch[1];
        }
    }
    
    // Fallback: generate from title
    const titleField = document.querySelector('#title, input[name="post_title"], #name');
    if (titleField && titleField.value) {
        return titleField.value.toLowerCase()
                              .replace(/[^a-z0-9\s-]/g, '')
                              .replace(/\s+/g, '-')
                              .replace(/-+/g, '-')
                              .replace(/^-|-$/g, '');
    }
    
    return '';
}

/**
 * Get site URL from DOM
 */
function getSiteUrlFromDOM() {
    // Try to get from admin bar
    const adminBarSiteLink = document.querySelector('#wp-admin-bar-site-name a');
    if (adminBarSiteLink && adminBarSiteLink.href) {
        return adminBarSiteLink.href;
    }
    
    // Try to get from canonical link
    const canonical = document.querySelector('link[rel="canonical"]');
    if (canonical && canonical.href) {
        const url = new URL(canonical.href);
        return url.origin;
    }
    
    return window.location.origin;
}

/**
 * Get WooCommerce product base
 */
function getWooCommerceProductBase() {
    // Default WooCommerce product base
    return '/product/';
}

/**
 * Get parent page slug (for hierarchical pages)
 */
function getParentPageSlug() {
    const parentSelect = document.querySelector('#parent_id');
    if (parentSelect && parentSelect.selectedOptions[0] && parentSelect.selectedOptions[0].text) {
        const parentTitle = parentSelect.selectedOptions[0].text;
        return parentTitle.toLowerCase()
                         .replace(/[^a-z0-9\s-]/g, '')
                         .replace(/\s+/g, '-')
                         .replace(/-+/g, '-')
                         .replace(/^-|-$/g, '');
    }
    return '';
}

/**
 * Generate fallback title when API fails
 */
function generateFallbackTitle(keyword, entityType) {
    if (entityType === 'Product') {
        return `${keyword} - Produsul Perfect Pentru Nevoile Tale | ${document.title.split(' - ')[1] || 'Site Name'}`;
    } else if (entityType === 'Category') {
        return `${keyword} - Varietate și Calitate | ${document.title.split(' - ')[1] || 'Site Name'}`;
    } else {
        return `${keyword} - Informații Complete și Actualizate | ${document.title.split(' - ')[1] || 'Site Name'}`;
    }
}

/**
 * Generate fallback meta keywords when API fails
 */
function generateFallbackMetaKeywords(keyword, entityType) {
    // Similar to generateFallbackKeywords but with different variations
    const variations = [
        keyword,
        keyword + ' online',
        keyword + ' romania',
        'cel mai bun ' + keyword,
        keyword + ' calitate',
        keyword + ' pret'
    ];
    
    // Return with proper spacing after commas
    return variations.map(kw => kw.trim()).filter(kw => kw !== '').join(', ');
}

/**
 * Generate fallback description when API fails
 */
function generateFallbackDescription(keyword, entityType) {
    if (entityType === 'Product') {
        return `Descoperă ${keyword} la cel mai bun raport calitate-preț. Livrare rapidă, garanție extinsă și suport tehnic disponibil 24/7. Comandă acum!`;
    } else if (entityType === 'Category') {
        return `Explorează selecția noastră variată de ${keyword}. Produse de calitate, prețuri competitive și opțiuni pentru toate preferințele și bugetele.`;
    } else {
        return `Informații complete despre ${keyword}. Sfaturi de specialiști, analize detaliate și recomandări personalizate pentru a face cea mai bună alegere.`;
    }
}

/**
 * Generate fallback category description when API fails
 * @param {string} keyword - Main keyword
 * @returns {string} A basic category description
 */
function generateFallbackCategoryDescription(keyword) {
    return `Explorează selecția noastră completă de ${keyword}. Oferim o gamă variată de produse de înaltă calitate, cu prețuri competitive și livrare rapidă. Găsești tot ce ai nevoie pentru ${keyword} în magazinul nostru online, unde calitatea și satisfacția clienților sunt prioritatea noastră principală. Răsfoiește categoria și descoperă ofertele speciale disponibile chiar acum.`;
}

/**
 * Show toast notification
 * @param {string} message - Message to display
 * @param {string} type - Type of toast (success, error, info, warning)
 */
function showToast(message, type = 'info') {
    console.log(`Toast (${type}): ${message}`);
    
    // Check if there's a global toast function that is NOT this function
    if (typeof window.showToast === 'function' && window.showToast !== showToast) {
        // Use the existing function (but not if it's the same as this one)
        window.showToast(message, type);
        return;
    }
    
    // Create a toast container if it doesn't exist
    let toastContainer = document.getElementById('aysa-toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'aysa-toast-container';
        toastContainer.style.position = 'fixed';
        toastContainer.style.top = '20px';
        toastContainer.style.right = '20px';
        toastContainer.style.zIndex = '9999';
        document.body.appendChild(toastContainer);
    }
    
    // Create the toast element
    const toast = document.createElement('div');
    toast.className = `aysa-toast aysa-toast-${type}`;
    toast.style.minWidth = '250px';
    toast.style.maxWidth = '350px';
    toast.style.padding = '12px 16px';
    toast.style.borderRadius = '4px';
    toast.style.marginBottom = '10px';
    toast.style.boxShadow = '0 3px 6px rgba(0,0,0,0.16)';
    toast.style.animation = 'aysa-toast-in 0.3s ease-out forwards';
    
    // Add background color based on type
    switch (type) {
        case 'success':
            toast.style.backgroundColor = '#d4edda';
            toast.style.color = '#155724';
            toast.style.borderLeft = '4px solid #28a745';
            break;
        case 'error':
            toast.style.backgroundColor = '#f8d7da';
            toast.style.color = '#721c24';
            toast.style.borderLeft = '4px solid #dc3545';
            break;
        case 'warning':
            toast.style.backgroundColor = '#fff3cd';
            toast.style.color = '#856404';
            toast.style.borderLeft = '4px solid #ffc107';
            break;
        case 'info':
        default:
            toast.style.backgroundColor = '#d1ecf1';
            toast.style.color = '#0c5460';
            toast.style.borderLeft = '4px solid #17a2b8';
            break;
    }
    
    // Add animation styles if they don't exist
    if (!document.getElementById('aysa-toast-style')) {
        const style = document.createElement('style');
        style.id = 'aysa-toast-style';
        style.textContent = `
            @keyframes aysa-toast-in {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes aysa-toast-out {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
    }
    
    // Set the message
    toast.textContent = message;
    
    // Add to container
    toastContainer.appendChild(toast);
    
    // Remove after 3 seconds
    setTimeout(() => {
        toast.style.animation = 'aysa-toast-out 0.3s ease-in forwards';
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    }, 3000);
}

// Export showToast to window for global access
if (typeof window !== 'undefined') {
    window.showToast = showToast;
}

/**
 * Get the entity ID for API calls
 * @returns {number} Entity ID
 */
function getEntityId() {
    let entityId = 0;
    
    // Check URL parameters for category/term ID
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('tag_ID')) {
        entityId = parseInt(urlParams.get('tag_ID'));
        console.log('🚀 DEBUG: Found tag_ID in URL:', entityId);
    } 
    // Check for post ID
    else if (urlParams.get('post')) {
        entityId = parseInt(urlParams.get('post'));
        console.log('🚀 DEBUG: Found post ID in URL:', entityId);
    }
    
    // Try to get from global aysaParams if available
    if (entityId === 0 && typeof aysaParams !== 'undefined') {
        if (aysaParams.postId) {
            entityId = parseInt(aysaParams.postId);
            console.log('🚀 DEBUG: Found entity ID in aysaParams.postId:', entityId);
        } else if (aysaParams.termId) {
            entityId = parseInt(aysaParams.termId);
            console.log('🚀 DEBUG: Found entity ID in aysaParams.termId:', entityId);
        }
    }
    
    // Try to get from hidden input
    if (entityId === 0) {
        const postIdInput = document.querySelector('input[name="post_ID"]');
        if (postIdInput) {
            entityId = parseInt(postIdInput.value);
            console.log('🚀 DEBUG: Found entity ID in hidden input:', entityId);
        }
    }
    
    console.log('🚀 DEBUG: Final detected entity ID:', entityId);
    return entityId;
}

/**
 * Get the current entity type based on the URL or admin page
 * @returns {string} Entity type (Product, Category, Page)
 */
function getEntityTypeGood() {
    // Default value
    let entityType = 'Page';
    
    // Try to determine by URL
    const url = window.location.href;
    console.log('🚀 DEBUG getEntityType - URL being checked:', url);
    
    // Check URL parameters first
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('tag_ID') || urlParams.get('taxonomy')) {
        entityType = 'Category';
        console.log('🚀 DEBUG: Detected Category from URL params');
        return entityType;
    }
    
    // Check for product in URL params
    if (urlParams.get('post_type') === 'product') {
        entityType = 'Product';
        console.log('🚀 DEBUG: Detected Product from URL params');
        return entityType;
    }
    
    // Try to get from global aysaParams if available
    if (typeof aysaParams !== 'undefined') {
        if (aysaParams.entityType === 'term') {
            entityType = 'Category';
            console.log('🚀 DEBUG: Detected Category from aysaParams');
            return entityType;
        } else if (aysaParams.entityType === 'product') {
            entityType = 'Product';
            console.log('🚀 DEBUG: Detected Product from aysaParams');
            return entityType;
        }
    }

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

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

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

/** * Clear any existing error messages in the fields */
function clearExistingErrors() {
    // Clear errors from main fields now that we no longer have suggested fields
    const mainFields = [
        'aysa-entity-meta-title',
        'aysa-entity-meta-description',
        'aysa-entity-meta-keywords',
        'aysa-entity-second-keyword'
    ];
    
    mainFields.forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field) {
            // Remove error class
            field.classList.remove('has-error');
            
            // Remove error messages
            const parent = field.parentNode;
            if (parent) {
                const errorMsg = parent.querySelector('.error-message');
                if (errorMsg) {
                    errorMsg.remove();
                }
                
                // For second-keyword specifically, check if it shows an error message
                if (fieldId === 'aysa-entity-second-keyword' && field.value.startsWith('Error:')) {
                    // Clear the error
                    field.value = '';
                    
                    // Add a helpful message for users
                    const helpMsg = document.createElement('div');
                    helpMsg.className = 'help-message';
                    helpMsg.style.color = '#50575e';
                    helpMsg.style.fontSize = '12px';
                    helpMsg.style.marginTop = '5px';
                    helpMsg.innerHTML = 'Click "Generate SEO Suggestions" to get secondary keywords';
                    
                    parent.appendChild(helpMsg);
                }
            }
        }
    });
    
    // Also check containers
    const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
    if (secondaryKeywordsContainer) {
        const errorPlaceholder = secondaryKeywordsContainer.querySelector('.error-placeholder');
        if (errorPlaceholder && errorPlaceholder.textContent.includes('Error:')) {
            secondaryKeywordsContainer.innerHTML = '<div class="empty-placeholder" style="color: #999; font-style: italic;">Click "Generate SEO Suggestions" to get secondary keywords</div>';
        }
    }
}

/**
 * Format a string for use as a WordPress permalink
 * - Converts to lowercase
 * - Replaces spaces with hyphens
 * - Removes special characters
 * - Removes diacritics (accents)
 * 
 * @param {string} str - The string to format as a permalink
 * @returns {string} - The formatted permalink
 */
function formatPermalink(str) {
    if (!str) return '';
    
    // Convert to lowercase
    let permalink = str.toLowerCase();
    
    // Remove diacritics (accents)
    permalink = permalink.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
    
    // Replace spaces with hyphens
    permalink = permalink.replace(/\s+/g, '-');
    
    // Remove special characters (keep only alphanumeric, hyphens, and underscores)
    permalink = permalink.replace(/[^a-z0-9-_]/g, '');
    
    // Remove multiple consecutive hyphens
    permalink = permalink.replace(/-+/g, '-');
    
    // Remove leading or trailing hyphens
    permalink = permalink.replace(/^-+|-+$/g, '');
    
    return permalink;
}

/**
 * Adaugă butonul de revert pentru permalink
 * Poate fi apelat în orice moment pentru a asigura că butonul este prezent
 */
function addPermalinkRevertButton() {
    // Verifică dacă butonul există deja
    if (document.getElementById('aysa-permalink-revert-container')) {
        console.log('Revert container already exists, skipping creation');
        return;
    }
    
    // Obține informațiile necesare despre post și permalink
    const postId = document.querySelector('input[name="post_ID"]')?.value || 
                  document.getElementById('post_ID')?.value ||
                  new URLSearchParams(window.location.search).get('post');
                  
    const slugInput = document.getElementById('post_name') || 
                     document.getElementById('slug') || 
                     document.querySelector('input[name="post_name"]');
                     
    const permalinkContainer = document.getElementById('edit-slug-box');
    
    // Verifică dacă avem toate informațiile necesare
    if (!postId || !slugInput || !permalinkContainer) {
        console.warn('Missing required information for revert button', { 
            postId, 
            slugInput: !!slugInput,
            permalinkContainer: !!permalinkContainer
        });
        return;
    }
    
    // Get the current permalink with slug
    let currentPermalink = '';
    let currentSlug = slugInput.value;
    
    // Try multiple ways to get the proper permalink (not a preview URL)
    // 1. Try to get from the permalink displayed in the admin interface
    const viewLink = permalinkContainer.querySelector('a[href]:not(.button)');
    
    if (viewLink && viewLink.href && !viewLink.href.includes('preview=true')) {
        currentPermalink = viewLink.href;
        console.log('Found permalink from view link:', currentPermalink);
    } 
    // 2. If we can't find it or it's a preview link, build it from the sample permalink
    else {
        const samplePermalink = document.getElementById('sample-permalink');
        if (samplePermalink) {
            const permalinkText = samplePermalink.innerHTML;
            // Extract the URL from the sample permalink HTML
            const permalinkMatch = permalinkText.match(/(https?:\/\/[^"]+)/);
            if (permalinkMatch && permalinkMatch[1]) {
                currentPermalink = permalinkMatch[1];
                console.log('Extracted permalink from sample permalink:', currentPermalink);
            }
        }
    }
    
    // If we still don't have a valid permalink, try to build it
    if (!currentPermalink || currentPermalink.includes('preview=true') || currentPermalink.includes('&p=')) {
        // This is likely a post that hasn't been published yet, so we'll try to build a permalink
        const baseUrl = window.location.protocol + '//' + window.location.host;
        
        // Try to determine if we're editing a product
        const isProduct = document.body.classList.contains('post-type-product') || 
                         window.location.href.includes('post_type=product');
        
        if (isProduct && currentSlug) {
            currentPermalink = `${baseUrl}/wordpress/product/${currentSlug}/`;
            console.log('Built product permalink:', currentPermalink);
        } else if (currentSlug) {
            currentPermalink = `${baseUrl}/wordpress/${currentSlug}/`;
            console.log('Built generic permalink:', currentPermalink);
        }
    }
    
    if (!currentPermalink) {
        console.warn('Could not determine current permalink');
        return;
    }
    
    if (!currentSlug) {
        console.warn('Could not determine current slug');
        return;
    }
    
    // Generate a storage key based on post ID
    const storageKey = `aysa_original_permalink_product_${postId}`;
    
    // Get the original permalink from storage
    let originalPermalink = localStorage.getItem(storageKey);
    
    // Check if we have a valid original permalink stored
    if (!originalPermalink || originalPermalink.includes('preview=true') || originalPermalink.includes('&p=')) {
        // If the stored permalink is invalid, store the current one as original
        originalPermalink = currentPermalink;
        localStorage.setItem(storageKey, originalPermalink);
        console.log('Stored original permalink:', originalPermalink);
        
        // Since we just set the original, we don't need to show the revert option yet
        return;
    }
    
    // Ensure original permalink has the correct path structure
    if (!originalPermalink.includes('/wordpress/')) {
        const baseUrl = window.location.protocol + '//' + window.location.host;
        const originalSlug = extractSlugFromPermalink(originalPermalink);
        if (originalSlug) {
            originalPermalink = `${baseUrl}/wordpress/product/${originalSlug}/`;
            localStorage.setItem(storageKey, originalPermalink);
            console.log('Updated original permalink with correct path:', originalPermalink);
        }
    }
    
    // Extract original slug from permalink
    const originalSlug = extractSlugFromPermalink(originalPermalink);
    
    // Only show the revert option if the current slug differs from the original
    if (!originalSlug || currentSlug === originalSlug) {
        console.log('Current slug matches original, no need for revert button');
        return;
    }
    
    console.log('Current slug differs from original, showing revert option');
    
    // Create the container for the revert section
    const revertContainer = document.createElement('div');
    revertContainer.id = 'aysa-permalink-revert-container';
    revertContainer.style.marginTop = '5px';
    revertContainer.style.padding = '5px';
    revertContainer.style.backgroundColor = '#f8f8f8';
    revertContainer.style.border = '1px solid #ddd';
    revertContainer.style.borderRadius = '3px';
    
    // Add original permalink display
    const originalPermalinkDisplay = document.createElement('div');
    originalPermalinkDisplay.style.fontSize = '12px';
    originalPermalinkDisplay.style.marginBottom = '5px';
    originalPermalinkDisplay.innerHTML = `<strong>Original permalink:</strong> <span style="word-break: break-all; font-family: monospace;">${originalPermalink}</span>`;
    
    // Creează butonul
    const revertBtn = document.createElement('button');
    revertBtn.id = 'aysa-revert-permalink';
    revertBtn.type = 'button';
    revertBtn.className = 'button button-small';
    revertBtn.textContent = 'Revert to Original Permalink';
    revertBtn.style.display = 'inline-block';
    revertBtn.title = 'Revert to the original permalink';
    
    // Adaugă butonul și originalPermalinkDisplay la container
    revertContainer.appendChild(originalPermalinkDisplay);
    revertContainer.appendChild(revertBtn);
    
    // Adaugă container după permalinkContainer
    permalinkContainer.parentNode.insertBefore(revertContainer, permalinkContainer.nextSibling);
    
    // Adaugă handler pentru click
    revertBtn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        console.log('Revert button clicked');
        
        // Get the post ID
        const postId = document.querySelector('input[name="post_ID"]')?.value || 
                      document.getElementById('post_ID')?.value ||
                      new URLSearchParams(window.location.search).get('post');
        
        if (!postId) {
            showToast('Could not identify post ID', 'error');
            return;
        }
        
        // Get the original permalink from storage
        const storageKey = `aysa_original_permalink_product_${postId}`;
        const originalPermalink = localStorage.getItem(storageKey);
        
        if (!originalPermalink) {
            showToast('No original permalink found to revert to', 'error');
            return;
        }
        
        // Get current permalink with correct path
        const baseUrl = window.location.origin;
        const currentPermalink = `${baseUrl}/wordpress/product/${slugInput.value}/`;
        
        console.log('Reverting permalink:', {
            currentPermalink,
            originalPermalink,
            postId
        });

        // Extract the original slug from the original permalink
        const originalSlug = extractSlugFromPermalink(originalPermalink);
        if (!originalSlug) {
            showToast('Could not extract original slug from permalink', 'error');
            return;
        }

        // Update the slug field directly
        slugInput.value = originalSlug;
        
        // Dispatch change event to notify WordPress
        slugInput.dispatchEvent(new Event('change', { bubbles: true }));

        // Find the WP "Update" button and click it
        const updateButton = document.querySelector('#publish, input[name="save"]');
        if (updateButton) {
            // Click the update button to save changes
            updateButton.click();
            
            // Show success message
            showToast('Permalink has been reverted to the original value', 'success');
            
            // Remove the revert container since we've reverted
            if (revertContainer.parentNode) {
                revertContainer.parentNode.removeChild(revertContainer);
            }
        } else {
            showToast('Error: Could not find update button', 'error');
        }

        // ✅ DISABLED: Redirect removal is now managed by PHP system
        console.log('✅ Permalink revert - redirect cleanup will be handled by PHP system if needed');
    });
    
    console.log('Added revert button under permalink container');
}

/**
 * Extract slug from permalink URL
 * @param {string} permalink - The permalink URL
 * @returns {string} The extracted slug
 */
function extractSlugFromPermalink(permalink) {
    if (!permalink) return '';
    
    try {
        // Try to parse the URL
        const url = new URL(permalink);
        
        // Get the pathname (e.g., /wordpress/product/my-product/)
        const path = url.pathname;
        
        // Split by slashes and remove empty entries
        const segments = path.split('/').filter(segment => segment !== '');
        
        // The slug is typically the last segment
        if (segments.length > 0) {
            return segments[segments.length - 1];
        }
        
        return '';
    } catch (e) {
        console.error('Error extracting slug from permalink:', e);
        return '';
    }
}

// Apelează funcția după încărcarea paginii
document.addEventListener('DOMContentLoaded', function() {
    if (document.querySelector('input[name="post_ID"]') || 
        document.getElementById('post_ID') || 
        new URLSearchParams(window.location.search).get('post') ||
        window.location.href.includes('post.php') ||
        window.location.href.includes('post-new.php')) {
        
        if (window.AYSA_DEBUG === true) {
            console.log('🔍 [AYSA DEBUG] Post editing page detected, initializing permalink revert functionality');
        }
        
        // Try multiple times to add the revert button, as the permalink container
        // might be added dynamically after some delay in WordPress admin
        
        // First attempt - immediate
        addPermalinkRevertButton();
        
        // Second attempt - after a short delay
        setTimeout(addPermalinkRevertButton, 500);
        
        // Third attempt - after WordPress UI has likely fully loaded
        setTimeout(addPermalinkRevertButton, 1500);
        
        // Final attempt - after all AJAX calls have likely completed
        setTimeout(addPermalinkRevertButton, 3000);
    } else if (window.AYSA_DEBUG === true) {
        console.log('🚫 [AYSA DEBUG] Not a post editing page, skipping permalink revert functionality');
    }
    
    // Also add a mutation observer to detect when the permalink box appears
    const mainContentArea = document.querySelector('#post-body-content') || document.body;
    if (mainContentArea) {
        const observer = new MutationObserver(function(mutations) {
            // Check if the permalink container has been added
            if (document.getElementById('edit-slug-box') && !document.getElementById('aysa-permalink-revert-container')) {
                addPermalinkRevertButton();
            }
        });
        
        // Start observing content changes
        observer.observe(mainContentArea, { 
            childList: true, 
            subtree: true 
        });
        
        // Stop observing after 10 seconds to prevent performance issues
        setTimeout(function() {
            observer.disconnect();
        }, 10000);
    }
}); 

/**
 * ✅ DISABLED: Handle permalink changes and create 301 redirects
 * 
 * Redirect creation is now handled by PHP hooks in class-product-metabox.php
 * This ensures redirects are only created when Update/Publish buttons are pressed,
 * providing more reliable and intelligent redirect management.
 */
function handlePermalinkChange(oldPermalink, newPermalink) {
    if (!oldPermalink || !newPermalink || oldPermalink === newPermalink) {
        return;
    }

    console.log('✅ Permalink change detected (redirect creation disabled):', { oldPermalink, newPermalink });
    console.log('✅ Redirect will be created automatically by PHP hooks when Update/Publish is pressed');
    
    // Note: Redirect creation is now handled by PHP hooks:
    // - handle_category_redirect_if_needed()
    // - handle_product_redirect_if_needed() 
    // - handle_page_redirect_if_needed()
    // in includes/controllers/admin/class-product-metabox.php
}

/**
 * Handle permalink revert and remove 301 redirect
 * @param {string} oldPermalink - The permalink to revert from
 * @param {string} originalPermalink - The original permalink to revert to
 */
function handlePermalinkRevert(oldPermalink, originalPermalink) {
    if (!oldPermalink || !originalPermalink || oldPermalink === originalPermalink) {
        return;
    }

    console.log('Handling permalink revert:', { oldPermalink, originalPermalink });

    // Extract the original slug from the original permalink
    const originalSlug = extractSlugFromPermalink(originalPermalink);
    if (!originalSlug) {
        console.error('Could not extract original slug from permalink:', originalPermalink);
        return;
    }

    // Get the slug input field
    const slugInput = document.getElementById('post_name') || 
                     document.getElementById('slug') || 
                     document.querySelector('input[name="post_name"]');

    if (!slugInput) {
        console.error('Could not find slug input field');
        return;
    }

    // Update the slug field directly
    slugInput.value = originalSlug;
    
    // Dispatch change event to notify WordPress
    slugInput.dispatchEvent(new Event('change', { bubbles: true }));

    // Find the WP "Update" button and click it
    const updateButton = document.querySelector('#publish, input[name="save"]');
    if (updateButton) {
        // Click the update button to save changes
        updateButton.click();
        
        // Show success message
        showToast('Permalink has been reverted to the original value', 'success');
    } else {
        showToast('Error: Could not find update button', 'error');
    }

    // Remove the revert container since we've reverted
    const revertContainer = document.getElementById('aysa-permalink-revert-container');
    if (revertContainer && revertContainer.parentNode) {
        revertContainer.parentNode.removeChild(revertContainer);
    }
}

// ✅ DISABLED: Event listener for permalink changes
// Redirect creation is now handled by PHP hooks on Update/Publish
document.addEventListener('DOMContentLoaded', function() {
    const slugInput = document.getElementById('post_name') || 
                     document.getElementById('slug') || 
                     document.querySelector('input[name="post_name"]');
                     
    if (slugInput) {
        // Store original value when page loads (for tracking purposes)
        if (!slugInput.dataset.originalValue) {
            slugInput.dataset.originalValue = slugInput.value;
        }
        
        // Note: Redirect creation listener disabled
        // Redirects are now handled by PHP hooks in class-product-metabox.php
        console.log('✅ Permalink tracking enabled, but redirect creation moved to PHP hooks');
    }
});

// ... existing code ...

// Add this helper function at the top of the file
function getAjaxUrl() {
    // Try to get from aysa_params first
    if (typeof aysa_params !== 'undefined' && aysa_params.ajax_url) {
        return aysa_params.ajax_url;
    }
    
    // Fallback to WordPress default admin-ajax.php
    return '/wp-admin/admin-ajax.php';
}

/**
 * Update product permalink with the suggestion
 * @param {string} productPermalink - The suggested permalink
 */
function updateProductPermalink(productPermalink) {
    console.log('updateProductPermalink called with:', productPermalink);
    
    if (!productPermalink) {
        console.warn('Empty permalink provided, skipping update');
        return;
    }
    
    // Handle different response formats
    let processedPermalink = '';
    
    if (typeof productPermalink === 'object') {
        // If we receive an object, try to extract the permalink
        if (productPermalink.seoFriendlyUrl) {
            processedPermalink = productPermalink.seoFriendlyUrl;
        } else if (productPermalink.slug) {
            processedPermalink = productPermalink.slug;
        } else {
            console.warn('Received object for permalink but could not extract value:', productPermalink);
            return;
        }
    } else if (typeof productPermalink === 'string') {
        processedPermalink = productPermalink.trim();
    } else {
        console.warn('Unsupported permalink type:', typeof productPermalink);
        return;
    }
    
    if (processedPermalink === '') {
        console.warn('Empty processed permalink, skipping update');
        return;
    }
    
    console.log('Updating product permalink with processed value:', processedPermalink);
    
    // Format the permalink to ensure it's WordPress compatible
    const formattedPermalink = formatPermalink(processedPermalink);
    console.log('Formatted permalink:', formattedPermalink);
    
    // Find all potential permalink input fields
    const permalinkInputs = [
        document.getElementById('post_name'),
        document.getElementById('slug'),
        document.querySelector('input[name="post_name"]'),
        document.querySelector('input[name="slug"]'),
        document.querySelector('.editor-post-slug__input')
    ].filter(el => el); // Filter out null values
    
    console.log('Found permalink inputs:', permalinkInputs.length);
    
    let originalPermalink = '';
    
    // Get the original permalink from the first available input
    if (permalinkInputs.length > 0) {
        const permalinkInput = permalinkInputs[0];
        
        // Check if we already stored the original value in a data attribute
        if (permalinkInput.dataset.originalValue) {
            originalPermalink = permalinkInput.dataset.originalValue;
            console.log('Found original permalink from dataset:', originalPermalink);
        } else {
            // If not stored yet, use the current value and store it
            originalPermalink = permalinkInput.value;
            permalinkInput.dataset.originalValue = originalPermalink;
            console.log('Saving current value as original permalink:', originalPermalink);
        }
    } else {
        console.warn('Could not find any permalink input elements');
    }
    
    // Update the product slug field directly
    updateProductSlug(formattedPermalink);
    
    // Update all slug fields in the WordPress UI
    updateWordPressPermalinkFields(formattedPermalink);
    
    // Show a toast notification
    if (typeof showToast === 'function') {
        showToast('Permalink updated successfully', 'success');
    }
    
    // Add the revert button with a delay to ensure the DOM is updated
    setTimeout(addPermalinkRevertButton, 500);
    
    // ✅ REMOVED: Redirect tracking and creation moved to PHP hooks
    console.log('Permalink change detected:', {
        originalPermalink,
        formattedPermalink,
        changed: originalPermalink && originalPermalink !== formattedPermalink
    });
    
    // Note: Redirect creation is now handled automatically by PHP hooks on Update/Publish
    if (originalPermalink && formattedPermalink && originalPermalink !== formattedPermalink) {
        console.log('✅ Permalink change detected - redirect will be created automatically when Update/Publish is pressed');
    } else {
        console.log('No permalink change detected - no redirect needed');
    }
}

/**
 * Update the product slug field directly
 * @param {string} slug - The formatted slug to set
 */
function updateProductSlug(slug) {
    // Find all possible slug input fields
    const slugFields = [
        document.getElementById('post_name'),
        document.getElementById('slug'),
        document.querySelector('input[name="post_name"]'),
        document.querySelector('input[name="slug"]'),
        document.querySelector('.editor-post-slug__input'),
        document.querySelector('#edittag input[name="slug"]'),
        document.querySelector('#titlediv input[name="post_name"]')
    ].filter(field => field); // Filter out null values
    
    if (slugFields.length === 0) {
        console.warn('Could not find any slug fields to update');
        return;
    }
    
    // Set flag to prevent redirect creation during programmatic updates
    window.aysaProgrammaticUpdate = true;
    
    // Update all found slug fields
    slugFields.forEach(field => {
        // Save original value for potential revert if not already saved
        if (!field.dataset.originalValue) {
            field.dataset.originalValue = field.value;
            console.log('Saved original slug:', field.dataset.originalValue);
        }
        
        // Update the field
        field.value = slug;
        field.dispatchEvent(new Event('change'));
        console.log('Updated slug field:', field);
    });
    
    // Reset flag after a short delay to allow all events to process
    setTimeout(() => {
        window.aysaProgrammaticUpdate = false;
    }, 100);
    
    // If we're in Gutenberg editor, also try to update via the editor API
    if (typeof wp !== 'undefined' && wp.data && wp.data.dispatch && wp.data.select) {
        try {
            const editor = wp.data.dispatch('core/editor');
            if (editor && editor.editPost) {
                editor.editPost({ slug: slug });
                console.log('Updated slug in Gutenberg editor via API');
            }
        } catch (e) {
            console.error('Error updating slug via Gutenberg API:', e);
        }
    }
}

/**
 * Update WordPress permalink UI elements
 * @param {string} slug - The formatted slug to set
 */
function updateWordPressPermalinkFields(slug) {
    // Find the permalink container
    const permalinkContainer = document.getElementById('edit-slug-box');
    
    if (!permalinkContainer) {
        console.log('No permalink container found to update UI');
        return;
    }
    
    // Check if Edit button exists
    const editBtn = permalinkContainer.querySelector('.edit-slug') || 
                   permalinkContainer.querySelector('button:not(.save):not(.cancel)');
                   
    // Check if Save button exists
    const saveBtn = permalinkContainer.querySelector('.save');
    
    // Simulate click on Edit if it exists and Save doesn't (meaning we're not already in edit mode)
    if (editBtn && !saveBtn) {
        console.log('Simulating click on edit button');
        editBtn.click();
        
        // Wait a bit for editing to open
        setTimeout(() => {
            // Now there should be an input field and a save button
            const permalinkField = permalinkContainer.querySelector('input[type="text"]');
            if (permalinkField) {
                permalinkField.value = slug;
                permalinkField.dispatchEvent(new Event('change'));
                console.log('Updated permalink field in edit mode:', slug);
                
                // Find and simulate click on Save
                const saveBtn = permalinkContainer.querySelector('.save');
                if (saveBtn) {
                    console.log('Simulating click on save button');
                    saveBtn.click();
                }
            }
        }, 200);
    } else if (saveBtn) {
        // We're already in edit mode
        const permalinkField = permalinkContainer.querySelector('input[type="text"]');
        if (permalinkField) {
            permalinkField.value = slug;
            permalinkField.dispatchEvent(new Event('change'));
            console.log('Updated permalink field already in edit mode:', slug);
            
            // Click save button
            saveBtn.click();
        }
    }
}

/**
 * Sanitize HTML/markup content
 * @param {string} content - The content to sanitize
 * @param {boolean} preserveAllHtml - Whether to preserve all HTML tags (default: true)
 * @returns {string} Sanitized content
 */
function sanitizeContent(content, preserveAllHtml = true) {
    if (!content || typeof content !== 'string') {
        return content;
    }

    const normalizeAysaEscapedContent = function(raw) {
        let text = String(raw || '').trim();
        if (!text) return '';

        // Decode JSON-string encoded payloads.
        if ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'"))) {
            try {
                const decoded = JSON.parse(text);
                if (typeof decoded === 'string') {
                    text = decoded;
                } else {
                    text = text.slice(1, -1);
                }
            } catch (e) {
                text = text.slice(1, -1);
            }
        }

        text = text
            .replace(/\\r\\n/g, '\n')
            .replace(/\\n\\r/g, '\n')
            .replace(/\\n/g, '\n')
            .replace(/\\r/g, '\n')
            .replace(/\\t/g, ' ')
            .replace(/\{\{\s*attributes\s*\}\}/gi, '');

        // Remove orphan lines that are only "n"/"nn" etc.
        text = text.replace(/(^|\n)\s*n+\s*(?=\n|$)/gim, '$1');

        // Keep paragraph spacing readable.
        text = text.replace(/\n{3,}/g, '\n\n');
        return text.trim();
    };

    let sanitized = normalizeAysaEscapedContent(content);

    // Remove ```html at the beginning of the content
    sanitized = sanitized.replace(/^```html\s*/i, '');
    
    // Remove ``` at the end of the content
    sanitized = sanitized.replace(/```\s*$/i, '');
    
    // Remove any other markdown code block markers
    sanitized = sanitized.replace(/^```[a-z]*\s*/img, '');

    // Ensure FAQ section is emitted with schema.org microdata if model returned plain FAQ HTML.
    sanitized = ensureFaqSchemaMicrodata(sanitized);

    // Persist JSON-LD scripts into a hidden input so they can be restored server-side on save
    // even if the visual editor strips <script type="application/ld+json"> blocks.
    try {
        const jsonLdScripts = extractJsonLdScriptsFromHtml(sanitized);
        if (jsonLdScripts.length) {
            persistPendingJsonLdScriptsForSave(jsonLdScripts);
        }
    } catch (e) {
        console.warn('AYSA: Failed to persist JSON-LD scripts for save', e);
    }
    
    console.log('Sanitized content, removed markdown markers');
    
    // Create a temporary div element to properly handle HTML content
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = sanitized;
    
    // WordPress might be filtering HTML tags, so we add attribute to preserve them
    if (preserveAllHtml) {
        // Find all elements and add data-mce-style to ensure styles persist in TinyMCE
        const allElements = tempDiv.querySelectorAll('*');
        allElements.forEach(el => {
            if (el.style && el.style.cssText) {
                el.setAttribute('data-mce-style', el.style.cssText);
            }
        });
        sanitized = tempDiv.innerHTML;
    }
    
    return sanitized;
}

function extractJsonLdScriptsFromHtml(html) {
    if (!html || typeof html !== 'string') {
        return [];
    }
    const matches = html.match(/<script[^>]*type=["']application\/ld\+json["'][^>]*>[\s\S]*?<\/script>/gi);
    if (!Array.isArray(matches) || !matches.length) {
        return [];
    }
    const unique = new Set();
    matches.forEach((item) => {
        const normalized = String(item || '').trim();
        if (normalized) {
            unique.add(normalized);
        }
    });
    return Array.from(unique);
}

function persistPendingJsonLdScriptsForSave(scripts) {
    const list = Array.isArray(scripts) ? scripts.filter(Boolean) : [];
    if (!list.length) {
        return;
    }

    const form = document.getElementById('post') || document.querySelector('form#post');
    if (!form) {
        return;
    }

    let hidden = form.querySelector('input[name="aysa_jsonld_scripts"]');
    if (!hidden) {
        hidden = document.createElement('input');
        hidden.type = 'hidden';
        hidden.name = 'aysa_jsonld_scripts';
        hidden.id = 'aysa_jsonld_scripts';
        form.appendChild(hidden);
    }

    let existing = [];
    try {
        existing = hidden.value ? JSON.parse(hidden.value) : [];
    } catch (e) {
        existing = [];
    }

    const combined = new Set();
    (Array.isArray(existing) ? existing : []).forEach((s) => {
        const v = String(s || '').trim();
        if (v) combined.add(v);
    });
    list.forEach((s) => {
        const v = String(s || '').trim();
        if (v) combined.add(v);
    });

    hidden.value = JSON.stringify(Array.from(combined));
}

/**
 * Convert plain FAQ section (H2/H3/P) into FAQPage microdata when missing.
 * Keeps original content unchanged when no FAQ section is detected.
 *
 * @param {string} html
 * @returns {string}
 */
function ensureFaqSchemaMicrodata(html) {
    if (!html || typeof html !== 'string') {
        return html;
    }

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

    const container = document.createElement('div');
    container.innerHTML = html;

    const faqHeading = Array.from(container.querySelectorAll('h2, h3')).find((el) => {
        const text = (el.textContent || '').toLowerCase();
        return text.includes('întrebări frecvente') || text.includes('intrebari frecvente') || text.includes('faq');
    });

    if (!faqHeading) {
        return html;
    }

    const entries = [];
    let cursor = faqHeading.nextElementSibling;
    let faqEndNode = null;

    while (cursor) {
        const tag = (cursor.tagName || '').toUpperCase();
        if (tag === 'H2') {
            faqEndNode = cursor;
            break;
        }

        if (tag === 'H3' || tag === 'H4') {
            const rawQuestion = (cursor.textContent || '').trim();
            const question = rawQuestion.replace(/^\d+[\).\s-]*/, '').trim();
            let answer = '';
            let probe = cursor.nextElementSibling;
            while (probe) {
                const probeTag = (probe.tagName || '').toUpperCase();
                if (probeTag === 'H2' || probeTag === 'H3' || probeTag === 'H4') {
                    break;
                }
                const t = (probe.textContent || '').trim();
                if (t) {
                    answer = t;
                    break;
                }
                probe = probe.nextElementSibling;
            }
            if (question && answer) {
                entries.push({ question, answer });
            }
        }

        cursor = cursor.nextElementSibling;
    }

    if (!entries.length) {
        return html;
    }

    const faqSection = document.createElement('section');
    faqSection.className = 'aysa-faq';
    faqSection.setAttribute('itemscope', '');
    faqSection.setAttribute('itemtype', 'https://schema.org/FAQPage');

    const h2 = document.createElement('h2');
    h2.textContent = 'Întrebări frecvente';
    faqSection.appendChild(h2);

    entries.slice(0, 8).forEach((entry) => {
        const qWrap = document.createElement('div');
        qWrap.setAttribute('itemscope', '');
        qWrap.setAttribute('itemprop', 'mainEntity');
        qWrap.setAttribute('itemtype', 'https://schema.org/Question');

        const q = document.createElement('h3');
        q.setAttribute('itemprop', 'name');
        q.textContent = entry.question;

        const aWrap = document.createElement('div');
        aWrap.setAttribute('itemscope', '');
        aWrap.setAttribute('itemprop', 'acceptedAnswer');
        aWrap.setAttribute('itemtype', 'https://schema.org/Answer');

        const p = document.createElement('p');
        p.setAttribute('itemprop', 'text');
        p.textContent = entry.answer;

        aWrap.appendChild(p);
        qWrap.appendChild(q);
        qWrap.appendChild(aWrap);
        faqSection.appendChild(qWrap);
    });

    // Remove old FAQ block nodes (from FAQ heading until next H2/end).
    let removeNode = faqHeading;
    while (removeNode && removeNode !== faqEndNode) {
        const next = removeNode.nextElementSibling;
        removeNode.remove();
        removeNode = next;
    }

    if (faqEndNode) {
        faqEndNode.parentNode.insertBefore(faqSection, faqEndNode);
    } else {
        container.appendChild(faqSection);
    }

    return container.innerHTML;
}

/**
 * Update category permalink with the suggestion
 * @param {string} categoryPermalink - The suggested permalink
 */
function updateCategoryPermalink(categoryPermalink) {
    console.log('updateCategoryPermalink called with:', categoryPermalink);
    
    if (!categoryPermalink) {
        console.warn('Empty category permalink provided, skipping update');
        return;
    }
    
    // Handle different response formats
    let processedPermalink = '';
    
    if (typeof categoryPermalink === 'object') {
        // If we receive an object, try to extract the permalink
        if (categoryPermalink.seoFriendlyUrl) {
            processedPermalink = categoryPermalink.seoFriendlyUrl;
        } else if (categoryPermalink.slug) {
            processedPermalink = categoryPermalink.slug;
        } else {
            console.warn('Received object for category permalink but could not extract value:', categoryPermalink);
            return;
        }
    } else if (typeof categoryPermalink === 'string') {
        processedPermalink = categoryPermalink.trim();
    } else {
        console.warn('Unsupported category permalink type:', typeof categoryPermalink);
        return;
    }
    
    if (processedPermalink === '') {
        console.warn('Empty processed category permalink, skipping update');
        return;
    }
    
    console.log('Updating category permalink with processed value:', processedPermalink);
    
    // Format the permalink to ensure it's WordPress compatible
    const formattedPermalink = formatPermalink(processedPermalink);
    console.log('Formatted category permalink:', formattedPermalink);
    
    // For categories, WordPress uses a different UI and field structure
    // Find the slug field - it might be different in category edit screen
    const slugInput = document.getElementById('tag-slug') || 
                     document.getElementById('slug') || 
                     document.querySelector('input[name="slug"]');
    
    // Get the original permalink for redirect creation
    let originalPermalink = '';
    if (slugInput && slugInput.dataset.originalValue) {
        originalPermalink = slugInput.dataset.originalValue;
    } else if (slugInput) {
        originalPermalink = slugInput.value;
    }
    
    // Update the slug field if found
    if (slugInput) {
        slugInput.value = formattedPermalink;
        // Trigger change event for any listeners
        slugInput.dispatchEvent(new Event('change'));
        
        // Store the original value for possible revert
        if (!slugInput.dataset.originalValue) {
            slugInput.dataset.originalValue = originalPermalink;
        }
        
        console.log('Updated category slug field with value:', formattedPermalink);
        
        // Show a toast notification
        if (typeof showToast === 'function') {
            showToast('Category permalink updated successfully', 'success');
        }
        
        // Add the revert button with a delay to ensure the DOM is updated
        setTimeout(addPermalinkRevertButton, 500);
        
        // Create a redirect if the permalink changed
        if (originalPermalink && originalPermalink !== formattedPermalink) {
            console.log('Redirect creation disabled - now handled by WordPress PHP hooks on Update/Publish');
            // ✅ DISABLED: Redirect creation is now handled by PHP hooks in class-product-metabox.php
            // createRedirect(originalPermalink, formattedPermalink);
        }
    } else {
        console.warn('Could not find slug input field for category');
    }
}

/** 
 * ✅ REMOVED: createRedirect function
 * 
 * Redirect functionality has been moved to PHP hooks in class-product-metabox.php
 * Redirects are now intelligently created only when Update/Publish buttons are pressed,
 * and only when permalinks actually change. This prevents duplicate API calls and
 * provides more reliable redirect management.
 * 
 * See: handle_category_redirect_if_needed(), handle_product_redirect_if_needed(), 
 * handle_page_redirect_if_needed() in includes/controllers/admin/class-product-metabox.php
 */

/**
 * Function to get Project ID from multiple sources with robust fallback mechanisms
 * @returns {number} Project ID
 */
function getProjectId() {
    // First try to get from aysaParams (passed from PHP)
    if (typeof aysaParams !== 'undefined' && aysaParams.project_id && aysaParams.project_id > 0) {
        console.log('Project ID from aysaParams:', aysaParams.project_id);
        return aysaParams.project_id;
    }
    
    // Fallback to localStorage
    const storedProjectId = localStorage.getItem('aysa_project_id');
    if (storedProjectId && storedProjectId > 0) {
        console.log('Project ID from localStorage:', storedProjectId);
        return parseInt(storedProjectId);
    }
    
    // If neither available, resolve through local WP broker endpoint (tracked server-side)
    const domain = window.location.hostname;
    let apiProjectId = null;
    
    // Synchronous AJAX call to ensure projectId is available before proceeding
    if (typeof jQuery !== 'undefined') {
        const ajaxUrl = (typeof aysaParams !== 'undefined' && aysaParams.ajax_url) 
            ? aysaParams.ajax_url 
            : (typeof ajaxurl !== 'undefined' ? ajaxurl : '');
        const nonce = (typeof aysaParams !== 'undefined' && aysaParams.nonce)
            ? aysaParams.nonce
            : (document.querySelector('input[name="aysa_metabox_nonce"]') ? document.querySelector('input[name="aysa_metabox_nonce"]').value : '');

        jQuery.ajax({
            url: ajaxUrl,
            type: 'POST',
            dataType: 'json',
            async: false,
            data: {
                action: 'aysa_get_project_by_domain_broker',
                nonce: nonce,
                domain: domain
            },
            success: function(response) {
                if (response && response.success && response.data && response.data.project_id) {
                    apiProjectId = parseInt(response.data.project_id, 10);
                    // Store in localStorage for future use
                    localStorage.setItem('aysa_project_id', apiProjectId);
                    console.log('Project ID resolved via broker:', apiProjectId, 'source:', response.data.source || 'unknown');
                }
            },
            error: function(xhr, status, error) {
                console.error('Failed to resolve project by domain via broker:', error);
            }
        });
    }
    
    // Fallback to default project ID if available in aysaParams
    const fallbackProjectId = (typeof aysaParams !== 'undefined' && aysaParams.default_project_id) ? 
                             aysaParams.default_project_id : 1;
    
    if (apiProjectId && apiProjectId > 0) {
        console.log('Using Project ID from API by domain:', apiProjectId);
        return apiProjectId;
    } else {
        console.log('Using fallback Project ID:', fallbackProjectId);
        return fallbackProjectId;
    }
}

/**
 * Get the language optimize value from metabox or global WordPress settings
 * @returns {string} The language code (e.g., 'en', 'ro') or default 'en'
 */
function getLanguageOptimizeValue() {
    // ✅ Get value from metabox Language Optimize field
    const languageOptimizeField = document.getElementById('language_optimize');
    if (languageOptimizeField && languageOptimizeField.value.trim()) {
        return languageOptimizeField.value.trim();
    }
    return '';
}

/**
 * Get product attributes from WooCommerce product edit page
 * Returns array of strings in format "attribute: value"
 */
function getProductAttributes() {
    const attributes = [];
    
    try {
        // Check for WooCommerce product attributes section
        const attributesContainer = document.querySelector('#product_attributes, .woocommerce_product_attributes');
        
        if (attributesContainer) {
            // Look for attribute rows - more specific selectors
            const attributeRows = attributesContainer.querySelectorAll('.woocommerce_attribute');
            
            attributeRows.forEach(row => {
                try {
                    // Get attribute name from the specific input field
                    let attributeName = '';
                    
                    // Try different selectors for attribute name
                    const nameInput = row.querySelector('input[name*="attribute_names"]');
                    const nameSelect = row.querySelector('select[name*="attribute_names"]');
                    const nameElement = row.querySelector('.attribute_name h3, .attribute_name strong');
                    
                    if (nameInput && nameInput.value) {
                        attributeName = nameInput.value.trim();
                    } else if (nameSelect && nameSelect.value) {
                        // Get the selected option text, not value
                        const selectedOption = nameSelect.options[nameSelect.selectedIndex];
                        attributeName = selectedOption ? selectedOption.textContent.trim() : nameSelect.value;
                    } else if (nameElement) {
                        attributeName = nameElement.textContent.trim();
                        // Clean up attribute name (remove unwanted text like "Remove", newlines, tabs)
                        attributeName = attributeName.replace(/Remove|^\s*[\r\n\t]+/g, '').trim();
                        // Remove "Product " prefix if present
                        attributeName = attributeName.replace(/^Product\s+/i, '');
                    }
                    
                    // Clean attribute name from any remaining unwanted characters
                    attributeName = attributeName.replace(/[\r\n\t]+/g, ' ').trim();
                    
                    // Get attribute values
                    let attributeValue = '';
                    const valueElement = row.querySelector('textarea[name*="attribute_values"]');
                    
                    if (valueElement && valueElement.value) {
                        // Values might be pipe-separated, clean and join them
                        const values = valueElement.value.split('|')
                            .map(v => v.trim())
                            .filter(v => v && v !== 'Remove'); // Filter out empty values and "Remove" text
                        attributeValue = values.length > 0 ? values.join(', ') : '';
                    } else {
                        // Try to get from select options if it's a dropdown attribute
                        const selectElement = row.querySelector('select[name*="attribute_values"]');
                        if (selectElement) {
                            const selectedOptions = Array.from(selectElement.selectedOptions);
                            attributeValue = selectedOptions
                                .map(option => option.textContent.trim())
                                .filter(text => text && text !== 'Remove')
                                .join(', ');
                        }
                    }
                    
                    // Final cleanup for attribute value
                    attributeValue = attributeValue.replace(/[\r\n\t]+/g, ' ').trim();
                    
                    // Add to attributes array if both name and value exist and are not empty
                    if (attributeName && attributeValue && attributeName !== 'Remove') {
                        attributes.push(`${attributeName}: ${attributeValue}`);
                    }
                } catch (error) {
                    console.warn('Error processing attribute row:', error);
                }
            });
        }
        
        // Alternative: Try to get from product variation attributes if no global attributes found
        if (attributes.length === 0) {
            const variationAttributes = document.querySelectorAll('.woocommerce_variation_attributes select');
            variationAttributes.forEach(select => {
                try {
                    const attributeName = select.getAttribute('name');
                    const selectedValue = select.value;
                    
                    if (attributeName && selectedValue) {
                        // Clean up attribute name (remove "attribute_" prefix)
                        const cleanName = attributeName.replace(/^attribute_/, '').replace(/_/g, ' ');
                        attributes.push(`${cleanName}: ${selectedValue}`);
                    }
                } catch (error) {
                    console.warn('Error processing variation attribute:', error);
                }
            });
        }
        
        console.log('🔍 [DEBUG] Extracted product attributes:', attributes);
        console.log('🔍 [DEBUG] Attributes array length:', attributes.length);
        if (attributes.length === 0) {
            console.log('⚠️ No product attributes found on this page');
        }
        
    } catch (error) {
        console.error('Error extracting product attributes:', error);
    }
    
    return attributes;
}

/**
 * Manually render secondary keyword tags when the main render function is not available
 * @param {string} keywordsStr - Comma-separated string of keywords
 */
function renderSecondaryKeywordTagsManually(keywordsStr) {
    console.log('🔥 renderSecondaryKeywordTagsManually called with:', keywordsStr);
    
    // Ensure CSS styles are loaded for tags
    if (!document.getElementById('aysa-keyword-tags-style')) {
        const style = document.createElement('style');
        style.id = 'aysa-keyword-tags-style';
        style.textContent = `
            .keyword-tag {
                display: inline-flex;
                align-items: center;
                background: #f0f0f1;
                border: 1px solid #c3c4c7;
                border-radius: 3px;
                padding: 4px 8px;
                margin: 2px;
                font-size: 12px;
                line-height: 1.4;
                color: #50575e;
            }
            .keyword-tag .tag-text {
                margin-right: 4px;
            }
            .keyword-tag .tag-remove {
                color: #787c82;
                cursor: pointer;
                font-weight: bold;
                padding: 0 2px;
            }
            .keyword-tag .tag-remove:hover {
                color: #d63638;
            }
            #secondary-keywords-container {
                display: flex;
                flex-wrap: wrap;
                gap: 2px;
                padding: 4px;
                min-height: 30px;
                background: #fff;
                border: 1px solid #c3c4c7;
                border-radius: 3px;
                margin-top: 4px;
            }
        `;
        document.head.appendChild(style);
    }
    
    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()) {
            const tag = document.createElement('div');
            tag.className = 'keyword-tag';
            tag.innerHTML = `
                <span class="tag-text">${keyword.trim()}</span>
                <span class="tag-remove">×</span>
            `;
            
            // Add remove functionality using the proper removeKeywordTag function if available
            tag.querySelector('.tag-remove').addEventListener('click', function(e) {
                e.stopPropagation();
                
                // Try to use the proper removeKeywordTag function from aysa-keywords.js if available
                if (typeof window.removeKeywordTag === 'function') {
                    console.log('🔥 renderSecondaryKeywordTagsManually: Using proper removeKeywordTag function with modal');
                    window.removeKeywordTag(tag, keyword.trim());
                } else if (typeof removeKeywordTag === 'function') {
                    console.log('🔥 renderSecondaryKeywordTagsManually: Using global removeKeywordTag function with modal');
                    removeKeywordTag(tag, keyword.trim());
                } else {
                    console.log('🔥 renderSecondaryKeywordTagsManually: Fallback - Using simple remove without modal');
                    // Fallback: Remove this keyword from the input and re-render
                    const currentKeywords = mainInput.value.split(',').map(k => k.trim()).filter(k => k !== keyword.trim());
                    mainInput.value = currentKeywords.join(', ');
                    tag.remove();
                    
                    // Trigger input event to update other listeners
                    mainInput.dispatchEvent(new Event('input', { bubbles: true }));
                }
            });
            
            secondaryKeywordsContainer.appendChild(tag);
        }
    });
    
    console.log('🔥 renderSecondaryKeywordTagsManually: Created', keywords.length, 'keyword tags');
}

/**
 * ✅ NEW: Clear existing secondary keywords from API and frontend
 */
async function clearExistingSecondaryKeywords(entityId, entityType) {
    console.log('🧹 CLEARING SECONDARY KEYWORDS for:', { entityId, entityType });
    
    // Skip for new entities (ID = 0)
    if (entityId === 0) {
        console.log('🧹 SKIPPING API DELETE - New entity (ID = 0)');
        // Still clear frontend
        clearSecondaryKeywordsFromFrontend();
        return;
    }
    
    try {
        // Get project ID
        const projectId = getProjectId();
        if (!projectId) {
            console.warn('🧹 No project ID found, skipping API delete');
            clearSecondaryKeywordsFromFrontend();
            return;
        }
        
        console.log('🧹 MAKING SERVER-SIDE DELETE CALL...', { entityId, entityType, projectId });
        const ajaxUrl = (typeof aysaParams !== 'undefined' && aysaParams.ajax_url)
            ? aysaParams.ajax_url
            : (typeof ajaxurl !== 'undefined' ? ajaxurl : '');
        const nonce = (typeof aysaParams !== 'undefined' && aysaParams.nonce)
            ? aysaParams.nonce
            : (document.querySelector('input[name="aysa_metabox_nonce"]') ? document.querySelector('input[name="aysa_metabox_nonce"]').value : '');
        const response = await window.jQuery.ajax({
            url: ajaxUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_delete_entity_associations',
                nonce: nonce,
                entity_id: entityId,
                entity_type: entityType,
                project_id: projectId
            }
        });

        if (response && response.success) {
            console.log('✅ SECONDARY KEYWORDS DELETED FROM API');
            showToast('Existing secondary keywords cleared', 'info');
        } else {
            console.warn('⚠️ API DELETE failed:', response && response.data ? response.data : 'unknown_error');
            showToast('Could not clear existing keywords from API', 'warning');
        }
        
    } catch (error) {
        console.error('❌ ERROR CLEARING SECONDARY KEYWORDS:', error);
        showToast('Error clearing existing keywords: ' + error.message, 'warning');
    }
    
    // Always clear frontend regardless of API success/failure
    clearSecondaryKeywordsFromFrontend();
}

/**
 * ✅ NEW: Clear secondary keywords from frontend
 */
function clearSecondaryKeywordsFromFrontend() {
    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 tagsContainer = document.querySelector('.aysa-secondary-keywords-tags');
    if (tagsContainer) {
        tagsContainer.innerHTML = '';
        console.log('🧹 Cleared secondary keyword tags');
    }
    
    // Clear secondary keywords container
    const secondaryContainer = document.getElementById('secondary-keywords-container');
    if (secondaryContainer) {
        secondaryContainer.innerHTML = '';
        console.log('🧹 Cleared secondary keywords container');
    }
    
    // Clear any other secondary keyword displays
    const otherContainers = document.querySelectorAll('[class*="secondary-keyword"], [class*="second-keyword"]');
    otherContainers.forEach(container => {
        if (container.tagName === 'INPUT' || container.tagName === 'TEXTAREA') {
            container.value = '';
        } else {
            container.innerHTML = '';
        }
    });
    
    console.log('✅ FRONTEND SECONDARY KEYWORDS CLEARED');
}

// Initialize event listeners when the DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    if (window.AYSA_DEBUG === true) {
        console.log('🚀 DEBUG: DOM Content Loaded in aysa-actions.js - initializing event listeners');
    }
    bindEventListeners();
});

/**
 * Debug function to check if Elementor handler is loaded and test integration
 */
function checkElementorIntegration() {
    console.log('🔍 AYSA Elementor Integration Status:', {
        handlerLoaded: typeof window.aysaElementorHandler !== 'undefined',
        elementorFunction: typeof window.updateElementorContent !== 'undefined',
        elementorAjax: typeof aysaElementorAjax !== 'undefined',
        updateWooCommerceDescription: typeof window.updateWooCommerceDescription !== 'undefined',
        updateWooCommerceShortDescription: typeof window.updateWooCommerceShortDescription !== 'undefined',
        timestamp: new Date().toISOString()
    });
    
    if (typeof window.aysaElementorHandler !== 'undefined') {
        console.log('✅ Elementor Handler Details:', {
            isActive: window.aysaElementorHandler.isElementorActive,
            currentPostId: window.aysaElementorHandler.getCurrentPostId()
        });
        
        // Run integration test
        try {
            const testResults = window.aysaElementorHandler.testIntegration();
            console.log('🧪 Integration test completed:', testResults);
        } catch (error) {
            console.error('❌ Integration test failed:', error);
        }
    } else {
        if (window.AYSA_DEBUG === true) {
            console.warn('⚠️ AYSA Elementor Handler not loaded');
        }
    }
    
    return {
        handlerLoaded: typeof window.aysaElementorHandler !== 'undefined',
        elementorActive: window.aysaElementorHandler?.isElementorActive || false,
        functionsAvailable: {
            updateWooCommerceDescription: typeof window.updateWooCommerceDescription !== 'undefined',
            updateWooCommerceShortDescription: typeof window.updateWooCommerceShortDescription !== 'undefined',
            updateElementorContent: typeof window.updateElementorContent !== 'undefined'
        }
    };
}

/**
 * Test function to verify Elementor content updates work
 */
function testElementorContentUpdate(testContent = 'Test content from AYSA') {
    console.log('🧪 Testing Elementor content update...');
    
    if (typeof window.aysaElementorHandler === 'undefined') {
        console.error('❌ Elementor handler not available');
        return false;
    }
    
    if (!window.aysaElementorHandler.isElementorActive) {
        console.warn('⚠️ Elementor not active on this page');
        return false;
    }
    
    try {
        // Test description update
        if (typeof window.updateWooCommerceDescription === 'function') {
            console.log('🚀 Testing description update...');
            window.updateWooCommerceDescription(testContent + ' - Description Test');
        }
        
        // Test short description update
        if (typeof window.updateWooCommerceShortDescription === 'function') {
            console.log('🚀 Testing short description update...');
            window.updateWooCommerceShortDescription(testContent + ' - Short Description Test');
        }
        
        console.log('✅ Test completed - check console for detailed results');
        return true;
        
    } catch (error) {
        console.error('❌ Test failed:', error);
        return false;
    }
}

// Make test function available globally
window.testElementorContentUpdate = testElementorContentUpdate;

// Only auto-probe Elementor integration in debug mode to avoid noisy logs on non-Elementor pages.
if (window.AYSA_DEBUG === true) {
    console.log('AYSA Actions loaded, checking for Elementor integration...');
    setTimeout(checkElementorIntegration, 1000);
}

/**
 * Handle keyword conflict detection and upsert with user confirmation
 * @param {string} apiUrl - The API URL for upsert
 * @param {object} associationData - The association data to send
 * @returns {Promise} - Promise that resolves to the API response
 */
async function handleKeywordConflictAndUpsert(apiUrl, associationData) {
    console.log('🔍 Checking for keyword conflicts before upsert:', associationData);
    
    try {
        // First attempt - try upsert without ForceOverride
        let response = await fetch(apiUrl, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            body: JSON.stringify(associationData),
            mode: 'cors'
        });
        
        // If successful, return the response
        if (response.ok) {
            console.log('✅ Association upsert successful - no conflicts detected');
            return response;
        }
        
        // If it's a conflict error (400 Bad Request), handle it
        if (response.status === 400) {
            const errorData = await response.json();
            
            // Check if this is a keyword conflict error
            if (errorData.Message && errorData.Message.includes('already associated with other entities') && errorData.ConflictingEntities) {
                console.log('⚠️ Keyword conflict detected:', errorData);
                
                // Show confirmation dialog with conflict details
                const conflictEntities = errorData.ConflictingEntities.join('\n• ');
                const confirmMessage = `⚠️ KEYWORD CONFLICT DETECTED\n\nThe keyword "${associationData.Keyword}" is already associated with:\n\n• ${conflictEntities}\n\n${errorData.Suggestion}\n\nDo you want to move this keyword to the current entity?\n\n⚠️ This will remove the keyword from the conflicting entities.`;
                
                const userConfirmed = confirm(confirmMessage);
                
                if (userConfirmed) {
                    console.log('✅ User confirmed keyword override, retrying with ForceOverride=true');
                    
                    // Retry with ForceOverride flag
                    associationData.ForceOverride = true;
                    
                    const retryResponse = await fetch(apiUrl, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json',
                            'Origin': window.location.origin
                        },
                        body: JSON.stringify(associationData),
                        mode: 'cors'
                    });
                    
                    if (retryResponse.ok) {
                        console.log('✅ Keyword conflict resolved - association updated successfully');
                        // Show success notification
                        if (typeof showNotification === 'function') {
                            showNotification(`Keyword "${associationData.Keyword}" moved successfully! Conflicts resolved.`, 'success');
                        }
                        return retryResponse;
                    } else {
                        const retryError = await retryResponse.json();
                        throw new Error(`Failed to resolve conflict: ${retryError.Message || retryResponse.statusText}`);
                    }
                } else {
                    console.log('❌ User cancelled keyword override');
                    // Show cancellation notification
                    if (typeof showNotification === 'function') {
                        showNotification(`Association cancelled. Keyword "${associationData.Keyword}" remains with existing entities.`, 'info');
                    }
                    throw new Error('User cancelled keyword association due to conflicts');
                }
            }
        }
        
        // If it's not a conflict error, throw the original error
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.Message || `API response status: ${response.status}`);
        
    } catch (error) {
        console.error('❌ Error in handleKeywordConflictAndUpsert:', error);
        throw error;
    }
}

/**
 * 🔒 DISABLE ALL RELEVANT BUTTONS during SEO generation
 */
function disableAllRelevantButtons() {
    console.log('🔒 DISABLING all relevant buttons during SEO generation...');
    
    // Store original button states for restoration
    window.aysaOriginalButtonStates = window.aysaOriginalButtonStates || {};
    
    // WordPress core buttons
    const wpButtons = [
        '#publish',           // Publish button
        '#save-post',         // Save Draft button  
        '#post-preview',      // Preview button
        '.editor-post-publish-button', // Gutenberg publish
        '.editor-post-save-draft',     // Gutenberg save draft
        '.editor-post-preview',        // Gutenberg preview
        '.page-title-action', // Add New buttons
        '#submit',            // General submit buttons
        '.button-primary',    // Primary action buttons
        '.button-secondary'   // Secondary action buttons
    ];
    
    // WooCommerce specific buttons
    const wooButtons = [
        '#woocommerce-product-data .button',
        '.wc-metabox-content .button',
        '.woocommerce_variation .button'
    ];
    
    // Category/Taxonomy buttons
    const taxonomyButtons = [
        '#submit',
        '.form-table .button',
        '#addtag .button'
    ];
    
    // AYSA specific buttons (but not the current one being clicked)
    const aysaButtons = [
        '.aysa-sidebar-generate-btn:not(:disabled)',
        '.aysa-sidebar-seo-button:not(:disabled)',
        '#aysa-floating-seo-button:not(:disabled)'
    ];
    
    // Combine all selectors
    const allSelectors = [...wpButtons, ...wooButtons, ...taxonomyButtons, ...aysaButtons];
    
    let disabledCount = 0;
    
    allSelectors.forEach(selector => {
        const buttons = document.querySelectorAll(selector);
        buttons.forEach(button => {
            if (!button.disabled) {
                // Store original state
                const buttonId = button.id || `btn_${Math.random().toString(36).substr(2, 9)}`;
                window.aysaOriginalButtonStates[buttonId] = {
                    element: button,
                    disabled: button.disabled,
                    innerHTML: button.innerHTML,
                    className: button.className
                };
                
                // Disable button and add visual indicator
                button.disabled = true;
                button.style.opacity = '0.6';
                button.style.cursor = 'not-allowed';
                button.title = 'Disabled during SEO generation - please wait...';
                
                disabledCount++;
            }
        });
    });
    
    console.log(`🔒 DISABLED ${disabledCount} buttons during SEO generation`);
    
    // Also disable form submissions
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', preventFormSubmission, true);
    });
}

/**
 * 🔓 RE-ENABLE ALL RELEVANT BUTTONS after SEO generation
 */
function enableAllRelevantButtons() {
    console.log('🔓 RE-ENABLING all relevant buttons after SEO generation...');
    
    if (!window.aysaOriginalButtonStates) {
        console.warn('🔓 No stored button states found - skipping restoration');
        return;
    }
    
    let enabledCount = 0;
    
    // Restore all buttons to their original state
    Object.keys(window.aysaOriginalButtonStates).forEach(buttonId => {
        const buttonState = window.aysaOriginalButtonStates[buttonId];
        const button = buttonState.element;
        
        if (button && document.contains(button)) {
            // Restore original state
            button.disabled = buttonState.disabled;
            button.style.opacity = '';
            button.style.cursor = '';
            button.title = '';
            
            enabledCount++;
        }
    });
    
    console.log(`🔓 RE-ENABLED ${enabledCount} buttons after SEO generation`);
    
    // Clear stored states
    window.aysaOriginalButtonStates = {};
    
    // Re-enable form submissions
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.removeEventListener('submit', preventFormSubmission, true);
    });
}

/**
 * Prevent form submission during SEO generation
 */
function preventFormSubmission(e) {
    if (window.aysaOriginalButtonStates && Object.keys(window.aysaOriginalButtonStates).length > 0) {
        e.preventDefault();
        e.stopPropagation();
        
        if (typeof showToast === 'function') {
            showToast('Please wait for SEO generation to complete before saving changes.', 'warning');
        } else {
            alert('Please wait for SEO generation to complete before saving changes.');
        }
        
        return false;
    }
}

// ✅ CRITICAL: Expose functions to window for cross-script access
window.handleGenerateSuggestions = handleGenerateSuggestions;
window.handleKeywordConflictAndUpsert = handleKeywordConflictAndUpsert;
window.disableAllRelevantButtons = disableAllRelevantButtons;
window.enableAllRelevantButtons = enableAllRelevantButtons;

console.log('✅ AYSA Actions: Exposed functions to window object');
console.log('✅ window.handleGenerateSuggestions available:', typeof window.handleGenerateSuggestions);
console.log('✅ window.disableAllRelevantButtons available:', typeof window.disableAllRelevantButtons);
console.log('✅ window.enableAllRelevantButtons available:', typeof window.enableAllRelevantButtons);
