/**
 * AYSA Metabox JavaScript
 * Main functionality for category metabox
 */

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

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

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

// ✅ Global API data cache
let aysaAPIData = null;

// Store original values for meta fields
let originalMetaValues = {
    title: '',
    description: '',
    keywords: ''
};

// Store values before SEO generation for meta fields
let preGenerationMetaValues = {
    title: '',
    description: '',
    keywords: ''
};

// Global variable to store original WordPress field values
let originalWpValues = {
    name: '',
    slug: '',
    description: '',
    shortDescription: '',
    productTitle: '',        // Add product title
    productPermalink: '',    // Add product permalink
    productDescription: ''   // Add main product description
};

// Global variable to store values before SEO generation
let preGenerationValues = {
    name: '',
    slug: '',
    description: '',
    shortDescription: '',
    productTitle: '',        // Add product title
    productPermalink: '',    // Add product permalink
    productDescription: ''   // Add main product description
};

let aysaKeywordValidationState = {
    runId: 0,
    pollTimer: null
};

document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM Content Loaded - Starting initialization in aysa-metabox.js');
    
    // Initialize AYSA Versioning Service via a dedicated function
    initializeVersioningService();
    
    // Initialize new SEO generator classes (non-blocking)
    initializeNewSeoGeneratorClasses();
    
    // Check for pending new entity data to process
    checkForPendingEntityData();
    
    // Check if we're on a form that's about to be submitted
    // WordPress sets a flag in the URL when redirecting back after submission
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('_wp_http_referer') || urlParams.has('message')) {
        console.log('Form was just submitted, skipping AYSA initialization to prevent interference');
        return; // Skip initialization if we're returning from a form submission
    }
    
    // Save original meta values
    const metaTitleInput = document.getElementById('aysa-entity-meta-title');
    const metaDescriptionInput = document.getElementById('aysa-entity-meta-description');
    const metaKeywordsInput = document.getElementById('aysa-entity-meta-keywords');
    
    if (metaTitleInput) originalMetaValues.title = metaTitleInput.value;
    if (metaDescriptionInput) originalMetaValues.description = metaDescriptionInput.value;
    if (metaKeywordsInput) originalMetaValues.keywords = metaKeywordsInput.value;
    
    // Initialize preGenerationMetaValues with the same values
    preGenerationMetaValues = JSON.parse(JSON.stringify(originalMetaValues));
    
    // Initialize tabs
    initTabs();
    
    // Initialize radar chart
    initRadarChart();
    
    // Only load data from API for existing entities
    const entityId = getEntityId();
    if (entityId !== 0) {
        // Only load data for existing entities, not new ones
        loadDataFromAPI();
    }
    
    // Initialize keyword functionality
    initKeywordManagement();
    
    // Add event listeners - use the function from aysa-actions.js
    if (typeof bindEventListeners === 'function') {
        bindEventListeners();
    } else {
        console.error('bindEventListeners function not found.');
    }
    
    // Add listener to the Add Category form
    setupFormSubmitHandlers();
    
    // Save original WordPress values
    saveOriginalWpValues();
    
    // Add description buttons with a delay to ensure all WordPress elements are loaded
    setTimeout(addDescriptionButtons, 500);
    
    // Add a single set of product fields buttons with a delay
    setTimeout(addProductFieldsButtons, 500);

    setTimeout(initKeywordValidationPanel, 300);
});

/**
 * Initialize the AYSA Versioning Service and dispatch ready event.
 * This now relies on aysa-versioningService.js to have already defined window.aysaVersioningService.
 */

/**
 * ✅ GLOBAL: Function to completely disable WordPress beforeunload warnings
 */
function disableWordPressBeforeUnloadWarning() {
    // Method 1: Set onbeforeunload to null
    window.onbeforeunload = null;
    
    // Method 2: Clear WordPress form change detection variables
    if (typeof window.postChanged !== 'undefined') {
        window.postChanged = false;
    }
    if (typeof window.tagChanged !== 'undefined') {
        window.tagChanged = false;
    }
    
    // Method 3: Override WordPress's autosave detection
    if (typeof window.autosave !== 'undefined') {
        window.autosave = function() { return false; };
    }
    
    // Method 4: Clear TinyMCE dirty state if present
    if (typeof tinyMCE !== 'undefined' && tinyMCE.editors) {
        Object.values(tinyMCE.editors).forEach(editor => {
            if (editor && typeof editor.isNotDirty === 'function') {
                editor.isNotDirty = true;
            }
            if (editor && typeof editor.setDirty === 'function') {
                editor.setDirty(false);
            }
        });
    }
    
    // Method 5: Clear WordPress editor dirty state
    if (typeof window.wp !== 'undefined' && window.wp.data) {
        try {
            if (window.wp.data.select && window.wp.data.dispatch) {
                const editPostStore = window.wp.data.select('core/edit-post');
                if (editPostStore && window.wp.data.dispatch('core/edit-post')) {
                    window.wp.data.dispatch('core/edit-post').__unstableSetHasBlockSelection(false);
                }
            }
        } catch (e) {
            console.log('Could not clear WordPress editor state:', e);
        }
    }
    
    // Method 6: Remove jQuery beforeunload handlers if present
    if (typeof window.jQuery !== 'undefined') {
        window.jQuery(window).off('beforeunload');
        window.jQuery(document).off('beforeunload');
    }
    
    // Method 7: Force override by setting multiple times with delay
    setTimeout(() => {
        window.onbeforeunload = null;
        if (typeof window.postChanged !== 'undefined') {
            window.postChanged = false;
        }
    }, 100);
    
    setTimeout(() => {
        window.onbeforeunload = null;
        if (typeof window.postChanged !== 'undefined') {
            window.postChanged = false;
        }
    }, 500);
    
    console.log('🔒 WordPress beforeunload warning completely disabled');
}

function initializeVersioningService() {
    console.log('[aysa-metabox.js] Attempting to confirm AYSA Versioning Service availability...');
    
    const checkAndDispatch = () => {
        if (window.aysaVersioningService && typeof window.aysaVersioningService.logSeoSuggestions === 'function') {
            console.log('[aysa-metabox.js] AYSA Versioning Service and logSeoSuggestions are available. Dispatching ready event.', window.aysaVersioningService);
            const event = new CustomEvent('aysaVersioningServiceReady', { detail: window.aysaVersioningService });
            document.dispatchEvent(event);
            return true;
        }
        return false;
    };

    if (checkAndDispatch()) {
        return; // Service already available
    }

    console.warn('[aysa-metabox.js] AYSA Versioning Service or logSeoSuggestions method not found initially. Attempting to load script dynamically...');
    
    const scriptId = 'aysa-versioning-service-script';
    if (document.getElementById(scriptId)) {
        console.log('[aysa-metabox.js] Versioning service script tag already exists. Waiting for it to load/execute.');
    } else {
        const script = document.createElement('script');
        script.id = scriptId;
        // Resolve plugin base URL from localized config or current script path.
        let pluginBaseUrl = '/wp-content/plugins/aysaaiseo/'; // Safe local fallback
        if (typeof aysaParams !== 'undefined' && aysaParams.plugin_url) {
            pluginBaseUrl = aysaParams.plugin_url;
            if (!pluginBaseUrl.endsWith('/')) {
                pluginBaseUrl += '/';
            }
        } else {
            const currentScript = document.currentScript || document.querySelector('script[src*="aysa-metabox.js"]');
            const currentSrc = currentScript && currentScript.src ? String(currentScript.src) : '';
            const marker = '/admin/js/';
            const markerPos = currentSrc.indexOf(marker);
            if (markerPos > 0) {
                pluginBaseUrl = currentSrc.slice(0, markerPos + 1);
            }
        }
        script.src = pluginBaseUrl + 'admin/js/services/aysa-versioningService.js?v=' + new Date().getTime(); // Cache busting
        script.async = true;
        console.log(`[aysa-metabox.js] Attempting to load script from: ${script.src}`);

        script.onload = () => {
            console.log('[aysa-metabox.js] Dynamically loaded script aysa-versioningService.js has finished loading.');
            // Now check again if the service is available
            setTimeout(() => {
                if (!checkAndDispatch()) {
                    console.error('[aysa-metabox.js] After dynamic load, AYSA Versioning Service or logSeoSuggestions method STILL not found.');
                }
            }, 500); // Wait a bit for the script to execute
        };

        script.onerror = () => {
            console.error(`[aysa-metabox.js] Failed to load script dynamically from ${script.src}. Check path and network.`);
        };

        document.head.appendChild(script);
    }

    // Fallback check in case the script was already loading or onload doesn't fire reliably in all scenarios
    setTimeout(() => {
        if (!checkAndDispatch()) {
             console.warn('[aysa-metabox.js] (Delayed check after dynamic load attempt) AYSA Versioning Service or logSeoSuggestions method STILL not found. Versioning will likely fail.');
        }
    }, 3000); // Check again after 3 seconds total
}

/**
 * Setup form submit handlers for seamless integration with WordPress
 */
function setupFormSubmitHandlers() {
    // ✅ IMPROVED: Enhanced form handling for better WordPress integration
    
    // Handle new category form (addtag form)
    const addCategoryForm = document.querySelector('#addtag');
    if (addCategoryForm) {
        console.log('Found WordPress Add Category form, setting up enhanced handler');
        
        // Find the submit button 
        const submitButton = addCategoryForm.querySelector('input[type="submit"]');
        if (submitButton) {
            // ✅ NEW: Enhanced click handler that makes API calls FIRST like for EDIT
            submitButton.addEventListener('click', async function(e) {
                // ✅ CRITICAL: Prevent duplicate submissions
                if (window.aysaNewCategoryFormSubmitting) {
                    console.log('🚫 New category form already submitting, ignoring duplicate click');
                    e.preventDefault();
                    return false;
                }
                
                console.log('🚀 WordPress Add Category submit clicked - validating first...');
                
                // ✅ CRITICAL: Validate category name is provided before any API calls
                const categoryNameInput = addCategoryForm.querySelector('input[name="tag-name"]') || addCategoryForm.querySelector('#tag-name');
                const categoryName = categoryNameInput ? categoryNameInput.value.trim() : '';
                
                if (!categoryName) {
                    console.warn('❌ Category name is required but missing');
                    
                    // Show error message to user
                    showToast('Category name is required!', 'error');
                    
                    // Focus on 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 false; // Don't prevent default, just exit
                }
                
                console.log('✅ Category name validated:', categoryName);
                
                // Prevent immediate form submission
                e.preventDefault();
                e.stopPropagation();
                
                // Mark as submitting to prevent duplicates
                window.aysaNewCategoryFormSubmitting = true;
                
                // Disable button to prevent double clicks
                this.disabled = true;
                const originalText = this.value || this.textContent;
                
                // Update button text
                if (this.value) {
                    this.value = 'Saving to API...';
                } else {
                    this.textContent = 'Saving to API...';
                }
                
                try {
                    // Collect AYSA data
                    const aysaData = collectAysaFormData();
                    if (aysaData && Object.keys(aysaData).length > 0 && (aysaData.keyword || aysaData.meta_title)) {
                        console.log('🔥 Making API calls for new category with data:', aysaData);
                        
                        // Store data for after WordPress creates the category
                        window.aysaPendingNewCategoryData = aysaData;
                        
                        // Add data to form for WordPress
                        addHiddenFieldsToForm(addCategoryForm, aysaData);
                        
                        // Update button text
                        if (this.value) {
                            this.value = 'Creating category...';
                        } else {
                            this.textContent = 'Creating category...';
                        }
                        
                        // Small delay to show the message
                        await new Promise(resolve => setTimeout(resolve, 500));
                        
                    } else {
                        console.log('No AYSA data to save, proceeding with WordPress only');
                    }
                    
                    // Set flags for WordPress processing
                    window.aysaBypassValidation = true;
                    window.aysaWordPressSubmission = true;
                    
                    // ✅ NEW: Disable WordPress beforeunload warning
                    disableWordPressBeforeUnloadWarning();
                    
                    // Submit to WordPress
                    console.log('📤 Submitting new category form to WordPress...');
                    
                    // Set up detection for after category is created
                    setTimeout(() => {
                        detectAndProcessNewCategory();
                    }, 2000);
                    
                    addCategoryForm.submit();
                    
                } catch (error) {
                    console.error('💥 Error in new category API preparation:', error);
                    
                    // Re-enable button and reset state
                    this.disabled = false;
                    if (this.value) {
                        this.value = originalText;
                    } else {
                        this.textContent = originalText;
                    }
                    window.aysaNewCategoryFormSubmitting = false;
                    
                    // Still allow WordPress submission
                    disableWordPressBeforeUnloadWarning();
                    console.log('📤 Submitting to WordPress despite error...');
                    addCategoryForm.submit();
                }
            });
        }
    }
    
    // Handle edit category form (edittag form)
    const editCategoryForm = document.querySelector('#edittag');
    if (editCategoryForm) {
        console.log('Found WordPress Edit Category form, setting up enhanced handler');
        
        // ✅ IMPROVED: Enhanced category update handling
        setupCategoryUpdateHandler(editCategoryForm);
    }
    
    // Handle WordPress post/product form (post.php)
    const postForm = document.querySelector('#post');
    if (postForm) {
        console.log('Found WordPress post form, setting up enhanced handler');
        
        // ✅ IMPROVED: Enhanced post/product handling
        setupPostUpdateHandler(postForm);
    }
    
    // ✅ IMPROVED: Enhanced global event handling
    setupGlobalFormEvents();
}

/**
 * ✅ NEW: Function to detect when new category was created and make API calls
 */
async function detectAndProcessNewCategory() {
    console.log('🔥 DETECTING NEW CATEGORY CREATION...');
    
    if (!window.aysaPendingNewCategoryData) {
        console.log('❌ No pending new category data found');
        return;
    }
    
    const pendingData = window.aysaPendingNewCategoryData;
    console.log('🔥 PENDING NEW CATEGORY DATA:', pendingData);
    
    // Try to find the new category ID
    const newCategoryId = await findNewCategoryId();
    
    if (newCategoryId && (pendingData.keyword || pendingData.meta_title)) {
        console.log('🔥 MAKING API CALLS FOR NEW CATEGORY ID:', newCategoryId);
        
        // Show the same "Saving to API..." message as for edit
        showToast('Saving to API...', 'info');
        
        try {
            // Make the API calls with the new category ID
            const result = await makeAysaApiCalls(newCategoryId, 'category', pendingData);
            
            if (result.success) {
                console.log('✅ NEW CATEGORY API CALLS COMPLETED SUCCESSFULLY');
                showToast('Category saved to API successfully!', 'success');
            } else {
                console.error('❌ NEW CATEGORY API CALLS FAILED:', result.error);
                showToast('Failed to save to API: ' + (result.error || 'Unknown error'), 'error');
            }
            
        } catch (error) {
            console.error('❌ NEW CATEGORY API CALL ERROR:', error);
            showToast('Failed to save to API: ' + error.message, 'error');
        }
    } else if (!newCategoryId) {
        console.log('❌ Could not find new category ID');
        showToast('Could not find new category ID for API save', 'warning');
    } else {
        console.log('❌ No keyword or meta title to save');
    }
    
    // Clear pending data
    window.aysaPendingNewCategoryData = null;
    window.aysaNewCategoryFormSubmitting = false;
}

/**
 * ✅ NEW: Function to find the new category ID after WordPress creates it
 */
async function findNewCategoryId() {
    console.log('🔥 SEARCHING FOR NEW CATEGORY ID...');
    
    // Method 1: Check URL parameters (most reliable)
    const urlParams = new URLSearchParams(window.location.search);
    const categoryId = urlParams.get('tag_ID');
    if (categoryId) {
        console.log('🔥 FOUND CATEGORY ID FROM URL:', categoryId);
        return parseInt(categoryId);
    }
    
    // Method 2: Check for WordPress success messages
    const messageDiv = document.querySelector('.notice-success, .updated');
    if (messageDiv) {
        const messageText = messageDiv.textContent;
        console.log('🔥 CHECKING MESSAGE:', messageText);
        
        // Look for various patterns in different languages
        const idPatterns = [
            /ID\s*:?\s*(\d+)/i,
            /category\s+(\d+)/i,
            /categorie\s+(\d+)/i,
            /\#(\d+)/,
            /id=(\d+)/i
        ];
        
        for (const pattern of idPatterns) {
            const match = messageText.match(pattern);
            if (match) {
                console.log('🔥 FOUND CATEGORY ID FROM MESSAGE:', match[1]);
                return parseInt(match[1]);
            }
        }
    }
    
    // Method 3: Check if page was redirected to edit page
    if (window.location.href.includes('tag_ID=')) {
        const match = window.location.href.match(/tag_ID=(\d+)/);
        if (match) {
            console.log('🔥 FOUND CATEGORY ID FROM REDIRECT URL:', match[1]);
            return parseInt(match[1]);
        }
    }
    
    // Method 4: Try to find the newest category in the list (if still on list page)
    const categoryRows = document.querySelectorAll('#the-list tr');
    if (categoryRows.length > 0) {
        const firstRow = categoryRows[0];
        const editLink = firstRow.querySelector('a[href*="tag_ID"]');
        if (editLink) {
            const href = editLink.getAttribute('href');
            const idMatch = href.match(/tag_ID=(\d+)/);
            if (idMatch) {
                console.log('🔥 FOUND CATEGORY ID FROM FIRST ROW:', idMatch[1]);
                return parseInt(idMatch[1]);
            }
        }
    }
    
    console.log('❌ Could not find new category ID');
    return null;
}

/**
 * ✅ IMPROVED: Enhanced category update handler with API calls BEFORE WordPress
 */
function setupCategoryUpdateHandler(editCategoryForm) {
    // Create enhanced save function that makes API calls FIRST
    if (typeof window.saveAysaDataWithApiCalls !== 'function') {
        window.aysaDataProcessed = false;
        window.aysaCategoryFormSubmitting = false; // ✅ NEW: Prevent duplicate submissions
        
        window.saveAysaDataWithApiCalls = async function() {
            if (window.aysaDataProcessed) {
                console.log('AYSA data already processed for this submission, skipping');
                return Promise.resolve({
                    success: true,
                    message: 'Already processed, skipping',
                    skipped: true
                });
            }
            
            try {
                console.log('🚀 Starting AYSA API calls BEFORE WordPress save...');
                
                // Collect form data
                const aysaData = collectAysaFormData();
                if (!aysaData || Object.keys(aysaData).length === 0) {
                    console.log('No AYSA data to save');
                    window.aysaDataProcessed = true;
                    return Promise.resolve({
                        success: true,
                        message: 'No AYSA data to save',
                        skipped: true
                    });
                }
                
                // Get entity info
                const entityId = getEntityId();
                const entityType = getEntityTypeGood();
                
                if (!entityId) {
                    console.warn('No entity ID found, skipping AYSA save');
                    return Promise.resolve({
                        success: false,
                        error: 'No entity ID found',
                        skipped: true
                    });
                }
                
                console.log('🔥 Making API calls for entity:', entityId, entityType);
                
                // ✅ STEP 1: Make the actual API calls FIRST (upsert + insert many)
                const apiCallsResult = await makeAysaApiCalls(entityId, entityType, aysaData);
                
                if (apiCallsResult.success) {
                    console.log('✅ API calls completed successfully, now saving to WordPress');
                    
                    // ✅ STEP 2: Save to WordPress via AJAX (as backup/sync)
                    const wpSaveResult = await saveAysaDataViaAjax(entityId, entityType, aysaData);
                    
                    // ✅ STEP 3: Also add to form for WordPress native save
                    addHiddenFieldsToForm(editCategoryForm, aysaData);
                    
                    window.aysaDataProcessed = true;
                    console.log('🎉 All AYSA operations completed successfully');
                    
                    return Promise.resolve({
                        success: true,
                        apiCalls: apiCallsResult,
                        wpSave: wpSaveResult
                    });
                    
                } else {
                    console.error('❌ API calls failed:', apiCallsResult.error);
                    
                    // Still add data to form as backup
                    addHiddenFieldsToForm(editCategoryForm, aysaData);
                    window.aysaDataProcessed = true;
                    
                    // Don't block WordPress save even if API fails
                    return Promise.resolve({
                        success: false,
                        error: apiCallsResult.error,
                        fallback: 'wordpress_only'
                    });
                }
                
            } catch (error) {
                console.error('💥 Error in API calls:', error);
                
                // Fallback: add data to form
                const aysaData = collectAysaFormData();
                if (aysaData) {
                    addHiddenFieldsToForm(editCategoryForm, aysaData);
                }
                
                window.aysaDataProcessed = true;
                return Promise.resolve({
                    success: false,
                    error: error.message,
                    fallback: 'wordpress_only'
                });
            }
        };
    }
    
    // Add click handler to category update button
    const updateButton = editCategoryForm.querySelector('input[type="submit"], .button-primary, #submit');
    if (updateButton) {
        console.log('Found category update button, adding API-first save handler');
        
        updateButton.addEventListener('click', async function(e) {
            // ✅ CRITICAL: Prevent duplicate submissions
            if (window.aysaCategoryFormSubmitting) {
                console.log('🚫 Category form already submitting, ignoring duplicate click');
                e.preventDefault();
                return false;
            }
            
            console.log('🚀 WordPress category update button clicked - making API calls FIRST...');
            
            // Prevent immediate form submission
            e.preventDefault();
            e.stopPropagation(); // ✅ NEW: Stop event bubbling
            
            // Mark as submitting to prevent duplicates
            window.aysaCategoryFormSubmitting = true;
            
            // Disable button to prevent double clicks
            this.disabled = true;
            const originalText = this.value || this.textContent;
            
            // Update button text
            if (this.value) {
                this.value = 'Saving to API...';
            } else {
                this.textContent = 'Saving to API...';
            }
            
                         try {
                 // ✅ CRITICAL: Make API calls FIRST, before WordPress
                 const result = await window.saveAysaDataWithApiCalls();
                 
                 if (result && result.success) {
                    console.log('✅ API calls completed, now submitting to WordPress...');
                    
                    // Update button text
                    if (this.value) {
                        this.value = 'Submitting to WordPress...';
                    } else {
                        this.textContent = 'Submitting to WordPress...';
                    }
                    
                    // Small delay to show the message
                    await new Promise(resolve => setTimeout(resolve, 500));
                    
                                 } else {
                     console.warn('⚠️ API calls failed, but continuing with WordPress save');
                     if (result && result.error) {
                         console.log('Error details:', result.error);
                     }
                 }
                
                // ✅ NEW: Completely disable WordPress beforeunload warning
                disableWordPressBeforeUnloadWarning();
                
                // NOW submit to WordPress
                console.log('📤 Submitting form to WordPress...');
                editCategoryForm.submit();
                
            } catch (error) {
                console.error('💥 Error in API-first save:', error);
                
                // Re-enable button and reset state
                this.disabled = false;
                if (this.value) {
                    this.value = originalText;
                } else {
                    this.textContent = originalText;
                }
                window.aysaCategoryFormSubmitting = false;
                
                // ✅ NEW: Completely disable WordPress beforeunload warning
                disableWordPressBeforeUnloadWarning();
                
                // Still allow WordPress submission
                console.log('📤 Submitting to WordPress despite API error...');
                editCategoryForm.submit();
            }
        });
    }
    
    // Enhanced submit handler as backup (in case direct submit happens)
    editCategoryForm.addEventListener('submit', async function(e) {
        // ✅ NEW: If we're already handling submission via button click, don't interfere
        if (window.aysaCategoryFormSubmitting) {
            console.log('⚡ Category form submit event - button handler already processing, allowing...');
            return; // Let it proceed
        }
        
        if (!window.aysaDataProcessed) {
            console.log('⚡ Form submit event - making quick API calls...');
            
            // Don't prevent if we can't wait
            setTimeout(async () => {
                try {
                    await window.saveAysaDataWithApiCalls();
                } catch (error) {
                    console.error('Error in submit handler API calls:', error);
                }
            }, 0);
        }
        
        // ✅ NEW: Disable the beforeunload warning to prevent "Changes may not be saved"
        disableWordPressBeforeUnloadWarning();
        
        // Reset flag for future submissions
        setTimeout(() => {
            window.aysaDataProcessed = false;
            window.aysaCategoryFormSubmitting = false;
        }, 2000);
    });
}

/**
 * ✅ NEW: Language-independent detection of update vs publish operation
 */
function detectPostOperation(postForm, buttonText) {
    let isUpdate = false;
    
    // Method 1: Check if post already has an ID (exists in database)
    const postIdField = postForm.querySelector('input[name="post_ID"]');
    const postId = postIdField ? parseInt(postIdField.value) : 0;
    
    // Method 2: Check current post status
    const currentPostStatus = postForm.querySelector('input[name="original_post_status"]');
    const postStatus = currentPostStatus ? currentPostStatus.value : '';
    
    // Method 3: Check button text for common update words in multiple languages
    const updateKeywords = ['update', 'actualizează', 'actualizeaza', 'actualizar', 'mettre à jour', 'aggiornare', 'aktualisieren', 'modifier', 'bearbeiten'];
    const textLower = (buttonText || '').toLowerCase();
    const hasUpdateKeyword = updateKeywords.some(keyword => textLower.includes(keyword));
    
    // Determine if this is an update
    if (postId > 0 && (postStatus === 'publish' || postStatus === 'private' || hasUpdateKeyword)) {
        isUpdate = true;
        console.log('🔄 Detected UPDATE operation - Post ID:', postId, 'Status:', postStatus, 'Button text:', buttonText);
    } else {
        isUpdate = false;
        console.log('🆕 Detected NEW PUBLISH operation - Post ID:', postId, 'Status:', postStatus, 'Button text:', buttonText);
    }
    
    return isUpdate;
}

/**
 * ✅ IMPROVED: Enhanced post/product update handler with API calls BEFORE WordPress
 */
function setupPostUpdateHandler(postForm) {
    // Create enhanced save function for posts that makes API calls FIRST
    window.aysaDataProcessed = false;
    window.aysaFormSubmitting = false; // ✅ NEW: Prevent duplicate submissions
    

    
    window.saveAysaPostDataWithApiCalls = async function() {
        if (window.aysaDataProcessed) {
            console.log('AYSA post data already processed, skipping');
            return Promise.resolve({
                success: true,
                message: 'Already processed, skipping',
                skipped: true
            });
        }
        
        try {
            console.log('🚀 Starting AYSA API calls for POST BEFORE WordPress save...');
            
            // Collect form data
            const aysaData = collectAysaFormData();
            if (!aysaData || Object.keys(aysaData).length === 0) {
                console.log('No AYSA post data to save');
                window.aysaDataProcessed = true;
                return Promise.resolve({
                    success: true,
                    message: 'No AYSA data to save',
                    skipped: true
                });
            }
            
            // Get entity info
            const entityId = getEntityId();
            const entityType = getEntityTypeGood();
            
            if (!entityId) {
                console.warn('No post ID found, skipping AYSA save');
                return Promise.resolve({
                    success: false,
                    error: 'No entity ID found',
                    skipped: true
                });
            }
            
            console.log('🔥 Making API calls for post:', entityId, entityType);
            
            // ✅ STEP 1: Make the actual API calls FIRST (upsert + insert many)
            const apiCallsResult = await makeAysaApiCalls(entityId, entityType, aysaData);
            
            if (apiCallsResult.success) {
                console.log('✅ API calls completed successfully for post, now saving to WordPress');
                
                // ✅ STEP 2: Save to WordPress via AJAX (as backup/sync)
                const wpSaveResult = await saveAysaDataViaAjax(entityId, entityType, aysaData);
                
                // ✅ STEP 3: Also add to form for WordPress native save
                addHiddenFieldsToForm(postForm, aysaData);
                
                window.aysaDataProcessed = true;
                console.log('🎉 All AYSA post operations completed successfully');
                
                return Promise.resolve({
                    success: true,
                    apiCalls: apiCallsResult,
                    wpSave: wpSaveResult
                });
                
            } else {
                console.error('❌ API calls failed for post:', apiCallsResult.error);
                
                // Still add data to form as backup
                addHiddenFieldsToForm(postForm, aysaData);
                window.aysaDataProcessed = true;
                
                // Don't block WordPress save even if API fails
                return Promise.resolve({
                    success: false,
                    error: apiCallsResult.error,
                    fallback: 'wordpress_only'
                });
            }
            
        } catch (error) {
            console.error('💥 Error in post API calls:', error);
            
            // Fallback: add data to form
            const aysaData = collectAysaFormData();
            if (aysaData) {
                addHiddenFieldsToForm(postForm, aysaData);
            }
            
            window.aysaDataProcessed = true;
            return Promise.resolve({
                success: false,
                error: error.message,
                fallback: 'wordpress_only'
            });
        }
    };
    
    // Add click handler to publish/update button
    // ✅ CRITICAL: Support both Classic Editor (#publish) and Gutenberg (.editor-post-publish-button)
    
    // 🔍 DEBUG: Let's see what buttons actually exist on this page
    console.log('🔍 DEBUG: AYSA metabox script loaded and setupPostUpdateHandler called');
    console.log('🔍 DEBUG: Searching for publish buttons...');
    console.log('🔍 #publish exists:', !!document.querySelector('#publish'));
    console.log('🔍 .editor-post-publish-button__button exists:', !!document.querySelector('.editor-post-publish-button__button'));
    console.log('🔍 .editor-post-publish-panel__toggle exists:', !!document.querySelector('.editor-post-publish-panel__toggle'));
    console.log('🔍 .editor-post-publish-button exists:', !!document.querySelector('.editor-post-publish-button'));
    console.log('🔍 input[name="publish"] exists:', !!document.querySelector('input[name="publish"]'));
    console.log('🔍 input[type="submit"] exists:', !!document.querySelector('input[type="submit"]'));
    console.log('🔍 Current URL:', window.location.href);
    console.log('🔍 window.aysaBypassValidation:', window.aysaBypassValidation);
    console.log('🔍 Post form exists:', !!document.getElementById('post'));
    
    const publishButton = document.querySelector('#publish') || 
                         document.querySelector('.editor-post-publish-button__button') ||
                         document.querySelector('.editor-post-publish-panel__toggle') ||
                         document.querySelector('.editor-post-publish-button') ||
                         document.querySelector('input[name="publish"]') ||
                         document.querySelector('input[type="submit"][value="Update"]') ||
                         document.querySelector('input[type="submit"][value="Publish"]');
    
    // ✅ IMPORTANT: For any WordPress admin page, also set up a delayed check as buttons might load later
    if (!publishButton) {
        console.log('🔍 Publish button not found immediately, setting up delayed detection...');
        setTimeout(() => {
            console.log('🔍 DELAYED SEARCH: Searching again for publish buttons...');
            const delayedButton = document.querySelector('#publish') ||
                                document.querySelector('.editor-post-publish-button__button') ||
                                document.querySelector('.editor-post-publish-panel__toggle') ||
                                document.querySelector('.editor-post-publish-button') ||
                                document.querySelector('input[name="publish"]') ||
                                document.querySelector('input[type="submit"][value="Update"]') ||
                                document.querySelector('input[type="submit"][value="Publish"]') ||
                                document.querySelector('input[type="submit"][value="Actualizează"]'); // Romanian
            
            if (delayedButton) {
                console.log('🎯 Found delayed publish button:', delayedButton.tagName, delayedButton.className || delayedButton.value);
                
                if (delayedButton.className && delayedButton.className.includes('editor-post-publish')) {
                    setupGutenbergHook();
                } else {
                    setupClassicPublishButton(delayedButton);
                }
            } else {
                console.log('⚠️ Still no publish button found after delay - setting up form submit fallback');
                setupFormSubmitFallback();
            }
        }, 2000);
    }
    
    function setupGutenbergHook() {
        console.log('🎯 Setting up Gutenberg save hook...');
        if (typeof wp !== 'undefined' && wp.data) {
            wp.data.subscribe(async () => {
                const isAutosaving = wp.data.select('core/editor')?.isAutosavingPost();
                const isSavingPost = wp.data.select('core/editor')?.isSavingPost();
                const wasPublishing = window.aysaWasPublishing || false;
                
                if (isSavingPost && !isAutosaving && !wasPublishing && !window.aysaDataProcessed) {
                    window.aysaWasPublishing = true;
                    console.log('🚀 Gutenberg publish detected - making API calls...');
                    
                    try {
                        const result = await window.saveAysaPostDataWithApiCalls();
                        console.log('✅ AYSA API calls completed for Gutenberg post');
                    } catch (error) {
                        console.error('❌ AYSA API calls failed for Gutenberg post:', error);
                    }
                }
                
                if (!isSavingPost) {
                    window.aysaWasPublishing = false;
                }
            });
        }
    }
    
    if (publishButton) {
        console.log('🔍 Found publish button:', publishButton.className, publishButton.textContent);
        
        // ✅ CRITICAL: Different handling for Gutenberg vs Classic Editor
        const isGutenberg = publishButton.className.includes('editor-post-publish');
        
        if (isGutenberg) {
            console.log('🎯 Detected Gutenberg editor - using pre-publish hook');
            setupGutenbergHook();
        } else {
            // Classic editor behavior
            publishButton.addEventListener('click', async function(e) {
                // ✅ CRITICAL: Prevent duplicate submissions
                if (window.aysaFormSubmitting) {
                    console.log('🚫 Form already submitting, ignoring duplicate click');
                    e.preventDefault();
                    return false;
                }
                
                console.log('🚀 WordPress publish button clicked - making API calls FIRST...');
                
                // Prevent immediate form submission
                e.preventDefault();
                e.stopPropagation(); // ✅ NEW: Stop event bubbling
            
            // Mark as submitting to prevent duplicates
            window.aysaFormSubmitting = true;
            
            // Disable button to prevent double clicks
            this.disabled = true;
            const originalText = this.value || this.textContent;
            
            // Update button text
            if (this.value) {
                this.value = 'Saving to API...';
            } else {
                this.textContent = 'Saving to API...';
            }
            
            try {
                // ✅ CRITICAL: Make API calls FIRST, before WordPress
                const result = await window.saveAysaPostDataWithApiCalls();
                
                if (result && result.success) {
                    console.log('✅ API calls completed for post, now submitting to WordPress...');
                    
                    // Update button text
                    if (this.value) {
                        this.value = 'Publishing...';
                    } else {
                        this.textContent = 'Publishing...';
                    }
                    
                    // Small delay to show the message
                    await new Promise(resolve => setTimeout(resolve, 500));
                    
                } else {
                    console.warn('⚠️ API calls failed for post, but continuing with WordPress save');
                    if (result && result.error) {
                        console.log('Error details:', result.error);
                    }
                }
                
                // ✅ CRITICAL: Submit form with proper post status
                console.log('📝 Submitting form with WordPress publish behavior...');
                
                // Add AYSA data to form first
                const aysaData = collectAysaFormData();
                if (aysaData && Object.keys(aysaData).length > 0) {
                    addHiddenFieldsToForm(postForm, aysaData);
                }
                
                // ✅ CRITICAL: Detect operation type (language-independent)
                const buttonText = originalText || '';
                const isUpdate = detectPostOperation(postForm, buttonText);
                
                // Remove any existing publish/save actions
                const existingActions = postForm.querySelectorAll('input[name="publish"], input[name="save"]');
                existingActions.forEach(action => action.remove());
                
                // Add the correct action
                const publishAction = document.createElement('input');
                publishAction.type = 'hidden';
                
                if (isUpdate) {
                    publishAction.name = 'save';
                    publishAction.value = 'Update';
                    console.log('📝 Added UPDATE action to form');
                } else {
                    publishAction.name = 'publish';
                    publishAction.value = 'Publish';
                    console.log('📝 Added PUBLISH action to form');
                }
                
                postForm.appendChild(publishAction);
                
                // ✅ CRITICAL: Also add post_status to ensure proper status change
                let postStatusField = postForm.querySelector('input[name="post_status"]');
                if (!postStatusField) {
                    postStatusField = document.createElement('input');
                    postStatusField.type = 'hidden';
                    postStatusField.name = 'post_status';
                    postForm.appendChild(postStatusField);
                }
                
                if (isUpdate) {
                    postStatusField.value = 'publish'; // Keep it published when updating
                    console.log('📝 Set post_status to "publish" for update');
                } else {
                    postStatusField.value = 'publish'; // Change from draft to published
                    console.log('📝 Set post_status to "publish" for new publish');
                }
                
                // ✅ NEW: Disable the beforeunload warning to prevent "Changes may not be saved"
                disableWordPressBeforeUnloadWarning();
                
                // Submit the form
                console.log('📝 Submitting form to WordPress...');
                postForm.submit();
                
                console.log('✅ Form submission initiated!');
                
            } catch (error) {
                console.error('💥 Error in post API-first save:', error);
                
                // Re-enable button and reset state
                this.disabled = false;
                if (this.value) {
                    this.value = originalText;
                } else {
                    this.textContent = originalText;
                }
                window.aysaFormSubmitting = false;
                
                // Still allow WordPress submission
                console.log('📤 Submitting post to WordPress despite API error...');
                
                // Add AYSA data to form first
                const aysaData = collectAysaFormData();
                if (aysaData && Object.keys(aysaData).length > 0) {
                    addHiddenFieldsToForm(postForm, aysaData);
                }
                
                // ✅ CRITICAL: Detect operation type (language-independent)
                const buttonText = originalText || '';
                const isUpdate = detectPostOperation(postForm, buttonText);
                
                // Remove any existing publish/save actions
                const existingActions = postForm.querySelectorAll('input[name="publish"], input[name="save"]');
                existingActions.forEach(action => action.remove());
                
                // Add the correct action
                const publishAction = document.createElement('input');
                publishAction.type = 'hidden';
                
                if (isUpdate) {
                    publishAction.name = 'save';
                    publishAction.value = 'Update';
                    console.log('📝 Added UPDATE action to form after error');
                } else {
                    publishAction.name = 'publish';
                    publishAction.value = 'Publish';
                    console.log('📝 Added PUBLISH action to form after error');
                }
                
                postForm.appendChild(publishAction);
                
                // ✅ CRITICAL: Also add post_status to ensure proper status change
                let postStatusField = postForm.querySelector('input[name="post_status"]');
                if (!postStatusField) {
                    postStatusField = document.createElement('input');
                    postStatusField.type = 'hidden';
                    postStatusField.name = 'post_status';
                    postForm.appendChild(postStatusField);
                }
                
                if (isUpdate) {
                    postStatusField.value = 'publish'; // Keep it published when updating
                    console.log('📝 Set post_status to "publish" for update after error');
                } else {
                    postStatusField.value = 'publish'; // Change from draft to published
                    console.log('📝 Set post_status to "publish" for new publish after error');
                }
                
                // ✅ NEW: Disable the beforeunload warning to prevent "Changes may not be saved"
                disableWordPressBeforeUnloadWarning();
                
                // Submit the form
                console.log('📝 Submitting form to WordPress after error...');
                postForm.submit();
                
                console.log('✅ Form submission initiated after error!');
            }
            });
        }
    } else {
        console.log('⚠️ No publish button found - page might use different save mechanism');
    }
    
    // ✅ SIMPLIFIED: Submit handler - just preserve AYSA data (NO DUPLICATE SUBMISSION)
    postForm.addEventListener('submit', function(e) {
        // ✅ NEW: If we're already handling submission via button click, don't interfere
        if (window.aysaFormSubmitting) {
            console.log('⚡ Form submit event - button handler already processing, allowing...');
            return; // Let it proceed
        }
        
        if (!window.aysaDataProcessed) {
            console.log('⚡ Post form submit event - preserving AYSA data...');
            
            // Collect and add AYSA data to form
            const aysaData = collectAysaFormData();
            if (aysaData && Object.keys(aysaData).length > 0) {
                addHiddenFieldsToForm(postForm, aysaData);
            }
        }
        
        // ✅ NEW: Disable the beforeunload warning to prevent "Changes may not be saved"
        disableWordPressBeforeUnloadWarning();
        
        // Reset flag for future submissions
        setTimeout(() => {
            window.aysaDataProcessed = false;
            window.aysaFormSubmitting = false;
        }, 1000);
    });
}

/**
 * ✅ Setup classic publish button with AYSA save intercept
 */
function setupClassicPublishButton(button) {
    console.log('🎯 Setting up classic publish button:', button.tagName, button.value || button.textContent);
    
    button.addEventListener('click', async function(e) {
        // ✅ CRITICAL: Prevent duplicate submissions
        if (window.aysaFormSubmitting) {
            console.log('🚫 Form already submitting, ignoring duplicate click');
            e.preventDefault();
            return false;
        }
        
        console.log('🚀 WordPress publish button clicked - making API calls FIRST...');
        
        // Prevent immediate form submission
        e.preventDefault();
        e.stopPropagation();
        
        // Set submission flag
        window.aysaFormSubmitting = true;
        
        // Store original button state
        const originalText = this.value || this.textContent;
        const wasDisabled = this.disabled;
        
        // Update button to show loading
        this.disabled = true;
        if (this.value) {
            this.value = 'Processing...';
        } else {
            this.textContent = 'Processing...';
        }
        
        try {
            console.log('🔄 Making AYSA API calls first...');
            const result = await window.saveAysaPostDataWithApiCalls();
            
            if (result.success) {
                console.log('✅ AYSA API calls completed successfully!');
            } else {
                console.log('⚠️ AYSA API calls had issues:', result.error);
            }
            
            // Reset button state
            this.disabled = wasDisabled;
            if (this.value) {
                this.value = originalText;
            } else {
                this.textContent = originalText;
            }
            window.aysaFormSubmitting = false;
            
            // Now submit the form to WordPress
            console.log('📤 Submitting to WordPress after API calls...');
            const postForm = document.getElementById('post');
            if (postForm) {
                postForm.submit();
            }
            
        } catch (error) {
            console.error('💥 Error in API-first save:', error);
            
            // Reset button state
            this.disabled = wasDisabled;
            if (this.value) {
                this.value = originalText;
            } else {
                this.textContent = originalText;
            }
            window.aysaFormSubmitting = false;
            
            // Still submit to WordPress
            console.log('📤 Submitting to WordPress despite API error...');
            const postForm = document.getElementById('post');
            if (postForm) {
                postForm.submit();
            }
        }
    });
}

/**
 * ✅ Setup form submit fallback when no publish button is found
 */
function setupFormSubmitFallback() {
    console.log('🎯 Setting up form submit fallback...');
    
    const postForm = document.getElementById('post');
    if (!postForm) {
        console.log('⚠️ No post form found for fallback');
        return;
    }
    
    // Add a submit event listener as last resort
    postForm.addEventListener('submit', async function(e) {
        // Only intercept if we haven't processed AYSA data yet
        if (window.aysaDataProcessed || window.aysaFormSubmitting) {
            console.log('⚡ Form submit fallback - already processed, allowing...');
            return;
        }
        
        console.log('🚀 Form submit fallback - making API calls FIRST...');
        
        // Prevent submission temporarily
        e.preventDefault();
        
        window.aysaFormSubmitting = true;
        
        try {
            console.log('🔄 Making AYSA API calls via fallback...');
            const result = await window.saveAysaPostDataWithApiCalls();
            
            if (result.success) {
                console.log('✅ Fallback AYSA API calls completed successfully!');
            } else {
                console.log('⚠️ Fallback AYSA API calls had issues:', result.error);
            }
            
            window.aysaFormSubmitting = false;
            
            // Now submit the form
            console.log('📤 Submitting to WordPress after fallback API calls...');
            this.submit();
            
        } catch (error) {
            console.error('💥 Error in fallback API-first save:', error);
            window.aysaFormSubmitting = false;
            
            // Still submit to WordPress
            console.log('📤 Submitting to WordPress despite fallback API error...');
            this.submit();
        }
    });
}

/**
 * ✅ NEW: Collect AYSA form data from the metabox
 */
function collectAysaFormData() {
    const data = {};
    
    try {
        // Collect main fields
        const keywordField = document.getElementById('aysa-entity-keyword');
        const secondKeywordField = document.getElementById('aysa-entity-second-keyword');
        const metaTitleField = document.getElementById('aysa-entity-meta-title');
        const metaDescriptionField = document.getElementById('aysa-entity-meta-description');
        const metaKeywordsField = document.getElementById('aysa-entity-meta-keywords');
        
        if (keywordField && keywordField.value.trim()) {
            data.keyword = keywordField.value.trim();
        }
        
        // ✅ Always include secondary keywords (even if empty) to respect user's intention
        if (secondKeywordField) {
            data.second_keyword = secondKeywordField.value.trim();
            console.log('📋 Secondary keywords from form field:', data.second_keyword || '(empty)');
        }
        
        if (metaTitleField && metaTitleField.value.trim()) {
            data.aysa_meta_title = metaTitleField.value.trim();
        }
        
        if (metaDescriptionField && metaDescriptionField.value.trim()) {
            data.aysa_meta_description = metaDescriptionField.value.trim();
        }
        
        if (metaKeywordsField && metaKeywordsField.value.trim()) {
            data.aysa_meta_keywords = metaKeywordsField.value.trim();
        }
        
        // Collect track checkbox
        const trackField = document.getElementById('track');
        if (trackField) {
            data.track = trackField.checked ? 1 : 0;
        }
        
        // ✅ SEO SETTINGS fields - using correct IDs from metabox
        const targetedSearchEngineField = document.getElementById('targeted_se');
        const targetedCountryField = document.getElementById('targeted_country');
        const targetedRegionField = document.getElementById('targeted_region');
        const targetedCityField = document.getElementById('targeted_city');
        const updateFrequencyField = document.getElementById('update_frequency');
        const languageOptimizeField = document.getElementById('language_optimize');
        const deviceOptimizeField = document.getElementById('device_optimize');
        
        if (targetedSearchEngineField) {
            data.targeted_search_engine = targetedSearchEngineField.value.trim();
        }
        
        if (targetedCountryField) {
            data.targeted_country = targetedCountryField.value.trim();
        }
        
        if (targetedRegionField) {
            data.targeted_region = targetedRegionField.value.trim();
        }
        
        if (targetedCityField) {
            data.targeted_city = targetedCityField.value.trim();
        }
        
        if (updateFrequencyField) {
            data.update_frequency = updateFrequencyField.value.trim();
        }
        
        if (languageOptimizeField) {
            data.language_optimize = languageOptimizeField.value.trim();
        }
        
        if (deviceOptimizeField) {
            data.device_optimize = deviceOptimizeField.value.trim();
        }
        
        // ✅ ADVANCED fields - using correct IDs from metabox
        const indexField = document.getElementById('index');
        const noFollowField = document.getElementById('nofollow');
        const noArchiveField = document.getElementById('noarchive');
        const noImageIndexField = document.getElementById('noimageindex');
        const noSnippetField = document.getElementById('nosnippet');
        const maxSnippetField = document.getElementById('max_snippet');
        const maxVideoPreviewField = document.getElementById('max_video_preview');
        const maxImagePreviewField = document.getElementById('max_image_preview');
        const canonicalUrlField = document.getElementById('canonical_url');
        
        // Handle index field (select, not checkbox)
        if (indexField) {
            data.index = indexField.value === 'index'; // true for 'index', false for 'noindex'
        }
        
        if (noFollowField) {
            data.no_follow = noFollowField.checked;
        }
        
        if (noArchiveField) {
            data.no_archive = noArchiveField.checked;
        }
        
        if (noImageIndexField) {
            data.no_image_index = noImageIndexField.checked;
        }
        
        if (noSnippetField) {
            data.no_snippet = noSnippetField.checked;
        }
        
        // Handle max snippet - it's a checkbox + value field
        if (maxSnippetField && maxSnippetField.checked) {
            const maxSnippetValueField = document.getElementById('number-max-snippet');
            if (maxSnippetValueField) {
                data.max_snippet = parseInt(maxSnippetValueField.value.trim()) || -1;
            }
        } else {
            data.max_snippet = null;
        }
        
        // Handle max video preview - it's a checkbox + value field
        if (maxVideoPreviewField && maxVideoPreviewField.checked) {
            const maxVideoPreviewValueField = document.getElementById('number-max-video-preview');
            if (maxVideoPreviewValueField) {
                data.max_video_preview = parseInt(maxVideoPreviewValueField.value.trim()) || -1;
            }
        } else {
            data.max_video_preview = null;
        }
        
        // Handle max image preview - it's a checkbox + select field
        if (maxImagePreviewField && maxImagePreviewField.checked) {
            const imagePreviewSelect = document.getElementById('image_preview');
            if (imagePreviewSelect) {
                data.max_image_preview = imagePreviewSelect.value.trim();
            }
        } else {
            data.max_image_preview = '';
        }
        
        if (canonicalUrlField) {
            data.canonical_url = canonicalUrlField.value.trim();
        }
        
    } catch (error) {
        console.error('Error collecting AYSA form data:', error);
    }
    
    return data;
}

/**
 * ✅ NEW: Add hidden fields to form for WordPress processing
 */
function addHiddenFieldsToForm(form, data) {
    try {
        Object.keys(data).forEach(key => {
            // ✅ CRITICAL: Check for problematic field names that could overwrite WordPress core fields
            if (key === 'post_title' || key === 'title' || key === 'meta_title' || key === 'meta_description' || key === 'meta_keywords') {
                console.error(`🚨 CRITICAL ERROR: Skipping dangerous field name: ${key}`);
                console.error(`🚨 This field could interfere with WordPress core functionality!`);
                console.error(`🚨 Field value:`, data[key]);
                return; // Skip creating this field
            }
            
            // Remove existing hidden field if present
            const existingField = form.querySelector(`input[name="${key}"][type="hidden"]`);
            if (existingField) {
                existingField.remove();
            }
            
            // Add new hidden field
            const hiddenField = document.createElement('input');
            hiddenField.type = 'hidden';
            hiddenField.name = key;
            hiddenField.value = data[key];
            hiddenField.setAttribute('data-aysa', 'true');
            
            form.appendChild(hiddenField);
        });
        
        console.log('Added hidden fields to form:', Object.keys(data));
        
    } catch (error) {
        console.error('Error adding hidden fields to form:', error);
    }
}

/**
 * ✅ NEW: Save AYSA data via AJAX
 */
async function saveAysaDataViaAjax(entityId, entityType, data) {
    return new Promise((resolve, reject) => {
        if (!window.jQuery) {
            reject(new Error('jQuery not available'));
            return;
        }
        
        const ajaxData = {
            action: 'aysa_save_seo_data',
            entity_id: entityId,
            entity_type: entityType.toLowerCase(), // ✅ NORMALIZE to lowercase
            nonce: typeof aysaParams !== 'undefined' ? aysaParams.nonce : '',
            
            // ✅ CRITICAL FIX: Map AYSA field names to PHP expected names
            keyword: data.keyword || '',
            second_keyword: data.second_keyword || '',
            meta_title: data.aysa_meta_title || '',  // ← CRITICAL MAPPING: aysa_meta_title → meta_title
            meta_description: data.aysa_meta_description || '',  // ← CRITICAL MAPPING: aysa_meta_description → meta_description  
            meta_keywords: data.aysa_meta_keywords || '',  // ← CRITICAL MAPPING: aysa_meta_keywords → meta_keywords
            track: data.track || 0,
            
            // SEO Settings - pass through as-is
            targeted_search_engine: data.targeted_search_engine || '',
            targeted_country: data.targeted_country || '',
            targeted_region: data.targeted_region || '',
            targeted_city: data.targeted_city || '',
            update_frequency: data.update_frequency || '',
            language_optimize: data.language_optimize || '',
            device_optimize: data.device_optimize || '',
            
            // Advanced Settings - pass through as-is
            index: data.index,
            no_follow: data.no_follow,
            no_archive: data.no_archive,
            no_image_index: data.no_image_index,
            no_snippet: data.no_snippet,
            max_snippet: data.max_snippet,
            max_video_preview: data.max_video_preview,
            max_image_preview: data.max_image_preview,
            canonical_url: data.canonical_url || ''
        };
        
        console.log('🔍 AJAX SAVE: Original data:', JSON.stringify(data, null, 2));
        console.log('🔍 AJAX SAVE: Mapped data for PHP:', JSON.stringify(ajaxData, null, 2));
        
        window.jQuery.ajax({
            url: typeof aysaParams !== 'undefined' ? aysaParams.ajax_url : ajaxurl,
            type: 'POST',
            data: ajaxData,
            timeout: 10000,
            success: function(response) {
                console.log('🔍 AJAX SAVE: Success response:', response);
                if (response && !response.success) {
                    console.error('🚨 AJAX SAVE FAILED!');
                    console.error('🚨 Error details:', response.data || response);
                    console.error('🚨 Full response object:', JSON.stringify(response, null, 2));
                }
                resolve(response);
            },
            error: function(xhr, status, error) {
                console.error('AJAX save error:', error);
                resolve({ success: false, error: error });
            }
        });
    });
}

/**
 * ✅ IMPROVED: Enhanced global event handling
 */
function setupGlobalFormEvents() {
    // Handle "Add New Category" button separately
    const addNewCategoryButton = document.querySelector('#category-add-submit');
    if (addNewCategoryButton) {
        addNewCategoryButton.addEventListener('click', function(e) {
            window.aysaBypassValidation = true;
            window.aysaWordPressSubmission = true;
            console.log('Add New Category button clicked, AYSA validation bypassed');
            
            // Collect and preserve AYSA data
            const aysaData = collectAysaFormData();
            if (aysaData && Object.keys(aysaData).length > 0) {
                const form = this.closest('form');
                if (form) {
                    addHiddenFieldsToForm(form, aysaData);
                }
            }
        });
    }
    
    // Enhanced keyboard event handling
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            const activeElement = document.activeElement;
            
            // If in WordPress form field (not AYSA container)
            if (activeElement && 
                (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') && 
                !activeElement.closest('.aysa-metabox-container')) {
                
                window.aysaBypassValidation = true;
                window.aysaWordPressSubmission = true;
                console.log('Enter key in WordPress field, AYSA validation bypassed');
                
                // Quick data preservation if in a form
                const form = activeElement.closest('form');
                if (form) {
                    const aysaData = collectAysaFormData();
                    if (aysaData && Object.keys(aysaData).length > 0) {
                        setTimeout(() => addHiddenFieldsToForm(form, aysaData), 10);
                    }
                }
            }
        }
    });
    
    // Auto-cleanup flags
    setInterval(() => {
        if (window.aysaBypassValidation || window.aysaWordPressSubmission) {
            window.aysaBypassValidation = false;
            window.aysaWordPressSubmission = false;
        }
    }, 5000);
}

/**
 * Initialize tabs functionality
 */
function initTabs() {
    // Check if we have a stored tab
    var storedTab = localStorage.getItem('aysaActiveTab');
    if (storedTab) {
        switchTab(storedTab);
    } else {
        // Default to General tab
        switchTab('general');
    }
    
    // Add click handlers for tabs
    document.querySelectorAll('.tabs li').forEach(function(tab) {
        tab.addEventListener('click', function() {
            switchTab(this.getAttribute('data-toggle'));
        });
    });
}

/**
 * Switch between tabs
 * @param {string} tabName - The name of the tab to switch to
 */
function switchTab(tabName) {
    // Get all tabs and panels
    var tabs = document.querySelectorAll('.tabs li');
    var panels = document.querySelectorAll('.tab-pane');
    
    // Remove active class from all tabs and hide all panels
    for (var i = 0; i < tabs.length; i++) {
        tabs[i].classList.remove('active');
    }
    
    for (var i = 0; i < panels.length; i++) {
        panels[i].classList.remove('active');
        panels[i].style.display = 'none';
    }
    
    // Add active class to clicked tab
    var activeTab = document.querySelector('.tabs li[data-toggle="' + tabName + '"]');
    if (activeTab) {
        activeTab.classList.add('active');
    }
    
    // Show the corresponding panel
    var activePanel = document.getElementById(tabName);
    if (activePanel) {
        activePanel.classList.add('active');
        activePanel.style.display = 'block';
    }
    
    // Store the active tab in localStorage
    if (typeof(Storage) !== "undefined") {
        localStorage.setItem('aysaActiveTab', tabName);
    }
}

/**
 * Initialize the SEO radar chart
 */
function initRadarChart() {
    // ❌ DISABLED: Metric pills are hidden, no need for click handlers
    // document.querySelectorAll('.metric-pill').forEach(function(pill) { ... });
    
    // ❌ DISABLED: No loading placeholder needed - using new scoring system
    // const loadingTextEl = document.querySelector('.seo-score-box .score-text');
    // if (loadingTextEl) loadingTextEl.innerText = 'Loading';
    // Direct scoring calculation without loading state
    
    // ❌ DISABLED: Using new scoring system from aysa-scoring.js instead
    // calculateAndRenderSeoScores();
}

/**
 * Load data from API
 */
function loadDataFromAPI() {
    // Show loading on accept buttons
    document.querySelectorAll('.btn-accept.save').forEach(button => {
        button.disabled = true;
        button.nextElementSibling.classList.add('is-active');
    });
    
    // Get entity ID and type
    const entityId = getEntityId();
    const entityType = getEntityTypeGood();
    
    if (entityId === 0) {
        console.log('No entity ID found, skipping data load (new entity)');
        // Don't try to load data for new entities
        document.querySelectorAll('.btn-accept.save').forEach(button => {
            button.disabled = false;
            button.nextElementSibling.classList.remove('is-active');
        });
        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);
        
        // Also update global variables if they exist
        if (typeof aysaProjectId !== 'undefined') {
            aysaProjectId = 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);
            
            // Also update global variables if they exist
            if (typeof aysaProjectId !== 'undefined') {
                aysaProjectId = projectId;
            }
        } else {
            console.warn('No project ID found!');
        }
    }
    
    // Update entity ID and type globals if they exist
    if (typeof aysaEntityId !== 'undefined') {
        aysaEntityId = entityId;
    }
    
    if (typeof aysaEntityType !== 'undefined') {
        aysaEntityType = entityType;
    }
    
    console.log('Loading data for', entityType, entityId, 'with project ID', projectId);
    
    // Clear existing values before loading new data
    clearFormValues();
    
    // Make API request
    fetch(`${getAysaApiBaseUrl()}/api/Association/GetAllByAssociatedOnAndIdIntern?associatedOn=${entityType}&idIntern=${entityId}&projectId=${projectId}`, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Origin': window.location.origin
        },
        mode: 'cors'
    })
    .then(response => {
        if (!response.ok) {
            if (response.status === 404) {
                return [];
            }
            throw new Error('API response status: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('Data loaded from API:', data);
        updateFormWithApiData(data);
    })
    .catch(error => {
        console.error('Error loading data from API:', error);
        // Remove tryFallbackDataLoad to prevent automatic keyword generation
        // tryFallbackDataLoad(entityId, entityType);
    })
    .finally(() => {
        // Remove loading state
        document.querySelectorAll('.btn-accept.save').forEach(button => {
            button.disabled = false;
            button.nextElementSibling.classList.remove('is-active');
        });
    });
}

window.loadDataFromAPI = loadDataFromAPI;

/**
 * Try to load data via fallback method if main API call fails
 */
function tryFallbackDataLoad(entityId, entityType) {
    // Try fallback method - get associations by value (name)
    const entityName = document.getElementById('name')?.value || 
                      document.getElementById('title')?.value || '';
    
    if (entityName) {
        console.log('Trying fallback with entity name:', entityName);
        fetch(`${getAysaApiBaseUrl()}/api/Association/associatedValue/${encodeURIComponent(entityName)}`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            mode: 'cors'
        })
        .then(response => response.json())
        .then(data => {
            console.log('Fallback data loaded:', data);
            if (data && data.keyword) {
                // Update keyword fields with fallback data
                const keywordInput = document.getElementById('aysa-entity-keyword');
                if (keywordInput) keywordInput.value = data.keyword;
                
                if (data.secondKeyword) {
                    const secondKeywordInput = document.getElementById('aysa-entity-second-keyword');
                    if (secondKeywordInput) secondKeywordInput.value = data.secondKeyword;
                }
            }
        })
        .catch(fallbackError => {
            console.error('Fallback loading also failed:', fallbackError);
        });
    }
}

/**
 * Clear all form values
 */
function clearFormValues() {
    // Clear keyword fields - these should be updated from API
    const keywordInput = document.getElementById('aysa-entity-keyword');
    if (keywordInput) keywordInput.value = '';
    
    const secondKeywordInput = document.getElementById('aysa-entity-second-keyword');
    if (secondKeywordInput) secondKeywordInput.value = '';
    
    // DO NOT clear meta fields if they already have values
    const metaTitleInput = document.getElementById('aysa-entity-meta-title');
    const metaDescriptionInput = document.getElementById('aysa-entity-meta-description');
    const metaKeywordsInput = document.getElementById('aysa-entity-meta-keywords');
    
    // Only clear if they're empty 
    const metaTitleEmpty = !metaTitleInput || metaTitleInput.value.trim() === '';
    const metaDescriptionEmpty = !metaDescriptionInput || metaDescriptionInput.value.trim() === '';
    const metaKeywordsEmpty = !metaKeywordsInput || metaKeywordsInput.value.trim() === '';
    
    console.log('Retaining existing meta values:', {
        title: !metaTitleEmpty,
        description: !metaDescriptionEmpty,
        keywords: !metaKeywordsEmpty
    });
    
    // Only clear meta fields if they are empty
    if (metaTitleEmpty && metaTitleInput) metaTitleInput.value = '';
    if (metaDescriptionEmpty && metaDescriptionInput) metaDescriptionInput.value = '';
    if (metaKeywordsEmpty && metaKeywordsInput) metaKeywordsInput.value = '';
    
    // Apply the same logic to SEO and advanced settings
    clearSeoSettings(true); // Pass true to indicate preserving existing values
    clearAdvancedSettings(true); // Pass true to indicate preserving existing values
}

/**
 * Clear SEO settings fields
 * @param {boolean} preserveExisting - If true, preserve fields that already have values
 */
function clearSeoSettings(preserveExisting = false) {
    const targetedSeSelect = document.getElementById('targeted_se');
    const targetedCountryInput = document.getElementById('targeted_country');
    const targetedRegionInput = document.getElementById('targeted_region');
    const targetedCityInput = document.getElementById('targeted_city');
    const updateFrequencySelect = document.getElementById('update_frequency');
    const languageOptimizeInput = document.getElementById('language_optimize');
    const deviceOptimizeSelect = document.getElementById('device_optimize');
    
    if (preserveExisting) {
        // Only clear if empty
        if (!targetedSeSelect || targetedSeSelect.value === '') {
            if (targetedSeSelect) targetedSeSelect.value = '';
        }
        
        if (!targetedCountryInput || targetedCountryInput.value.trim() === '') {
            if (targetedCountryInput) targetedCountryInput.value = '';
        }
        
        if (!targetedRegionInput || targetedRegionInput.value.trim() === '') {
            if (targetedRegionInput) targetedRegionInput.value = '';
        }
        
        if (!targetedCityInput || targetedCityInput.value.trim() === '') {
            if (targetedCityInput) targetedCityInput.value = '';
        }
        
        if (!updateFrequencySelect || updateFrequencySelect.value === '') {
            if (updateFrequencySelect) updateFrequencySelect.value = '';
        }
        
        if (!languageOptimizeInput || languageOptimizeInput.value.trim() === '') {
            if (languageOptimizeInput) languageOptimizeInput.value = '';
        }
        
        if (!deviceOptimizeSelect || deviceOptimizeSelect.value === '') {
            if (deviceOptimizeSelect) deviceOptimizeSelect.value = '';
        }
    } else {
        // Clear all fields
        if (targetedSeSelect) targetedSeSelect.value = '';
        if (targetedCountryInput) targetedCountryInput.value = '';
        if (targetedRegionInput) targetedRegionInput.value = '';
        if (targetedCityInput) targetedCityInput.value = '';
        if (updateFrequencySelect) updateFrequencySelect.value = '';
        if (languageOptimizeInput) languageOptimizeInput.value = '';
        if (deviceOptimizeSelect) deviceOptimizeSelect.value = '';
    }
}

/**
 * Clear advanced settings fields
 * @param {boolean} preserveExisting - If true, preserve fields that already have values
 */
function clearAdvancedSettings(preserveExisting = false) {
    const indexCheckbox = document.getElementById('robots_index');
    const noIndexCheckbox = document.getElementById('robots_noindex');
    const noFollowCheckbox = document.getElementById('robots_nofollow');
    const noArchiveCheckbox = document.getElementById('robots_noarchive');
    const noImageIndexCheckbox = document.getElementById('robots_noimageindex');
    const noSnippetCheckbox = document.getElementById('robots_nosnippet');
    const maxSnippetInput = document.getElementById('max_snippet');
    const maxVideoPreviewInput = document.getElementById('max_video_preview');
    const maxImagePreviewSelect = document.getElementById('max_image_preview');
    const canonicalUrlInput = document.getElementById('canonical_url');
    
    if (preserveExisting) {
        // For checkboxes, we'll consider them modified if they're checked (default is unchecked)
        // For inputs, we'll consider them populated if they have non-empty values
        
        // Only reset checkboxes if they're in default state
        if (!indexCheckbox || !indexCheckbox.checked) {
            if (indexCheckbox) indexCheckbox.checked = false;
        }
        
        if (!noIndexCheckbox || !noIndexCheckbox.checked) {
            if (noIndexCheckbox) noIndexCheckbox.checked = false;
        }
        
        if (!noFollowCheckbox || !noFollowCheckbox.checked) {
            if (noFollowCheckbox) noFollowCheckbox.checked = false;
        }
        
        if (!noArchiveCheckbox || !noArchiveCheckbox.checked) {
            if (noArchiveCheckbox) noArchiveCheckbox.checked = false;
        }
        
        if (!noImageIndexCheckbox || !noImageIndexCheckbox.checked) {
            if (noImageIndexCheckbox) noImageIndexCheckbox.checked = false;
        }
        
        if (!noSnippetCheckbox || !noSnippetCheckbox.checked) {
            if (noSnippetCheckbox) noSnippetCheckbox.checked = false;
        }
        
        // Only reset inputs if they're empty
        if (!maxSnippetInput || maxSnippetInput.value.trim() === '') {
            if (maxSnippetInput) maxSnippetInput.value = '';
        }
        
        if (!maxVideoPreviewInput || maxVideoPreviewInput.value.trim() === '') {
            if (maxVideoPreviewInput) maxVideoPreviewInput.value = '';
        }
        
        // Small is the default, so only preserve if it's different
        if (!maxImagePreviewSelect || maxImagePreviewSelect.value === 'small' || maxImagePreviewSelect.value === '') {
            if (maxImagePreviewSelect) maxImagePreviewSelect.value = 'small';
        }
        
        if (!canonicalUrlInput || canonicalUrlInput.value.trim() === '') {
            if (canonicalUrlInput) canonicalUrlInput.value = '';
        }
    } else {
        // Reset all to default
        if (indexCheckbox) indexCheckbox.checked = false;
        if (noIndexCheckbox) noIndexCheckbox.checked = false;
        if (noFollowCheckbox) noFollowCheckbox.checked = false;
        if (noArchiveCheckbox) noArchiveCheckbox.checked = false;
        if (noImageIndexCheckbox) noImageIndexCheckbox.checked = false;
        if (noSnippetCheckbox) noSnippetCheckbox.checked = false;
        if (maxSnippetInput) maxSnippetInput.value = '';
        if (maxVideoPreviewInput) maxVideoPreviewInput.value = '';
        if (maxImagePreviewSelect) maxImagePreviewSelect.value = 'small';
        if (canonicalUrlInput) canonicalUrlInput.value = '';
    }
}

/**
 * Update form with data from API
 */
function updateFormWithApiData(data) {
    // Check if the response is valid
    if (!data) {
        console.log('No data returned from API');
        return;
    }
    
    // Check if the response is an array (multiple associations)
    const associations = Array.isArray(data) ? data : [data];
    
    if (associations.length > 0) {
        console.log('Processing', associations.length, 'associations');
        
        // Actualizăm global cache dacă există
        if (typeof aysaAPIData !== 'undefined') {
            aysaAPIData = associations;
        }
        
        // Find the main association (with isMain=true), or use the first one if none is marked as main
        const mainAssociation = associations.find(a => a.isMain === true) || associations[0];
        console.log('Main association identified:', mainAssociation);
        
        // Update keyword field with the main association's keyword
        if (mainAssociation && mainAssociation.keyword) {
            const keywordInput = document.getElementById('aysa-entity-keyword');
            if (keywordInput) {
                console.log(`Setting main keyword: "${mainAssociation.keyword}" (isMain=${mainAssociation.isMain})`);
                keywordInput.value = mainAssociation.keyword;
            }
        }
        
        // Collect all other keywords from associations (not the main one)
        if (associations.length > 1) {
            const secondaryKeywords = associations
                .filter(assoc => assoc.id !== mainAssociation.id)  // Exclude main association by ID
                .map(assoc => assoc.keyword)
                .filter(keyword => keyword && keyword.trim() !== '');
            
            console.log('Secondary keywords:', secondaryKeywords);
            
            // Update secondary keyword field
            const secondKeywordInput = document.getElementById('aysa-entity-second-keyword');
            if (secondKeywordInput && secondaryKeywords.length > 0) {
                secondKeywordInput.value = secondaryKeywords.join(', ');
                console.log('📥 Populated secondary keywords from API:', secondaryKeywords.join(', '));
            } else if (secondKeywordInput) {
                // Clear field if no secondary keywords from API
                secondKeywordInput.value = '';
                console.log('📥 Cleared secondary keywords field (no secondary keywords in API)');
            }
        }
        
        // Update other metadata fields from API with priority, using main association
        if (mainAssociation) {
            updateMetaFieldsFromAPI(mainAssociation);
            
            // Update SEO settings
            updateSeoSettingsFromAPI(mainAssociation);
            
            // Update advanced settings
            updateAdvancedSettingsFromAPI(mainAssociation);
        }
    }
}

/**
 * Update meta fields with data from association
 * Always prefer API data over PHP rendered values
 */
function updateMetaFieldsFromAPI(association) {
    console.log("Updating meta fields from API:", association);
    
    // Get fields
    const metaTitleInput = document.getElementById('aysa-entity-meta-title');
    const metaDescriptionInput = document.getElementById('aysa-entity-meta-description');
    const metaKeywordsInput = document.getElementById('aysa-entity-meta-keywords');
    
    // Update from API for every field
    if (metaTitleInput) {
        const apiMetaTitle = association.metaTitle;
        if (apiMetaTitle !== null && apiMetaTitle !== undefined && apiMetaTitle !== '') {
            console.log(`Setting meta title from API: "${apiMetaTitle}"`);
            metaTitleInput.value = apiMetaTitle;
        } else {
            console.log("API returned empty meta title - keeping existing or default value");
        }
    }
    
    if (metaDescriptionInput) {
        const apiMetaDescription = association.metaDescription;
        if (apiMetaDescription !== null && apiMetaDescription !== undefined && apiMetaDescription !== '') {
            console.log(`Setting meta description from API: "${apiMetaDescription}"`);
            metaDescriptionInput.value = apiMetaDescription;
        } else {
            console.log("API returned empty meta description - keeping existing or default value");
        }
    }
    
    if (metaKeywordsInput) {
        const apiMetaKeywords = association.metaKeywords;
        if (apiMetaKeywords !== null && apiMetaKeywords !== undefined && apiMetaKeywords !== '') {
            console.log(`Setting meta keywords from API: "${apiMetaKeywords}"`);
            
            // Format the keywords with spaces after commas
            const formattedKeywords = apiMetaKeywords.split(',')
                .map(keyword => keyword.trim())
                .filter(keyword => keyword !== '')
                .join(', ');
                
            metaKeywordsInput.value = formattedKeywords;
        } else {
            console.log("API returned empty meta keywords - keeping existing or default value");
        }
    }
}

/**
 * Update SEO settings with data from association
 * Always prefer API data
 */
function updateSeoSettingsFromAPI(association) {
    // Get all SEO settings elements
    const targetedSeSelect = document.getElementById('targeted_se');
    const targetedCountryInput = document.getElementById('targeted_country');
    const targetedRegionInput = document.getElementById('targeted_region');
    const targetedCityInput = document.getElementById('targeted_city');
    const updateFrequencySelect = document.getElementById('update_frequency');
    const languageOptimizeInput = document.getElementById('language_optimize');
    const deviceOptimizeSelect = document.getElementById('device_optimize');
    
    // Update all fields that have API values
    if (targetedSeSelect && association.targetedSearchEngine) {
        // Ensure value is lowercase to match the select options (google, bing, yahoo)
        const searchEngine = association.targetedSearchEngine.toLowerCase();
        targetedSeSelect.value = searchEngine;
        console.log(`Setting targeted search engine to: ${searchEngine} from API value: ${association.targetedSearchEngine}`);
    }
    
    if (targetedCountryInput && association.targetedCountry) {
        targetedCountryInput.value = association.targetedCountry;
    }
    
    if (targetedRegionInput && association.targetedRegion) {
        targetedRegionInput.value = association.targetedRegion;
    }
    
    if (targetedCityInput && association.targetedCity) {
        targetedCityInput.value = association.targetedCity;
    }
    
    if (updateFrequencySelect && association.updateFrequency) {
        updateFrequencySelect.value = association.updateFrequency;
    }
    
    if (languageOptimizeInput && association.languageOptimize) {
        languageOptimizeInput.value = association.languageOptimize;
    }
    
    if (deviceOptimizeSelect && association.deviceOptimize) {
        deviceOptimizeSelect.value = association.deviceOptimize;
    }
}

/**
 * Update advanced settings with data from association
 * Always prefer API data
 */
function updateAdvancedSettingsFromAPI(association) {
    // Get all advanced settings elements
    const indexCheckbox = document.getElementById('robots_index');
    const noFollowCheckbox = document.getElementById('robots_nofollow');
    const noArchiveCheckbox = document.getElementById('robots_noarchive');
    const noImageIndexCheckbox = document.getElementById('robots_noimageindex');
    const noSnippetCheckbox = document.getElementById('robots_nosnippet');
    const maxSnippetInput = document.getElementById('max_snippet');
    const maxVideoPreviewInput = document.getElementById('max_video_preview');
    const maxImagePreviewSelect = document.getElementById('max_image_preview');
    const canonicalUrlInput = document.getElementById('canonical_url');
    
    // Update all fields that have API values
    if (indexCheckbox && association.index !== undefined) {
        indexCheckbox.checked = association.index;
    }
    
    if (noFollowCheckbox && association.noFollow !== undefined) {
        noFollowCheckbox.checked = association.noFollow;
    }
    
    if (noArchiveCheckbox && association.noArchive !== undefined) {
        noArchiveCheckbox.checked = association.noArchive;
    }
    
    if (noImageIndexCheckbox && association.noImageIndex !== undefined) {
        noImageIndexCheckbox.checked = association.noImageIndex;
    }
    
    if (noSnippetCheckbox && association.noSnippet !== undefined) {
        noSnippetCheckbox.checked = association.noSnippet;
    }
    
    if (maxSnippetInput && association.maxSnippet !== undefined) {
        maxSnippetInput.value = association.maxSnippet;
    }
    
    if (maxVideoPreviewInput && association.maxVideoPreview !== undefined) {
        maxVideoPreviewInput.value = association.maxVideoPreview;
    }
    
    if (maxImagePreviewSelect && association.maxImagePreview) {
        maxImagePreviewSelect.value = association.maxImagePreview;
    }
    
    if (canonicalUrlInput && association.canonicalUrl) {
        canonicalUrlInput.value = association.canonicalUrl;
    }
}

/**
 * Bind all event listeners
 */
function bindEventListeners() {
    // Clear any existing errors first
    if (typeof clearExistingErrors === 'function') {
        clearExistingErrors();
    }
    
    // Generate Suggestions button - only add listener if actions.js hasn't already
    const generateSuggestionsBtn = document.getElementById('generate-suggestions-btn');
    if (generateSuggestionsBtn && !generateSuggestionsBtn._hasAysaActionsListener) {
        generateSuggestionsBtn.addEventListener('click', handleGenerateSuggestions);
        generateSuggestionsBtn._hasMetaboxListener = true;
        console.log('Added metabox event listener to Generate Suggestions button');
    } else if (generateSuggestionsBtn && generateSuggestionsBtn._hasAysaActionsListener) {
        console.log('Generate Suggestions button already has actions listener, skipping metabox listener');
    }
    
    // Meta fields Revert button
    const revertMetaBtn = document.getElementById('reject-meta-fields');
    if (revertMetaBtn) {
        revertMetaBtn.textContent = 'Revert';
        revertMetaBtn.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Show spinner
            const spinner = this.nextElementSibling;
            if (spinner) spinner.classList.add('is-active');
            
            // Disable buttons temporarily
            this.disabled = true;
            
            // First, try to restore from pre-generation values
            let restoredFromPreGeneration = false;
            
            if (preGenerationMetaValues.title || preGenerationMetaValues.description || preGenerationMetaValues.keywords) {
                console.log('Restoring meta fields from pre-generation values');
                
                const metaTitleInput = document.getElementById('aysa-entity-meta-title');
                const metaDescriptionInput = document.getElementById('aysa-entity-meta-description');
                const metaKeywordsInput = document.getElementById('aysa-entity-meta-keywords');
                
                if (metaTitleInput && preGenerationMetaValues.title !== undefined) {
                    metaTitleInput.value = preGenerationMetaValues.title;
                    restoredFromPreGeneration = true;
                }
                
                if (metaDescriptionInput && preGenerationMetaValues.description !== undefined) {
                    metaDescriptionInput.value = preGenerationMetaValues.description;
                    restoredFromPreGeneration = true;
                }
                
                if (metaKeywordsInput && preGenerationMetaValues.keywords !== undefined) {
                    metaKeywordsInput.value = preGenerationMetaValues.keywords;
                    restoredFromPreGeneration = true;
                }
                
                if (restoredFromPreGeneration) {
                    console.log('Successfully restored meta fields from pre-generation values');
                    
                    // Show success message
                    if (typeof showToast === 'function') {
                        showToast('Meta fields restored to pre-generation values', 'info');
                    }
                    
                    // Re-enable buttons and hide spinner
                    this.disabled = false;
                    if (spinner) spinner.classList.remove('is-active');
                    return;
                }
            }
            
            // If no pre-generation values available, fall back to original values
            let restoredFromOriginal = false;
            if (originalMetaValues.title || originalMetaValues.description || originalMetaValues.keywords) {
                const metaTitleInput = document.getElementById('aysa-entity-meta-title');
                const metaDescriptionInput = document.getElementById('aysa-entity-meta-description');
                const metaKeywordsInput = document.getElementById('aysa-entity-meta-keywords');
                
                if (metaTitleInput && originalMetaValues.title) {
                    metaTitleInput.value = originalMetaValues.title;
                    restoredFromOriginal = true;
                }
                
                if (metaDescriptionInput && originalMetaValues.description) {
                    metaDescriptionInput.value = originalMetaValues.description;
                    restoredFromOriginal = true;
                }
                
                if (metaKeywordsInput && originalMetaValues.keywords) {
                    metaKeywordsInput.value = originalMetaValues.keywords;
                    restoredFromOriginal = true;
                }
                
                if (restoredFromOriginal) {
                    console.log('Restored meta fields from original values');
                    
                    // Show success message
                    if (typeof showToast === 'function') {
                        showToast('Meta fields restored to original values', 'info');
                    }
                    
                    // Re-enable buttons and hide spinner
                    this.disabled = false;
                    if (spinner) spinner.classList.remove('is-active');
                    return;
                }
            }
            
            // If no original values, try loading from API
            if (!restoredFromOriginal && !restoredFromPreGeneration) {
                // Attempt to reload data from API
                loadDataFromAPI();
                
                // Show message
                if (typeof showToast === 'function') {
                    showToast('Meta changes reverted and reset', 'info');
                }
                
                // Re-enable buttons and hide spinner after a short delay
                setTimeout(() => {
                    this.disabled = false;
                    if (spinner) spinner.classList.remove('is-active');
                }, 1000);
            }
        });
        console.log('Added event listener to Revert Meta Changes button');
    }
    
    // Find the WordPress category description field
    let descriptionField = document.getElementById('description');
    let wordpressForm = false;
    
    // For TinyMCE editors, check for the wrapper
    if (!descriptionField) {
        descriptionField = document.querySelector('.wp-editor-area[name="description"]');
    }
    
    console.log('Looking for WordPress description field:', !!descriptionField);
    
    // Also check for term edit form
    const edittagForm = document.getElementById('edittag');
    if (edittagForm) {
        wordpressForm = true;
        console.log('Found WordPress term edit form');
    }
    
    // Try additional selectors for description field and wrap
    let descriptionWrap = document.querySelector('.term-description-wrap');
    if (!descriptionWrap) {
        descriptionWrap = document.querySelector('.form-field.term-description-wrap');
    }
    
    // Find the description explanation paragraph - this is what we want to insert after
    let descriptionExplanation = document.querySelector('#description-description');
    
    console.log('Description wrap found:', !!descriptionWrap, 'Description explanation found:', !!descriptionExplanation);
    
    // Only proceed if we found the description field or we're on a term edit form
    if (descriptionField || wordpressForm) {
        console.log('Found WordPress term editing context, adding revert buttons');
        
        // Find the name field and slug field
        const nameField = document.getElementById('name');
        const slugField = document.getElementById('slug');
        
        console.log('Found name field:', !!nameField, 'Found slug field:', !!slugField, 'Found description wrap:', !!descriptionWrap);
        
        // If we're on a form with name and slug but no description, use that
        if (!descriptionField && (nameField || slugField)) {
            if (nameField) {
                descriptionField = nameField;
                console.log('Using name field as reference for button placement');
            } else if (slugField) {
                descriptionField = slugField;
                console.log('Using slug field as reference for button placement');
            }
        }
        
        // If we still don't have a reference element, try to find the submit button
        if (!descriptionField) {
            const submitBtn = document.querySelector('input[type="submit"], #submit');
            if (submitBtn) {
                descriptionField = submitBtn;
                console.log('Using submit button as reference for button placement');
            }
        }
        
        // Store original values if fields exist
        const originalValues = {
            name: nameField ? nameField.value : '',
            slug: slugField ? slugField.value : '',
            description: descriptionField ? descriptionField.value : ''
        };
        
        // Check if buttons already exist
        const existingButtons = document.getElementById('reject-category-fields');
        if (existingButtons) {
            console.log('Buttons already exist, not adding again');
            return;
        }
        
        // Create buttons for description - try different approaches to find a good insertion point
        if (descriptionField) {
            // Create the buttons HTML
            const descriptionButtonsHtml = `
                <div class="accept-btn-container description-field-buttons" style="text-align: right; margin-top: 15px; margin-bottom: 15px; clear: both;">
                    <button class="aysa-button aysa-button-action" id="reject-description-field">Revert</button>
                    <span class="spinner"></span>
                </div>
            `;
            
            // Try different insertion methods based on what we found
            let inserted = false;
            
            // Method 1: Insert after description explanation paragraph
            if (descriptionExplanation) {
                console.log('Adding description buttons after description explanation paragraph');
                descriptionExplanation.insertAdjacentHTML('afterend', descriptionButtonsHtml);
                inserted = true;
            }
            // Method 2: If the explanation paragraph doesn't exist, try the description wrap
            else if (descriptionWrap) {
                console.log('Adding description buttons after description wrap');
                descriptionWrap.insertAdjacentHTML('afterend', descriptionButtonsHtml);
                inserted = true;
            }
            // Method 3: If still not inserted, try inserting inside the TD of the description row
            else if (document.querySelector('.term-description-wrap td')) {
                const tdElement = document.querySelector('.term-description-wrap td');
                console.log('Adding description buttons at the end of description cell');
                tdElement.insertAdjacentHTML('beforeend', descriptionButtonsHtml);
                inserted = true;
            }
            // Method 4: Insert after description field itself as a last resort
            else if (descriptionField) {
                console.log('Adding description buttons after description field directly');
                
                // Try to find the parent container first
                const descriptionParent = descriptionField.closest('.form-field') || 
                                          descriptionField.closest('tr') || 
                                          descriptionField.parentNode;
                
                if (descriptionParent) {
                    console.log('Inserting after description parent');
                    descriptionParent.insertAdjacentHTML('afterend', descriptionButtonsHtml);
                    inserted = true;
                } else {
                    console.log('Inserting after description field');
                    descriptionField.insertAdjacentHTML('afterend', descriptionButtonsHtml);
                    inserted = true;
                }
            }
            
            console.log('Description buttons inserted:', inserted);
            
            // Add event listeners for the description buttons
            if (inserted) {
                const revertDescBtn = document.getElementById('reject-description-field');
                
                if (revertDescBtn) {
                    revertDescBtn.addEventListener('click', function(e) {
                        e.preventDefault();
                        
                        // Show spinner
                        const spinner = this.nextElementSibling;
                        if (spinner) spinner.classList.add('is-active');
                        
                        // Disable buttons temporarily
                        this.disabled = true;
                        
                        // First try to use the original description value that was stored on page load
                        if (typeof originalValues !== 'undefined' && originalValues.description) {
                            // Restore description value
                            if (descriptionField) {
                                descriptionField.value = originalValues.description;
                                
                                // If TinyMCE is active
                                if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
                                    tinyMCE.get('description').setContent(originalValues.description, {format: 'raw'});
                                }
                            }
                            
                            // Show success message
                            if (typeof showToast === 'function') {
                                showToast('Description restored to original', 'info');
                            }
                            
                            // Re-enable buttons and hide spinner
                            this.disabled = false;
                            if (spinner) spinner.classList.remove('is-active');
                            return;
                        }
                        
                        // If no stored values, get the term ID
                        const termId = getEntityId();
                        
                        if (termId) {
                            // Try to determine the taxonomy from the URL
                            let taxonomy = 'product_cat'; // Default taxonomy
                            const urlParams = new URLSearchParams(window.location.search);
                            if (urlParams.has('taxonomy')) {
                                taxonomy = urlParams.get('taxonomy');
                            }
                            
                            console.log('Fetching term description via AJAX for term ID:', termId, 'taxonomy:', taxonomy);
                            
                            // Build the request body
                            const requestBody = new URLSearchParams();
                            requestBody.append('action', 'aysa_get_term_data');
                            requestBody.append('term_id', termId);
                            requestBody.append('nonce', aysaParams.nonce);
                            requestBody.append('taxonomy', taxonomy);
                            
                            fetch(aysaParams.ajax_url, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded',
                                },
                                body: requestBody
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    // Restore description value
                                    if (descriptionField && data.description) {
                                        descriptionField.value = data.description;
                                        
                                        // If TinyMCE is active
                                        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
                                            tinyMCE.get('description').setContent(data.description, {format: 'raw'});
                                        }
                                    }
                                    
                                    // Show success message
                                    if (typeof showToast === 'function') {
                                        showToast('Description reset to original', 'info');
                                    }
                                } else {
                                    // Show error message
                                    if (typeof showToast === 'function') {
                                        showToast('Failed to reset description', 'error');
                                    }
                                }
                            })
                            .catch(error => {
                                console.error('Error fetching original description data:', error);
                                // Show error message
                                if (typeof showToast === 'function') {
                                    showToast('Failed to reset description', 'error');
                                }
                            })
                            .finally(() => {
                                // Re-enable buttons and hide spinner
                                this.disabled = false;
                                if (spinner) spinner.classList.remove('is-active');
                            });
                        } else {
                            // Show message
                            if (typeof showToast === 'function') {
                                showToast('No category ID found', 'error');
                            }
                            
                            // Re-enable buttons and hide spinner
                            this.disabled = false;
                            if (spinner) spinner.classList.remove('is-active');
                        }
                    });
                    console.log('Added event listener to Revert Description button');
                }
            }
        }
        
        // Add Revert buttons for name/slug fields
        const buttonsHtml = `
            <div class="accept-btn-container native-fields-buttons" style="text-align: right; margin-top: 15px; margin-bottom: 15px; clear: both;">
                <button class="aysa-button aysa-button-action" id="reject-category-fields">Revert</button>
                <span class="spinner"></span>
            </div>
        `;
        
        // Decide where to insert the buttons
        let targetElement = null;
        
        // First, try to find the slug field wrapper
        targetElement = document.querySelector('.form-field.term-slug-wrap');
        
        // If that doesn't exist, try to find the submit button wrapper
        if (!targetElement) {
            targetElement = document.querySelector('.submit');
        }
        
        // If we have a target, insert before it
        if (targetElement) {
            console.log('Adding name/slug buttons after slug field');
            targetElement.insertAdjacentHTML('afterend', buttonsHtml);
        } 
        // Otherwise, try to use our reference element
        else if (nameField || slugField) {
            // Find the best parent container
            const parentElement = nameField ? 
                (nameField.closest('.form-field') || nameField.closest('.form-table') || nameField.closest('tr') || nameField.parentNode) :
                (slugField.closest('.form-field') || slugField.closest('.form-table') || slugField.closest('tr') || slugField.parentNode);
            
            if (parentElement) {
                console.log('Adding name/slug buttons after parent element');
                parentElement.insertAdjacentHTML('afterend', buttonsHtml);
            } else {
                console.log('Adding name/slug buttons directly after reference field');
                if (nameField) {
                    nameField.insertAdjacentHTML('afterend', buttonsHtml);
                } else {
                    slugField.insertAdjacentHTML('afterend', buttonsHtml);
                }
            }
        } 
        // Last resort, add at the end of the form
        else if (edittagForm) {
            console.log('Adding name/slug buttons at the end of the form');
            edittagForm.insertAdjacentHTML('beforeend', buttonsHtml);
        } else {
            console.log('No suitable location found for name/slug buttons');
            return;
        }
        
        // Add event listeners to the new buttons
        const revertCategoryBtn = document.getElementById('reject-category-fields');
        
        if (revertCategoryBtn) {
            revertCategoryBtn.addEventListener('click', function(e) {
                e.preventDefault();
                
                // Show spinner
                const spinner = this.nextElementSibling;
                if (spinner) spinner.classList.add('is-active');
                
                // Disable buttons temporarily
                this.disabled = true;
                
                // First try to use the original values that were stored on page load
                if (typeof originalValues !== 'undefined') {
                    // Restore values
                    if (nameField && originalValues.name) nameField.value = originalValues.name;
                    if (slugField && originalValues.slug) slugField.value = originalValues.slug;
                    
                    // Show success message
                    if (typeof showToast === 'function') {
                        showToast('Name and slug restored to original', 'info');
                    }
                    
                    // Re-enable buttons and hide spinner
                    this.disabled = false;
                    if (spinner) spinner.classList.remove('is-active');
                    return;
                }
                
                // If no stored values, get the term ID
                const termId = getEntityId();
                
                if (termId) {
                    // Try to determine the taxonomy from the URL
                    let taxonomy = 'product_cat'; // Default taxonomy
                    const urlParams = new URLSearchParams(window.location.search);
                    if (urlParams.has('taxonomy')) {
                        taxonomy = urlParams.get('taxonomy');
                    }
                    
                    console.log('Fetching term data via AJAX for term ID:', termId, 'taxonomy:', taxonomy);
                    
                    // Build the request body
                    const requestBody = new URLSearchParams();
                    requestBody.append('action', 'aysa_get_term_data');
                    requestBody.append('term_id', termId);
                    requestBody.append('nonce', aysaParams.nonce);
                    requestBody.append('taxonomy', taxonomy);
                    
                    fetch(aysaParams.ajax_url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: requestBody
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Restore values
                            if (nameField && data.name) nameField.value = data.name;
                            if (slugField && data.slug) slugField.value = data.slug;
                            
                            // Show success message
                            if (typeof showToast === 'function') {
                                showToast('Name and slug reset to original', 'info');
                            }
                        } else {
                            // Show error message
                            if (typeof showToast === 'function') {
                                showToast('Failed to reset name and slug', 'error');
                            }
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching original category data:', error);
                        // Show error message
                        if (typeof showToast === 'function') {
                            showToast('Failed to reset name and slug', 'error');
                        }
                    })
                    .finally(() => {
                        // Re-enable buttons and hide spinner
                        this.disabled = false;
                        if (spinner) spinner.classList.remove('is-active');
                    });
                } else {
                    // Show message
                    if (typeof showToast === 'function') {
                        showToast('No category ID found', 'error');
                    }
                    
                    // Re-enable buttons and hide spinner
                    this.disabled = false;
                    if (spinner) spinner.classList.remove('is-active');
                }
            });
            console.log('Added event listener to Revert Name/Slug button');
        }
    }
}

/**
 * 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'));
    } 
    // Check for post ID
    else if (urlParams.get('post')) {
        entityId = parseInt(urlParams.get('post'));
    }
    
    // Try to get from global aysaParams if available
    if (entityId === 0 && typeof aysaParams !== 'undefined') {
        if (aysaParams.postId) {
            entityId = parseInt(aysaParams.postId);
        } else if (aysaParams.termId) {
            entityId = parseInt(aysaParams.termId);
        }
    }
    
    console.log('Detected entity ID:', entityId);
    return entityId;
}

/**
 * Get the entity type for API calls
 * @returns {string} Entity type (Category, Product, Page, etc.)
 */
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';
    } else if ((url.includes('post.php?post=') && url.includes('&action=edit')) ||
               url.includes('post-new.php') ||
               aysaEntityType === 'post') {
        // Check if it's a regular post (not product or page)
        const isRegularPost = !url.includes('post_type=') || 
                             url.includes('post_type=post') ||
                             (document.getElementById('post_type') && document.getElementById('post_type').value === 'post');
        
        if (isRegularPost && aysaEntityType !== 'page') {
            entityType = 'Post';
        }
    }
    
    console.log('🚀 DEBUG getEntityType - Final detected entity type:', entityType);
    return entityType;
}

/**
 * Load SEO Settings from API and populate the SEO settings tab
 * This fetches the global SEO settings for the project and applies them to the metabox
 */
function loadSeoSettingsFromAPI() {
    // Get project ID from WordPress params or localStorage
    let projectId = 0;
    if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
        projectId = parseInt(aysaParams.project_id);
    } else {
        // Fallback to localStorage if needed
        const storedProjectId = localStorage.getItem('aysa_project_id');
        if (storedProjectId) {
            projectId = parseInt(storedProjectId);
        }
    }
    
    if (!projectId) {
        console.warn('No project ID found, cannot fetch SEO settings');
        return;
    }
    
    console.log('Fetching SEO settings for project ID:', projectId);
    
    // Fetch SEO settings from API
    fetch(`${getAysaApiBaseUrl()}/api/SeoSettings/ByProject/${projectId}`, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Origin': window.location.origin
        },
        mode: 'cors'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('API response status: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('SEO Settings loaded from API:', data);
        
        if (data && data.id) {
            // Apply SEO settings to form fields
            applySeoSettingsToForm(data);
        }
    })
    .catch(error => {
        console.error('Error loading SEO settings from API:', error);
    });
}

/**
 * Apply SEO settings from API to form fields
 * @param {Object} data - SEO settings data from API
 */
function applySeoSettingsToForm(data) {
    // Get SEO settings elements
    const targetedSeSelect = document.getElementById('targeted_se');
    const targetedCountryInput = document.getElementById('targeted_country');
    const targetedRegionInput = document.getElementById('targeted_region');
    const targetedCityInput = document.getElementById('targeted_city');
    const updateFrequencySelect = document.getElementById('update_frequency');
    const languageOptimizeInput = document.getElementById('language_optimize');
    const deviceOptimizeSelect = document.getElementById('device_optimize');
    
    // Apply values to form fields if they don't already have values
    if (targetedSeSelect && !targetedSeSelect.value && data.targetedSearchEngine) {
        // Ensure value is lowercase to match the select options (google, bing, yahoo)
        const searchEngine = data.targetedSearchEngine.toLowerCase();
        targetedSeSelect.value = searchEngine;
        console.log(`Setting targeted search engine to: ${searchEngine} from API value: ${data.targetedSearchEngine}`);
    }
    
    if (targetedCountryInput && !targetedCountryInput.value && data.targetedCountry) {
        targetedCountryInput.value = data.targetedCountry;
    }
    
    if (targetedRegionInput && !targetedRegionInput.value && data.targetedRegion) {
        targetedRegionInput.value = data.targetedRegion;
    }
    
    if (targetedCityInput && !targetedCityInput.value && data.targetedCity) {
        targetedCityInput.value = data.targetedCity;
    }
    
    // Apply the new fields
    if (updateFrequencySelect && !updateFrequencySelect.value && data.updateFrequency) {
        updateFrequencySelect.value = data.updateFrequency;
    }
    
    if (languageOptimizeInput && !languageOptimizeInput.value && data.languageOptimize) {
        languageOptimizeInput.value = data.languageOptimize;
    }
    
    if (deviceOptimizeSelect && !deviceOptimizeSelect.value && data.deviceOptimize) {
        deviceOptimizeSelect.value = data.deviceOptimize;
    }
}

// Modify loadDataFromAPI to also load SEO settings
const originalLoadDataFromAPI = loadDataFromAPI;
loadDataFromAPI = function() {
    // Call the original function
    originalLoadDataFromAPI();
    
    // Also load SEO settings
    loadSeoSettingsFromAPI();
};

/**
 * Initialize keyword functionality
 */
function initKeywordManagement() {
    // Call the main implementation from aysa-keywords.js if available
    if (typeof window.initKeywordManagement === 'function' && window.initKeywordManagement !== initKeywordManagement) {
        console.log('🔥 initKeywordManagement: Calling implementation from aysa-keywords.js');
        window.initKeywordManagement();
    } else {
        console.log('🔥 initKeywordManagement: Using local implementation');
        // Fallback implementation for when aysa-keywords.js is not loaded
        setupSecondaryKeywordsTags();
    }
}

/**
 * Fallback function to set up secondary keywords tags
 */
function setupSecondaryKeywordsTags() {
    const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
    const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
    
    if (!secondaryKeywordsContainer || !secondaryKeywordInput) {
        console.log('🔥 setupSecondaryKeywordsTags: Required elements not found');
        return;
    }
    
    console.log('🔥 setupSecondaryKeywordsTags: Setting up fallback implementation');
    
    // Render existing keywords as tags
    renderFallbackSecondaryKeywordTags();
    
    // Listen for changes to the input field
    secondaryKeywordInput.addEventListener('input', renderFallbackSecondaryKeywordTags);
}

/**
 * Fallback function to render secondary keyword tags
 */
function renderFallbackSecondaryKeywordTags() {
    const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
    const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
    
    if (!secondaryKeywordsContainer || !secondaryKeywordInput) return;
    
    // Clear container
    secondaryKeywordsContainer.innerHTML = '';
    
    // Get keywords from input
    const keywordsValue = secondaryKeywordInput.value.trim();
    if (!keywordsValue) return;
    
    // Split and create tags
    const keywords = keywordsValue.split(',').map(k => k.trim()).filter(k => k !== '');
    
    keywords.forEach(keyword => {
        const tag = document.createElement('div');
        tag.className = 'keyword-tag';
        tag.innerHTML = `
            <span class="tag-text">${keyword}</span>
            <span class="tag-remove">×</span>
        `;
        
        // Add remove functionality
        tag.querySelector('.tag-remove').addEventListener('click', function(e) {
            e.stopPropagation();
            const currentKeywords = secondaryKeywordInput.value.split(',').map(k => k.trim()).filter(k => k !== keyword);
            secondaryKeywordInput.value = currentKeywords.join(', ');
            renderFallbackSecondaryKeywordTags();
        });
        
        secondaryKeywordsContainer.appendChild(tag);
    });
    
    console.log('🔥 renderFallbackSecondaryKeywordTags: Created', keywords.length, 'tags');
}

/**
 * Show a toast notification
 * @param {string} message - The message to display
 * @param {string} type - The type of notification (success, error, warning, info)
 */
function showToast(message, type = 'info') {
    // Check if the WordPress admin notices container exists
    let noticesContainer = document.querySelector('.wrap .notice, .wrap .updated, .wrap .error');
    
    // If no notices container exists, find the main .wrap and insert the notices container at the top
    if (!noticesContainer) {
        const wrap = document.querySelector('.wrap');
        if (wrap) {
            const noticesDiv = document.createElement('div');
            noticesDiv.className = 'aysa-notices-container';
            wrap.insertBefore(noticesDiv, wrap.firstChild);
            noticesContainer = noticesDiv;
        } else {
            // If no wrap, try to find the form
            const form = document.querySelector('form#addtag, form#edittag, form#post');
            if (form) {
                const noticesDiv = document.createElement('div');
                noticesDiv.className = 'aysa-notices-container';
                form.insertBefore(noticesDiv, form.firstChild);
                noticesContainer = noticesDiv;
            }
        }
    }
    
    // If we found or created a notices container
    if (noticesContainer) {
        // Create the notice element
        const notice = document.createElement('div');
        
        // Set appropriate class based on type
        let noticeClass = 'notice ';
        switch (type) {
            case 'success':
                noticeClass += 'notice-success';
                break;
            case 'error':
                noticeClass += 'notice-error';
                break;
            case 'warning':
                noticeClass += 'notice-warning';
                break;
            default:
                noticeClass += 'notice-info';
        }
        
        notice.className = noticeClass + ' is-dismissible';
        
        // Add message
        const paragraph = document.createElement('p');
        paragraph.textContent = message;
        notice.appendChild(paragraph);
        
        // Add dismiss button
        const dismissButton = document.createElement('button');
        dismissButton.type = 'button';
        dismissButton.className = 'notice-dismiss';
        dismissButton.innerHTML = '<span class="screen-reader-text">Dismiss this notice.</span>';
        dismissButton.addEventListener('click', function() {
            notice.remove();
        });
        notice.appendChild(dismissButton);
        
        // Add to notices container
        noticesContainer.appendChild(notice);
        
        // Auto remove after 5 seconds
        setTimeout(() => {
            if (notice.parentNode) {
                notice.remove();
            }
        }, 5000);
    } else {
        // Fallback to console if we can't show a notice
        console.log(`${type.toUpperCase()}: ${message}`);
        
        // If it's an error, also show an alert
        if (type === 'error') {
            alert(message);
        }
    }
}

function initKeywordValidationPanel() {
    const keywordInput = document.getElementById('aysa-entity-keyword');
    if (!keywordInput || document.getElementById('aysa-keyword-validation-panel')) {
        return;
    }

    const panel = document.createElement('div');
    panel.id = 'aysa-keyword-validation-panel';
    panel.style.marginTop = '10px';
    panel.style.padding = '12px';
    panel.style.border = '1px solid #dcdcde';
    panel.style.borderRadius = '6px';
    panel.style.background = '#fff';
    panel.innerHTML = `
        <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;">
            <div>
                <strong>Keyword Validation</strong>
                <div id="aysa-keyword-validation-status" style="font-size:12px;color:#646970;margin-top:4px;">Validate current page keyword through AYSA worker.</div>
            </div>
            <button type="button" class="button button-secondary" id="aysa-keyword-validation-btn">Validate Keyword</button>
        </div>
        <div id="aysa-keyword-validation-result" style="display:none;margin-top:12px;font-size:13px;line-height:1.5;"></div>
    `;

    const mountPoint = keywordInput.closest('.form-field, .options_group, tr, .inside, .aysa-field-wrapper') || keywordInput.parentElement;
    mountPoint.appendChild(panel);

    const button = document.getElementById('aysa-keyword-validation-btn');
    if (button) {
        button.addEventListener('click', startKeywordValidationRun);
    }
}

function startKeywordValidationRun() {
    if (typeof aysaParams === 'undefined' || !aysaParams.ajax_url || !aysaParams.nonce) {
        showToast('AYSA config missing for keyword validation.', 'error');
        return;
    }

    const button = document.getElementById('aysa-keyword-validation-btn');
    const statusEl = document.getElementById('aysa-keyword-validation-status');
    const resultEl = document.getElementById('aysa-keyword-validation-result');
    if (button) {
        button.disabled = true;
        button.textContent = 'Starting...';
    }
    if (resultEl) {
        resultEl.style.display = 'none';
        resultEl.innerHTML = '';
    }
    if (statusEl) {
        statusEl.textContent = 'Submitting validation run...';
    }

    const payload = buildKeywordValidationRequestPayload();
    const body = new URLSearchParams();
    body.set('action', 'aysa_start_keyword_validation');
    body.set('nonce', aysaParams.nonce);
    body.set('project_id', String(aysaParams.project_id || 0));
    body.set('entity_id', String(payload.entity_id || 0));
    body.set('entity_type', payload.entity_type || '');
    body.set('taxonomy', payload.taxonomy || '');
    body.set('title', payload.title || '');
    body.set('meta_description', payload.meta_description || '');
    body.set('page_text', payload.page_text || '');
    body.set('url', payload.url || '');
    body.set('existing_keyword', payload.existing_keyword || '');
    body.set('language', payload.language || '');
    body.set('country_code', payload.country_code || '');

    fetch(aysaParams.ajax_url, {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
        body: body.toString()
    })
        .then((response) => response.json())
        .then((data) => {
            if (!data || !data.success || !data.data || !data.data.run_id) {
                throw new Error((data && data.data && data.data.message) || 'Failed to start keyword validation.');
            }
            aysaKeywordValidationState.runId = parseInt(data.data.run_id, 10) || 0;
            if (statusEl) {
                statusEl.textContent = 'Validation run started. Waiting for worker...';
            }
            pollKeywordValidationStatus();
        })
        .catch((error) => {
            if (button) {
                button.disabled = false;
                button.textContent = 'Validate Keyword';
            }
            if (statusEl) {
                statusEl.textContent = 'Validation failed to start.';
            }
            showToast(error.message || 'Failed to start keyword validation.', 'error');
        });
}

function pollKeywordValidationStatus() {
    if (!aysaKeywordValidationState.runId || typeof aysaParams === 'undefined') {
        return;
    }

    const button = document.getElementById('aysa-keyword-validation-btn');
    const statusEl = document.getElementById('aysa-keyword-validation-status');

    const body = new URLSearchParams();
    body.set('action', 'aysa_keyword_validation_status');
    body.set('nonce', aysaParams.nonce);
    body.set('project_id', String(aysaParams.project_id || 0));
    body.set('run_id', String(aysaKeywordValidationState.runId));

    fetch(aysaParams.ajax_url, {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
        body: body.toString()
    })
        .then((response) => response.json())
        .then((data) => {
            if (!data || !data.success) {
                throw new Error((data && data.data && data.data.message) || 'Failed to fetch keyword validation status.');
            }
            const run = data.data && data.data.run ? data.data.run : {};
            const validation = data.data && data.data.validation ? data.data.validation : {};
            const status = String(run.status || '').toLowerCase();

            if (statusEl) {
                statusEl.textContent = status === 'completed'
                    ? (validation.status_label || 'Validation completed.')
                    : `Validation ${status || 'running'}...`;
            }

            if (status === 'completed' || status === 'failed' || status === 'blocked') {
                if (button) {
                    button.disabled = false;
                    button.textContent = 'Validate Keyword';
                }
                renderKeywordValidationResult(validation, run);
                return;
            }

            if (button) {
                button.textContent = 'Validating...';
            }
            window.clearTimeout(aysaKeywordValidationState.pollTimer);
            aysaKeywordValidationState.pollTimer = window.setTimeout(pollKeywordValidationStatus, 2500);
        })
        .catch((error) => {
            if (button) {
                button.disabled = false;
                button.textContent = 'Validate Keyword';
            }
            if (statusEl) {
                statusEl.textContent = 'Validation status unavailable.';
            }
            showToast(error.message || 'Failed to fetch keyword validation status.', 'error');
        });
}

function renderKeywordValidationResult(validation, run) {
    const resultEl = document.getElementById('aysa-keyword-validation-result');
    const statusEl = document.getElementById('aysa-keyword-validation-status');
    if (!resultEl) {
        return;
    }

    const secondary = Array.isArray(validation.secondary_keywords) ? validation.secondary_keywords.filter(Boolean) : [];
    const confidence = typeof validation.confidence_score === 'number'
        ? `${Math.round(validation.confidence_score * 100)}%`
        : 'n/a';
    const existing = validation.existing_keyword || '';
    const candidate = validation.candidate_keyword || '';
    const selected = validation.selected_keyword || '';
    const label = validation.status_label || 'Keyword validation result';
    const comparisonReason = validation.comparison_reason || validation.decision_reason || validation.persist_reason || '';
    const nextStep = validation.next_step || '';
    const billing = run && run.estimated_credits_cents ? `${run.estimated_credits_cents}c est.` : '';

    resultEl.style.display = 'block';
    resultEl.innerHTML = `
        <div style="font-weight:600;margin-bottom:8px;">${escapeHtml(label)}</div>
        ${existing ? `<div><strong>Existing:</strong> ${escapeHtml(existing)}</div>` : ''}
        ${candidate && candidate !== existing ? `<div><strong>Candidate:</strong> ${escapeHtml(candidate)}</div>` : ''}
        ${selected ? `<div><strong>Selected:</strong> ${escapeHtml(selected)}</div>` : ''}
        ${secondary.length ? `<div><strong>Secondary:</strong> ${escapeHtml(secondary.join(', '))}</div>` : ''}
        <div><strong>Confidence:</strong> ${escapeHtml(confidence)}</div>
        ${comparisonReason ? `<div><strong>Reason:</strong> ${escapeHtml(comparisonReason)}</div>` : ''}
        ${nextStep ? `<div><strong>Next Step:</strong> ${escapeHtml(nextStep)}</div>` : ''}
        ${billing ? `<div><strong>Billing:</strong> ${escapeHtml(billing)}</div>` : ''}
    `;

    if (statusEl) {
        statusEl.textContent = label;
    }
}

function buildKeywordValidationRequestPayload() {
    const titleField = document.getElementById('title');
    const metaDescriptionField = document.getElementById('aysa-entity-meta-description');
    const keywordField = document.getElementById('aysa-entity-keyword');
    const descriptionField = document.getElementById('description');
    const tagDescriptionField = document.getElementById('tag-description');
    const excerptField = document.getElementById('excerpt');
    const contentField = document.getElementById('content');
    const productShortDescription = document.getElementById('excerpt_ifr') ? '' : (excerptField ? excerptField.value : '');

    return {
        entity_id: getEntityId(),
        entity_type: getEntityTypeGood(),
        taxonomy: getEntityTaxonomy(),
        title: readFirstValue([
            titleField ? titleField.value : '',
            document.getElementById('name') ? document.getElementById('name').value : '',
            document.querySelector('h1') ? document.querySelector('h1').textContent : ''
        ]),
        meta_description: metaDescriptionField ? metaDescriptionField.value : '',
        page_text: readFirstValue([
            getEditorTextContent(),
            contentField ? contentField.value : '',
            descriptionField ? descriptionField.value : '',
            tagDescriptionField ? tagDescriptionField.value : '',
            productShortDescription
        ]),
        url: getFrontendEntityUrl(),
        existing_keyword: keywordField ? keywordField.value.trim() : '',
        language: (typeof aysaParams !== 'undefined' && aysaParams.language_optimize) ? aysaParams.language_optimize : 'ro',
        country_code: 'ro'
    };
}

function getFrontendEntityUrl() {
    const selectors = [
        '#sample-permalink a',
        '#edit-slug-box a',
        'a.editor-post-preview',
        '.view a'
    ];
    for (const selector of selectors) {
        const node = document.querySelector(selector);
        if (node && node.href) {
            return node.href;
        }
    }
    return '';
}

function getEditorTextContent() {
    if (window.tinyMCE && typeof window.tinyMCE.get === 'function') {
        const editor = window.tinyMCE.get('content');
        if (editor) {
            return editor.getContent({ format: 'text' }).trim();
        }
    }
    const contentField = document.getElementById('content');
    return contentField ? String(contentField.value || '').trim() : '';
}

function getEntityTaxonomy() {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('taxonomy') || '';
}

function readFirstValue(values) {
    for (const value of values) {
        const normalized = String(value || '').trim();
        if (normalized !== '') {
            return normalized;
        }
    }
    return '';
}

function escapeHtml(value) {
    return String(value || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

/**
 * Save original values of WordPress fields
 */
function saveOriginalWpValues() {
    console.log('Saving original WordPress field values');
    const nameField = document.getElementById('name');
    const slugField = document.getElementById('slug');
    const descriptionField = document.getElementById('description');
    
    // Find short description field - try different selectors for WooCommerce
    const shortDescField = document.getElementById('excerpt') || 
                          document.getElementById('post_excerpt') || 
                          document.querySelector('#postexcerpt textarea');
    
    // Find product fields
    const productTitleField = document.getElementById('title') || 
                             document.getElementById('post_title');
    
    const productPermalinkField = document.getElementById('editable-post-name') || 
                                 document.getElementById('editable-post-name-full') || 
                                 document.querySelector('#edit-slug-box .editable-post-name');
    
    const productDescriptionField = document.getElementById('content') || 
                                   document.querySelector('#wp-content-editor-container textarea');
    
    if (nameField) {
        originalWpValues.name = nameField.value;
        console.log('Saved original name:', originalWpValues.name);
    }
    
    if (slugField) {
        originalWpValues.slug = slugField.value;
        console.log('Saved original slug:', originalWpValues.slug);
    }
    
    if (descriptionField) {
        originalWpValues.description = descriptionField.value;
        console.log('Saved original description:', originalWpValues.description);
        
        // If TinyMCE is active
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
            originalWpValues.description = tinyMCE.get('description').getContent();
            console.log('Saved original description from TinyMCE editor');
        }
    }
    
    // Save short description if found
    if (shortDescField) {
        originalWpValues.shortDescription = shortDescField.value;
        console.log('Saved original short description:', originalWpValues.shortDescription);
        
        // If TinyMCE is active for excerpt
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
            originalWpValues.shortDescription = tinyMCE.get('excerpt').getContent();
            console.log('Saved original short description from TinyMCE editor');
        }
    }
    
    // Save product title if found
    if (productTitleField) {
        originalWpValues.productTitle = productTitleField.value;
        console.log('Saved original product title:', originalWpValues.productTitle);
    }
    
    // Save product permalink if found
    if (productPermalinkField) {
        originalWpValues.productPermalink = productPermalinkField.textContent || productPermalinkField.value;
        console.log('Saved original product permalink:', originalWpValues.productPermalink);
    }
    
    // Save product description if found
    if (productDescriptionField) {
        originalWpValues.productDescription = productDescriptionField.value;
        console.log('Saved original product description:', originalWpValues.productDescription);
        
        // If TinyMCE is active for content
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
            originalWpValues.productDescription = tinyMCE.get('content').getContent();
            console.log('Saved original product description from TinyMCE editor');
        }
    }
    
    // Also initialize pre-generation values with the same original values
    preGenerationValues = JSON.parse(JSON.stringify(originalWpValues));
    console.log('Initialized pre-generation values with original values');
}

/**
 * Handle Generate Suggestions button click
 */
function handleGenerateSuggestions(e) {
    e.preventDefault();
    
    // Save current field values before generating suggestions
    savePreGenerationValues();
    
    // Also save meta field values before generating suggestions
    savePreGenerationMetaValues();
    
    // Show spinner
    const spinner = this.nextElementSibling;
    if (spinner) spinner.classList.add('is-active');
    
    // Disable button temporarily
    this.disabled = true;
    
    // Get entity ID and type
    const entityId = getEntityId();
    const entityType = getEntityTypeGood();
    
    // Check if we have the required data
    if (entityId === 0) {
        if (typeof showToast === 'function') {
            showToast('Entity ID not found. Please save the category first.', 'error');
        }
        
        // Re-enable button and hide spinner
        this.disabled = false;
        if (spinner) spinner.classList.remove('is-active');
        return;
    }
    
    // Call the main handleGenerateSuggestions function from aysa-actions.js
    console.log('🔍 DEBUG: Checking for window.handleGenerateSuggestions...');
    console.log('🔍 DEBUG: typeof window.handleGenerateSuggestions:', typeof window.handleGenerateSuggestions);
    console.log('🔍 DEBUG: window object keys containing "handle":', Object.keys(window).filter(k => k.includes('handle')));
    
    if (typeof window.handleGenerateSuggestions === 'function') {
        console.log('✅ Calling main handleGenerateSuggestions function from window');
        // Re-enable button first (will be managed by the main function)
        this.disabled = false;
        if (spinner) spinner.classList.remove('is-active');
        
        // Call the main function
        window.handleGenerateSuggestions(e);
    } else {
        console.log('❌ Main handleGenerateSuggestions function not found, showing toast message');
        console.log('❌ Available window functions:', Object.keys(window).filter(k => typeof window[k] === 'function' && k.includes('aysa')));
        showToast('Please refresh the page and try again. Function not loaded.', 'error');
        
        // Re-enable button and hide spinner
        this.disabled = false;
        if (spinner) spinner.classList.remove('is-active');
    }
}

/**
 * Save current values before generating SEO suggestions
 */
function savePreGenerationValues() {
    console.log('Saving values before SEO generation');
    const nameField = document.getElementById('name');
    const slugField = document.getElementById('slug');
    const descriptionField = document.getElementById('description');
    
    // Find short description field - try different selectors for WooCommerce
    const shortDescField = document.getElementById('excerpt') || 
                          document.getElementById('post_excerpt') || 
                          document.querySelector('#postexcerpt textarea');
    
    // Find product fields
    const productTitleField = document.getElementById('title') || 
                             document.getElementById('post_title');
    
    const productPermalinkField = document.getElementById('editable-post-name') || 
                                 document.getElementById('editable-post-name-full') || 
                                 document.querySelector('#edit-slug-box .editable-post-name');
    
    const productDescriptionField = document.getElementById('content') || 
                                   document.querySelector('#wp-content-editor-container textarea');
    
    if (nameField) {
        preGenerationValues.name = nameField.value;
        console.log('Saved pre-generation name:', preGenerationValues.name);
    }
    
    if (slugField) {
        preGenerationValues.slug = slugField.value;
        console.log('Saved pre-generation slug:', preGenerationValues.slug);
    }
    
    if (descriptionField) {
        preGenerationValues.description = descriptionField.value;
        console.log('Saved pre-generation description:', preGenerationValues.description);
        
        // If TinyMCE is active
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
            preGenerationValues.description = tinyMCE.get('description').getContent();
            console.log('Saved pre-generation description from TinyMCE editor');
        }
    }
    
    // Save short description if found
    if (shortDescField) {
        preGenerationValues.shortDescription = shortDescField.value;
        console.log('Saved pre-generation short description:', preGenerationValues.shortDescription);
        
        // If TinyMCE is active for excerpt
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
            preGenerationValues.shortDescription = tinyMCE.get('excerpt').getContent();
            console.log('Saved pre-generation short description from TinyMCE editor');
        }
    }
    
    // Save product title if found
    if (productTitleField) {
        preGenerationValues.productTitle = productTitleField.value;
        console.log('Saved pre-generation product title:', preGenerationValues.productTitle);
    }
    
    // Save product permalink if found
    if (productPermalinkField) {
        preGenerationValues.productPermalink = productPermalinkField.textContent || productPermalinkField.value;
        console.log('Saved pre-generation product permalink:', preGenerationValues.productPermalink);
    }
    
    // Save product description if found
    if (productDescriptionField) {
        preGenerationValues.productDescription = productDescriptionField.value;
        console.log('Saved pre-generation product description:', preGenerationValues.productDescription);
        
        // If TinyMCE is active for content
        if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
            preGenerationValues.productDescription = tinyMCE.get('content').getContent();
            console.log('Saved pre-generation product description from TinyMCE editor');
        }
    }
}

/**
 * Save current meta values before generating SEO suggestions
 */
function savePreGenerationMetaValues() {
    console.log('Saving meta values before SEO generation');
    const metaTitleInput = document.getElementById('aysa-entity-meta-title');
    const metaDescriptionInput = document.getElementById('aysa-entity-meta-description');
    const metaKeywordsInput = document.getElementById('aysa-entity-meta-keywords');
    
    if (metaTitleInput) {
        preGenerationMetaValues.title = metaTitleInput.value;
        console.log('Saved pre-generation meta title:', preGenerationMetaValues.title);
    }
    
    if (metaDescriptionInput) {
        preGenerationMetaValues.description = metaDescriptionInput.value;
        console.log('Saved pre-generation meta description:', preGenerationMetaValues.description);
    }
    
    if (metaKeywordsInput) {
        preGenerationMetaValues.keywords = metaKeywordsInput.value;
        console.log('Saved pre-generation meta keywords:', preGenerationMetaValues.keywords);
    }
}

/**
 * Add description Accept/Reject buttons
 * This function is called with a slight delay to ensure all DOM elements are loaded
 */
function addDescriptionButtons() {
    console.log('Adding description Accept/Reject buttons');
    
    // Try to find the description row
    const descRow = document.querySelector('.term-description-wrap');
    if (!descRow) {
        console.log('Description row not found');
        return;
    }
    
    console.log('Found description row:', descRow);
    
    // Try to find the TD element
    const tdElement = descRow.querySelector('td');
    if (!tdElement) {
        console.log('TD element not found in description row');
        return;
    }
    
    console.log('Found TD element in description row:', tdElement);
    
    // Create button elements directly
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'accept-btn-container description-field-buttons';
    buttonContainer.style.textAlign = 'right';
    buttonContainer.style.marginTop = '15px';
    buttonContainer.style.marginBottom = '15px';
    buttonContainer.style.clear = 'both';
    
    // Create Reject button
    const rejectButton = document.createElement('button');
    rejectButton.className = 'aysa-button aysa-button-action';
    rejectButton.id = 'reject-description-field';
    rejectButton.textContent = 'Revert';
    
    // Create spinner
    const spinner = document.createElement('span');
    spinner.className = 'spinner';
    
    // Add buttons to container
    buttonContainer.appendChild(rejectButton);
    buttonContainer.appendChild(spinner);
    
    // Check if buttons already exist to avoid duplicates
    if (document.getElementById('reject-description-field')) {
        console.log('Description buttons already exist, not adding again');
        return;
    }
    
    // Add container to TD element at the end
    tdElement.appendChild(buttonContainer);
    console.log('Description buttons added successfully');
    
    // Add event listeners
    rejectButton.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show spinner
        spinner.classList.add('is-active');
        
        // Disable buttons temporarily
        rejectButton.disabled = true;
        
        // Restore description value from pre-generation values (before SEO generation)
        const descriptionField = document.getElementById('description');
        if (descriptionField && preGenerationValues.description) {
            console.log('Restoring description to pre-generation value:', preGenerationValues.description);
            descriptionField.value = preGenerationValues.description;
            
            // If TinyMCE is active
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
                tinyMCE.get('description').setContent(preGenerationValues.description, {format: 'raw'});
            }
            
            // Show success message
            if (typeof showToast === 'function') {
                showToast('Description restored to pre-generation value', 'info');
            }
            
            // Re-enable buttons and hide spinner
            rejectButton.disabled = false;
            spinner.classList.remove('is-active');
            return;
        }
        
        // Fallback to original values if pre-generation values aren't available
        if (descriptionField && originalWpValues.description) {
            console.log('No pre-generation values found, using original values instead');
            descriptionField.value = originalWpValues.description;
            
            // If TinyMCE is active
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('description')) {
                tinyMCE.get('description').setContent(originalWpValues.description, {format: 'raw'});
            }
            
            // Show success message
            if (typeof showToast === 'function') {
                showToast('Description restored to original', 'info');
            }
            
            // Re-enable buttons and hide spinner
            rejectButton.disabled = false;
            spinner.classList.remove('is-active');
            return;
        }
    });
}

/**
 * Add product short description Accept/Reject buttons
 * This function is called with a slight delay to ensure all DOM elements are loaded
 */
function addProductShortDescriptionButtons() {
    console.log('Adding product short description Accept/Reject buttons');
    
    // Try to find the short description field - try different possible selectors for WooCommerce
    const shortDescField = document.getElementById('excerpt') || 
                          document.getElementById('post_excerpt') || 
                          document.querySelector('#postexcerpt textarea');
    
    if (!shortDescField) {
        console.log('Product short description field not found');
        return;
    }
    
    // Try to find the short description container or postbox
    const shortDescContainer = document.getElementById('postexcerpt') || 
                              shortDescField.closest('.postbox') || 
                              shortDescField.closest('#postexcerpt');
    
    if (!shortDescContainer) {
        console.log('Product short description container not found');
        return;
    }
    
    console.log('Found product short description field:', shortDescField);
    console.log('Found product short description container:', shortDescContainer);
    
    // Check if we're really on a product page
    const isProductPage = document.body.classList.contains('post-type-product') || 
                          (document.querySelector('input[name="post_type"]')?.value === 'product');
    
    if (!isProductPage) {
        console.log('Not on a product page, skipping short description buttons');
        return;
    }
    
    // Check if buttons already exist to avoid duplicates
    if (document.getElementById('accept-short-description-field')) {
        console.log('Short description buttons already exist, not adding again');
        return;
    }
    
    // Create button elements directly
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'accept-btn-container short-description-field-buttons';
    buttonContainer.style.textAlign = 'right';
    buttonContainer.style.marginTop = '15px';
    buttonContainer.style.marginBottom = '15px';
    buttonContainer.style.clear = 'both';
    
    // Create Accept button
    const acceptButton = document.createElement('button');
    acceptButton.className = 'aysa-button aysa-button-success save';
    acceptButton.id = 'accept-short-description-field';
    acceptButton.textContent = 'Accept Short Description';
    
    // Create Reject button
    const rejectButton = document.createElement('button');
    rejectButton.className = 'aysa-button aysa-button-action';
    rejectButton.id = 'reject-short-description-field';
    rejectButton.textContent = 'Revert';
    
    // Create spinner
    const spinner = document.createElement('span');
    spinner.className = 'spinner';
    
    // Add buttons to container
    buttonContainer.appendChild(acceptButton);
    buttonContainer.appendChild(rejectButton);
    buttonContainer.appendChild(spinner);
    
    // Try to find the best insertion point
    // For WooCommerce, try to find inside postexcerpt
    const targetElement = shortDescContainer.querySelector('.inside') || shortDescContainer;
    
    // Add container as the last child of the target element
    targetElement.appendChild(buttonContainer);
    console.log('Short description buttons added successfully');
    
    // Add event listeners
    acceptButton.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show spinner
        spinner.classList.add('is-active');
        
        // Disable buttons temporarily
        acceptButton.disabled = true;
        rejectButton.disabled = true;
        
        // Update original short description value
        if (shortDescField) {
            originalWpValues.shortDescription = shortDescField.value;
            
            // If TinyMCE is active, make sure to get content from editor
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
                originalWpValues.shortDescription = tinyMCE.get('excerpt').getContent();
            }
            
            // Also update pre-generation values
            preGenerationValues.shortDescription = originalWpValues.shortDescription;
        }
        
        // Show success message
        if (typeof showToast === 'function') {
            showToast('Short description accepted', 'success');
        }
        
        // Re-enable buttons and hide spinner after a short delay
        setTimeout(() => {
            acceptButton.disabled = false;
            rejectButton.disabled = false;
            spinner.classList.remove('is-active');
        }, 1000);
    });
    
    rejectButton.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show spinner
        spinner.classList.add('is-active');
        
        // Disable buttons temporarily
        acceptButton.disabled = true;
        rejectButton.disabled = true;
        
        // Restore short description value from pre-generation values
        if (shortDescField && preGenerationValues.shortDescription !== undefined) {
            console.log('Restoring short description to pre-generation value:', preGenerationValues.shortDescription);
            shortDescField.value = preGenerationValues.shortDescription;
            
            // If TinyMCE is active for excerpt
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
                tinyMCE.get('excerpt').setContent(preGenerationValues.shortDescription, {format: 'raw'});
            }
            
            // Show success message
            if (typeof showToast === 'function') {
                showToast('Short description restored to pre-generation value', 'info');
            }
            
            // Re-enable buttons and hide spinner
            acceptButton.disabled = false;
            rejectButton.disabled = false;
            spinner.classList.remove('is-active');
            return;
        }
        
        // Fallback to original values if pre-generation values aren't available
        if (shortDescField && originalWpValues.shortDescription) {
            console.log('No pre-generation values found, using original values instead');
            shortDescField.value = originalWpValues.shortDescription;
            
            // If TinyMCE is active for excerpt
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
                tinyMCE.get('excerpt').setContent(originalWpValues.shortDescription, {format: 'raw'});
            }
            
            // Show success message
            if (typeof showToast === 'function') {
                showToast('Short description restored to original', 'info');
            }
            
            // Re-enable buttons and hide spinner
            acceptButton.disabled = false;
            rejectButton.disabled = false;
            spinner.classList.remove('is-active');
            return;
        }
    });
}

/**
 * Add product title Accept/Reject buttons
 */
function addProductTitleButtons() {
    console.log('Adding product title Accept/Reject buttons');
    
    // Check if we're on a product page
    const isProductPage = document.body.classList.contains('post-type-product') || 
                          (document.querySelector('input[name="post_type"]')?.value === 'product');
    
    if (!isProductPage) {
        console.log('Not on a product page, skipping product title buttons');
        return;
    }
    
    // Find the product title field
    const titleField = document.getElementById('title') || document.getElementById('post_title');
    if (!titleField) {
        console.log('Product title field not found');
        return;
    }
    
    // Find a good place to insert the buttons - typically after the title field
    let targetElement = titleField.parentNode;
    if (!targetElement) {
        console.log('Could not find parent element for title field');
        return;
    }
    
    // Check if buttons already exist
    if (document.getElementById('accept-product-title')) {
        console.log('Product title buttons already exist, not adding again');
        return;
    }
    
    // Create button container
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'accept-btn-container product-title-buttons';
    buttonContainer.style.textAlign = 'right';
    buttonContainer.style.marginTop = '10px';
    buttonContainer.style.marginBottom = '15px';
    buttonContainer.style.clear = 'both';
    
    // Create Accept button
    const acceptButton = document.createElement('button');
    acceptButton.className = 'aysa-button aysa-button-success save';
    acceptButton.id = 'accept-product-title';
    acceptButton.textContent = 'Accept Title';
    
    // Create Reject button
    const rejectButton = document.createElement('button');
    rejectButton.className = 'aysa-button aysa-button-action';
    rejectButton.id = 'reject-product-title';
    rejectButton.textContent = 'Revert';
    
    // Create spinner
    const spinner = document.createElement('span');
    spinner.className = 'spinner';
    
    // Add buttons to container
    buttonContainer.appendChild(acceptButton);
    buttonContainer.appendChild(rejectButton);
    buttonContainer.appendChild(spinner);
    
    // Add container after the title field
    targetElement.appendChild(buttonContainer);
    console.log('Product title buttons added successfully');
    
    // Add event listeners
    acceptButton.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show spinner
        spinner.classList.add('is-active');
        
        // Disable buttons temporarily
        acceptButton.disabled = true;
        rejectButton.disabled = true;
        
        // Update original title value
        originalWpValues.productTitle = titleField.value;
        // Also update pre-generation value
        preGenerationValues.productTitle = titleField.value;
        
        // Show success message
        if (typeof showToast === 'function') {
            showToast('Product title accepted', 'success');
        }
        
        // Re-enable buttons and hide spinner after a short delay
        setTimeout(() => {
            acceptButton.disabled = false;
            rejectButton.disabled = false;
            spinner.classList.remove('is-active');
        }, 1000);
    });
    
    rejectButton.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show spinner
        spinner.classList.add('is-active');
        
        // Disable buttons temporarily
        acceptButton.disabled = true;
        rejectButton.disabled = true;
        
        // Restore title from pre-generation values
        if (preGenerationValues.productTitle) {
            titleField.value = preGenerationValues.productTitle;
            
            // Show success message
            if (typeof showToast === 'function') {
                showToast('Product title restored to pre-generation value', 'info');
            }
        } else if (originalWpValues.productTitle) {
            // Fallback to original values
            titleField.value = originalWpValues.productTitle;
            
            // Show success message
            if (typeof showToast === 'function') {
                showToast('Product title restored to original', 'info');
            }
        }
        
        // Re-enable buttons and hide spinner
        acceptButton.disabled = false;
        rejectButton.disabled = false;
        spinner.classList.remove('is-active');
    });
}

/**
 * Add product permalink Accept/Reject buttons
 */
function addProductPermalinkButtons() {
    console.log('Adding product permalink Accept/Reject buttons');
    
    // Check if we're on a product page
    const isProductPage = document.body.classList.contains('post-type-product') || 
                          (document.querySelector('input[name="post_type"]')?.value === 'product');
    
    if (!isProductPage) {
        console.log('Not on a product page, skipping product permalink buttons');
        return;
    }
    
    // Find the permalink container
    const permalinkContainer = document.getElementById('edit-slug-box');
    if (!permalinkContainer) {
        console.log('Permalink container not found');
        return;
    }
    
    // Check if buttons already exist
    if (document.getElementById('accept-product-permalink')) {
        console.log('Product permalink buttons already exist, not adding again');
        return;
    }
    
    // Create button container
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'accept-btn-container product-permalink-buttons';
    buttonContainer.style.textAlign = 'right';
    buttonContainer.style.marginTop = '10px';
    buttonContainer.style.marginBottom = '10px';
    buttonContainer.style.clear = 'both';
    
    // Create Accept button
    const acceptButton = document.createElement('button');
    acceptButton.className = 'aysa-button aysa-button-success save';
    acceptButton.id = 'accept-product-permalink';
    acceptButton.textContent = 'Accept Permalink';
    
    // Create Reject button
    const rejectButton = document.createElement('button');
    rejectButton.className = 'aysa-button aysa-button-action';
    rejectButton.id = 'reject-product-permalink';
    rejectButton.textContent = 'Revert';
    
    // Create spinner
    const spinner = document.createElement('span');
    spinner.className = 'spinner';
    
    // Add buttons to container
    buttonContainer.appendChild(acceptButton);
    buttonContainer.appendChild(rejectButton);
    buttonContainer.appendChild(spinner);
    
    // Add container after the permalink box
    permalinkContainer.appendChild(buttonContainer);
    console.log('Product permalink buttons added successfully');
    
    // Add event listeners
    acceptButton.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show spinner
        spinner.classList.add('is-active');
        
        // Disable buttons temporarily
        acceptButton.disabled = true;
        rejectButton.disabled = true;
        
        // Update original permalink value - this is trickier since permalink editing is complex in WordPress
        const permalinkField = document.getElementById('editable-post-name') || 
                             document.getElementById('editable-post-name-full') || 
                             document.querySelector('#edit-slug-box .editable-post-name');
        
        if (permalinkField) {
            originalWpValues.productPermalink = permalinkField.textContent || permalinkField.value;
            // Also update pre-generation value
            preGenerationValues.productPermalink = originalWpValues.productPermalink;
        }
        
        // Show success message
        if (typeof showToast === 'function') {
            showToast('Product permalink accepted', 'success');
        }
        
        // Re-enable buttons and hide spinner after a short delay
        setTimeout(() => {
            acceptButton.disabled = false;
            rejectButton.disabled = false;
            spinner.classList.remove('is-active');
        }, 1000);
    });
    
    rejectButton.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show spinner
        spinner.classList.add('is-active');
        
        // Disable buttons temporarily
        acceptButton.disabled = true;
        rejectButton.disabled = true;
        
        // For permalinks, we need to trigger WordPress's edit slug functionality
        // This is more complex - we'll show a message explaining what to do
        if (typeof showToast === 'function') {
            showToast('To reset permalink: Click "Edit" next to permalink, then enter: ' + 
                     (preGenerationValues.productPermalink || originalWpValues.productPermalink), 'info', 10000);
        }
        
        // Re-enable buttons and hide spinner
        acceptButton.disabled = false;
        rejectButton.disabled = false;
        spinner.classList.remove('is-active');
    });
}

/**
 * Add product description Accept/Reject buttons
 */
function addProductDescriptionButtons() {
    console.log('Adding product description Accept/Reject buttons');
    
    // Check if we're on a product page
    const isProductPage = document.body.classList.contains('post-type-product') || 
                          (document.querySelector('input[name="post_type"]')?.value === 'product');
    
    if (!isProductPage) {
        console.log('Not on a product page, skipping product description buttons');
        return;
    }
    
    // Find the description container
    const editorContainer = document.getElementById('wp-content-wrap') || 
                          document.getElementById('wp-content-editor-container') ||
                          document.getElementById('postdivrich');
    
    if (!editorContainer) {
        console.log('Product description editor container not found');
        return;
    }
    
    // Check if buttons already exist
    if (document.getElementById('reject-product-description')) {
        console.log('Product description buttons already exist, not adding again');
        return;
    }
    
    // Create button container
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'accept-btn-container product-description-buttons';
    buttonContainer.style.textAlign = 'right';
    buttonContainer.style.marginTop = '10px';
    buttonContainer.style.marginBottom = '15px';
    buttonContainer.style.clear = 'both';
    
    // Create Reject button
    const rejectButton = document.createElement('button');
    rejectButton.className = 'aysa-button aysa-button-action';
    rejectButton.id = 'reject-product-description';
    rejectButton.textContent = 'Revert';
    
    // Create spinner
    const spinner = document.createElement('span');
    spinner.className = 'spinner';
    
    // Add buttons to container
    buttonContainer.appendChild(rejectButton);
    buttonContainer.appendChild(spinner);
    
    // Add container after the editor
    editorContainer.appendChild(buttonContainer);
    console.log('Product description buttons added successfully');
    
    // Add event listeners
    rejectButton.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show spinner
        spinner.classList.add('is-active');
        
        // Disable buttons temporarily
        rejectButton.disabled = true;
        
        // Restore description content
        const contentToRestore = preGenerationValues.productDescription || originalWpValues.productDescription;
        
        if (contentToRestore) {
            // If TinyMCE is active
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                tinyMCE.get('content').setContent(contentToRestore, {format: 'raw'});
            } else {
                // If no TinyMCE, try to find the textarea
                const descriptionField = document.getElementById('content');
                if (descriptionField) {
                    descriptionField.value = contentToRestore;
                }
            }
            
            // Show success message
            if (typeof showToast === 'function') {
                if (contentToRestore === preGenerationValues.productDescription) {
                    showToast('Product description restored to pre-generation value', 'info');
                } else {
                    showToast('Product description restored to original', 'info');
                }
            }
        } else {
            // Show error message
            if (typeof showToast === 'function') {
                showToast('No saved product description found to restore', 'error');
            }
        }
        
        // Re-enable buttons and hide spinner
        rejectButton.disabled = false;
        spinner.classList.remove('is-active');
    });
}

/**
 * Add a single set of Accept/Reject buttons for all product fields
 */
function addProductFieldsButtons() {
    console.log('Adding product fields Accept/Reject buttons');
    
    // Check if we're on a product page
    const isProductPage = document.body.classList.contains('post-type-product') || 
                         (document.querySelector('input[name="post_type"]')?.value === 'product');
    
    if (!isProductPage) {
        console.log('Not on a product page, skipping product fields buttons');
        return;
    }
    
    // Check if buttons already exist to avoid duplicates
    if (document.getElementById('accept-product-fields')) {
        console.log('Product fields buttons already exist, not adding again');
        return;
    }
    
    // Find a good place to add the buttons - near the top of the page
    const titleBox = document.getElementById('titlediv');
    const submitBox = document.getElementById('submitdiv');
    
    if (!titleBox && !submitBox) {
        console.log('Could not find a suitable location for product fields buttons');
        return;
    }
    
    const targetElement = titleBox || submitBox;
    
    // Create button container with prominent styling
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'accept-btn-container product-fields-buttons';
    buttonContainer.style.textAlign = 'center';
    buttonContainer.style.padding = '10px 15px';
    buttonContainer.style.marginBottom = '20px';
    buttonContainer.style.backgroundColor = '#f0f0f1';
    buttonContainer.style.border = '1px solid #c3c4c7';
    buttonContainer.style.borderRadius = '3px';
    
    // Create Reject button
    const rejectButton = document.createElement('button');
    rejectButton.className = 'aysa-button aysa-button-action';
    rejectButton.id = 'reject-product-fields';
    rejectButton.textContent = 'Revert Product Content Changes';
    rejectButton.style.padding = '8px 16px';
    rejectButton.style.fontSize = '14px';
    
    // Create spinner
    const spinner = document.createElement('span');
    spinner.className = 'spinner';
    
    // Add explanation text
    const explanationText = document.createElement('div');
    explanationText.style.fontSize = '12px';
    explanationText.style.color = '#555';
    explanationText.style.marginTop = '8px';
    explanationText.textContent = 'This will revert changes to product title, permalink, description, and short description.';
    
    // Add buttons and text to container
    buttonContainer.appendChild(rejectButton);
    buttonContainer.appendChild(spinner);
    buttonContainer.appendChild(explanationText);
    
    // Add container BEFORE the target element to position it above the name field
    targetElement.insertAdjacentElement('beforebegin', buttonContainer);
    console.log('Product fields buttons added successfully above the name field');
    
    // Add event listeners
    rejectButton.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Show spinner
        spinner.classList.add('is-active');
        
        // Disable buttons temporarily
        rejectButton.disabled = true;
        
        // Restore all fields from pre-generation values
        
        // Title
        const titleField = document.getElementById('title') || document.getElementById('post_title');
        if (titleField && preGenerationValues.productTitle) {
            titleField.value = preGenerationValues.productTitle;
        }
        
        // Permalink - show message with instructions
        if (preGenerationValues.productPermalink) {
            if (typeof showToast === 'function') {
                showToast('To reset permalink: Click "Edit" next to permalink, then enter: ' + 
                         preGenerationValues.productPermalink, 'info', 5000);
            }
        }
        
        // Main Description
        if (preGenerationValues.productDescription) {
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                tinyMCE.get('content').setContent(preGenerationValues.productDescription, {format: 'raw'});
            } else {
                const descriptionField = document.getElementById('content');
                if (descriptionField) {
                    descriptionField.value = preGenerationValues.productDescription;
                }
            }
        }
        
        // Short Description
        if (preGenerationValues.shortDescription) {
            const shortDescField = document.getElementById('excerpt') || 
                                  document.getElementById('post_excerpt') || 
                                  document.querySelector('#postexcerpt textarea');
                                  
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
                tinyMCE.get('excerpt').setContent(preGenerationValues.shortDescription, {format: 'raw'});
            } else if (shortDescField) {
                shortDescField.value = preGenerationValues.shortDescription;
            }
        }
        
        // Show success message
        if (typeof showToast === 'function') {
            showToast('All product content restored to pre-generation values', 'info');
        }
        
        // Re-enable buttons and hide spinner
        rejectButton.disabled = false;
        spinner.classList.remove('is-active');
    });
}

/**
 * Check for pending new entity data in localStorage and process it
 */
function checkForPendingEntityData() {
    const currentEntityId = getEntityId();
    const currentEntityType = getEntityTypeGood();
    
    // Only process if we have a valid entity ID (entity was created)
    if (!currentEntityId || currentEntityId === 0) {
        return;
    }
    
    console.log('Checking for pending entity data for:', currentEntityType, currentEntityId);
    
    // Look for pending data in localStorage
    const pendingKeys = [];
    for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key && key.startsWith(`aysa_pending_${currentEntityType}_`)) {
            pendingKeys.push(key);
        }
    }
    
    if (pendingKeys.length === 0) {
        console.log('No pending data found');
        return;
    }
    
    console.log('Found pending data keys:', pendingKeys);
    
    // Process the most recent pending data
    pendingKeys.sort(); // Sort to get the most recent (highest timestamp)
    const latestKey = pendingKeys[pendingKeys.length - 1];
    
    try {
        const pendingDataStr = localStorage.getItem(latestKey);
        if (pendingDataStr) {
            const pendingData = JSON.parse(pendingDataStr);
            console.log('Processing pending data:', pendingData);
            
            // Check if this data is recent (within last 10 minutes)
            const dataAge = Date.now() - new Date(pendingData.timestamp).getTime();
            if (dataAge < 10 * 60 * 1000) { // 10 minutes
                // Process the data - call the function from aysa-actions.js
                if (typeof window.processNewEntityData === 'function') {
                    window.processNewEntityData(currentEntityId, pendingData, latestKey);
                } else if (typeof processNewEntityData === 'function') {
                    processNewEntityData(currentEntityId, pendingData, latestKey);
                } else {
                    console.error('processNewEntityData function not available, trying manual processing...');
                    
                    // Try to process manually by calling the API directly
                    processNewEntityDataManually(currentEntityId, pendingData, latestKey);
                }
            } else {
                console.log('Pending data too old, removing:', latestKey);
                localStorage.removeItem(latestKey);
            }
        }
    } catch (error) {
        console.error('Error processing pending data:', error);
        localStorage.removeItem(latestKey);
    }
    
    // Clean up other old pending keys
    pendingKeys.forEach(key => {
        if (key !== latestKey) {
            try {
                const dataStr = localStorage.getItem(key);
                if (dataStr) {
                    const data = JSON.parse(dataStr);
                    const age = Date.now() - new Date(data.timestamp).getTime();
                    if (age > 10 * 60 * 1000) { // Older than 10 minutes
                        localStorage.removeItem(key);
                        console.log('Removed old pending data:', key);
                    }
                }
            } catch (error) {
                // If we can't parse it, remove it
                localStorage.removeItem(key);
            }
        }
    });
}

/**
 * Manual processing of new entity data when automatic detection fails
 */
async function processNewEntityDataManually(entityId, newEntityData, pendingKey) {
    console.log('Processing new entity data manually for ID:', entityId, newEntityData);
    
    try {
        // Get the current entity name from the page
        const entityName = document.getElementById('name')?.value || 
                          document.getElementById('title')?.value || 
                          newEntityData.entityName || '';
        
        // Prepare the association data for the new entity
        const associationData = {
            IdIntern: entityId,
            AssociatedOn: newEntityData.entityType,
            Value: 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 from newEntityData.seoSettings
            TargetedSearchEngine: newEntityData.seoSettings?.targetedSearchEngine || '',
            TargetedCountry: newEntityData.seoSettings?.targetedCountry || '',
            TargetedRegion: newEntityData.seoSettings?.targetedRegion || '',
            TargetedCity: newEntityData.seoSettings?.targetedCity || '',
            UpdateFrequency: newEntityData.seoSettings?.updateFrequency || '',
            LanguageOptimize: newEntityData.seoSettings?.languageOptimize || '',
            DeviceOptimize: newEntityData.seoSettings?.deviceOptimize || '',
            
            // Advanced settings from newEntityData.advancedSettings
            Index: newEntityData.advancedSettings?.index || false,
            NoFollow: newEntityData.advancedSettings?.noFollow || false,
            NoArchive: newEntityData.advancedSettings?.noArchive || false,
            NoImageIndex: newEntityData.advancedSettings?.noImageIndex || false,
            NoSnippet: newEntityData.advancedSettings?.noSnippet || false,
            MaxSnippet: newEntityData.advancedSettings?.maxSnippet || -1,
            MaxVideoPreview: newEntityData.advancedSettings?.maxVideoPreview || -1,
            MaxImagePreview: newEntityData.advancedSettings?.maxImagePreview || 'small',
            CanonicalUrl: newEntityData.advancedSettings?.canonicalUrl || ''
        };
        
        console.log('Creating main association for new entity (manual):', 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 (manual):', mainAssociationData);
        
        // Process secondary keywords if any
        if (newEntityData.secondaryKeywords && newEntityData.secondaryKeywords.length > 0) {
            console.log('Processing secondary keywords for new entity (manual):', newEntityData.secondaryKeywords);
            
            // Process each secondary keyword
            for (const keywordData of newEntityData.secondaryKeywords) {
                const keyword = typeof keywordData === 'string' ? keywordData : keywordData.keyword;
                const isTracked = typeof keywordData === 'object' && keywordData.isTracked !== undefined ? 
                                 keywordData.isTracked : true;
                
                if (!keyword || keyword.trim() === '') continue;
                
                const secondaryAssociationData = {
                    IdIntern: entityId,
                    AssociatedOn: newEntityData.entityType,
                    Value: entityName,
                    Link: window.location.href,
                    Keyword: keyword.trim(),
                    ProjectId: newEntityData.projectId,
                    IsMain: false,
                    IsTracked: isTracked,
                    
                    // Copy SEO fields from main association
                    MetaTitle: mainAssociationData.metaTitle || '',
                    MetaDescription: mainAssociationData.metaDescription || '',
                    MetaKeywords: mainAssociationData.metaKeywords || '',
                    
                    // Copy SEO settings
                    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(`Creating secondary association for "${keyword}" (tracked=${isTracked}):`, secondaryAssociationData);
                
                const secondaryResponse = await fetch(apiUrl, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'Origin': window.location.origin
                    },
                    body: JSON.stringify(secondaryAssociationData),
                    mode: 'cors'
                });
                
                if (secondaryResponse.ok) {
                    const secondaryResult = await secondaryResponse.json();
                    console.log(`Secondary keyword "${keyword}" processed successfully:`, secondaryResult);
                } else {
                    console.error(`Error processing secondary keyword "${keyword}":`, secondaryResponse.status);
                }
            }
        }
        
        // Clean up localStorage
        localStorage.removeItem(pendingKey);
        console.log('Removed pending data from localStorage (manual):', pendingKey);
        
        // Show success message
        if (typeof showToast === 'function') {
            showToast('AYSA SEO data processed successfully for new entity!', 'success');
        }
        
        // Reload data from API to update the UI
        if (typeof loadDataFromAPI === 'function') {
            setTimeout(() => {
                loadDataFromAPI();
            }, 1000);
        }
        
    } catch (error) {
        console.error('Error processing new entity data manually:', error);
        
        // Show error message but keep data for retry
        if (typeof showToast === 'function') {
            showToast('Error processing AYSA data. Data saved for retry.', 'error');
        }
    }
}

/**
 * ✅ NEW: Make actual API calls to AYSA (upsert + insert many) BEFORE WordPress save
 */
async function makeAysaApiCalls(entityId, entityType, aysaData) {
    return new Promise(async (resolve, reject) => {
        try {
            console.log('🔥 Starting AYSA API calls for entity:', entityId, entityType);
            
            // ✅ Debug aysaParams availability
            console.log('🔍 aysaParams debug:', {
                available: typeof aysaParams !== 'undefined',
                nonce: typeof aysaParams !== 'undefined' ? (aysaParams.nonce ? aysaParams.nonce.substring(0, 10) + '...' : 'MISSING') : 'aysaParams undefined',
                ajax_url: typeof aysaParams !== 'undefined' ? aysaParams.ajax_url : 'MISSING',
                project_id: typeof aysaParams !== 'undefined' ? aysaParams.project_id : 'MISSING'
            });
            
            // Get required data for API calls
            const projectId = getProjectId();
            const apiKey = getApiKey();
            
            if (!projectId || !apiKey) {
                console.error('❌ Missing project ID or API key for AYSA API calls');
                resolve({
                    success: false,
                    error: 'Missing project ID or API key',
                    code: 'MISSING_CONFIG'
                });
                return;
            }
            
            // ✅ Get existing association data from API cache
            let mainAssociation = null;
            let associationId = null;
            
            if (aysaAPIData && Array.isArray(aysaAPIData)) {
                // Find the main association (with isMain=true), or use the first one
                mainAssociation = aysaAPIData.find(a => a.isMain === true) || aysaAPIData[0];
                if (mainAssociation) {
                    associationId = mainAssociation.id;
                    console.log('✅ Found existing main association with ID:', associationId);
                }
            }
            
            // Prepare API data
            const apiData = {
                // ✅ CRITICAL: Include association ID if exists (for update)
                association_id: associationId,
                entity_id: entityId,
                entity_type: entityType,
                project_id: projectId,
                
                // GENERAL
                keyword: aysaData.keyword || '',
                secondary_keywords: aysaData.second_keyword || '',
                meta_title: aysaData.aysa_meta_title || '',
                meta_description: aysaData.aysa_meta_description || '',
                meta_keywords: aysaData.aysa_meta_keywords || '',
                track: aysaData.track || 0,
                
                // SEO SETTINGS
                targeted_search_engine: aysaData.targeted_search_engine || '',
                targeted_country: aysaData.targeted_country || '',
                targeted_region: aysaData.targeted_region || '',
                targeted_city: aysaData.targeted_city || '',
                update_frequency: aysaData.update_frequency || '',
                language_optimize: aysaData.language_optimize || '',
                device_optimize: aysaData.device_optimize || '',
                
                // ADVANCED
                index: aysaData.index !== undefined ? aysaData.index : null,
                no_follow: aysaData.no_follow !== undefined ? aysaData.no_follow : null,
                no_archive: aysaData.no_archive !== undefined ? aysaData.no_archive : null,
                no_image_index: aysaData.no_image_index !== undefined ? aysaData.no_image_index : null,
                no_snippet: aysaData.no_snippet !== undefined ? aysaData.no_snippet : null,
                max_snippet: aysaData.max_snippet !== undefined ? aysaData.max_snippet : null,
                max_video_preview: aysaData.max_video_preview !== undefined ? aysaData.max_video_preview : null,
                max_image_preview: aysaData.max_image_preview || '',
                canonical_url: aysaData.canonical_url || '',
                
                timestamp: new Date().toISOString()
            };
            
            console.log('📤 Prepared API data:', apiData);
            console.log('🔍 Association ID being used:', associationId);
            console.log('🔍 aysaAPIData contents:', aysaAPIData);
            
            // ✅ STEP 1: Make UPSERT call
            console.log('🚀 Step 1: Making UPSERT call...');
            const upsertResult = await makeUpsertCall(apiData, apiKey);
            
            if (!upsertResult.success) {
                console.error('❌ UPSERT call failed:', upsertResult.error);
                resolve({
                    success: false,
                    error: 'UPSERT call failed: ' + upsertResult.error,
                    code: 'UPSERT_FAILED',
                    upsert: upsertResult
                });
                return;
            }
            
            console.log('✅ UPSERT call successful');
            
            // ✅ STEP 2: Make INSERT MANY call (for secondary keywords)
            let insertManyResult = { success: true, message: 'No secondary keywords to insert' };
            
            // ✅ Only make INSERT MANY if there are actual secondary keywords (respect user's form input)
            if (aysaData.second_keyword && aysaData.second_keyword.trim()) {
                console.log('🚀 Step 2: Making INSERT MANY call for secondary keywords...');
                console.log('🔍 Secondary keywords from form:', aysaData.second_keyword);
                
                // Parse secondary keywords
                const secondaryKeywords = aysaData.second_keyword.split(',').map(k => k.trim()).filter(k => k);
                
                if (secondaryKeywords.length > 0) {
                    try {
                        insertManyResult = await makeInsertManyCall(entityId, entityType, secondaryKeywords, projectId, apiKey, apiData);
                        
                        if (!insertManyResult.success) {
                            console.warn('⚠️ INSERT MANY call failed but continuing:', insertManyResult.error);
                            // ✅ Don't fail the whole process - just log and continue
                            insertManyResult = { 
                                success: false, 
                                error: insertManyResult.error,
                                non_blocking: true,
                                message: 'INSERT MANY failed but process continues'
                            };
                        } else {
                            console.log('✅ INSERT MANY call successful');
                        }
                    } catch (error) {
                        console.warn('⚠️ INSERT MANY call exception but continuing:', error);
                        insertManyResult = { 
                            success: false, 
                            error: error.message,
                            non_blocking: true,
                            message: 'INSERT MANY error but process continues'
                        };
                    }
                }
            } else {
                console.log('⏭️ Skipping INSERT MANY - no secondary keywords in form (user cleared them or never set them)');
            }
            
            // ✅ Success - main call completed (INSERT MANY failures are non-blocking)
            const allSuccess = upsertResult.success && (insertManyResult.success || insertManyResult.non_blocking);
            const message = allSuccess ? 'All API calls completed successfully' : 
                           'Main API call successful, secondary keywords may have failed';
            
            console.log('🎉 ' + message);
            resolve({
                success: true, // ✅ Always success if UPSERT worked
                message: message,
                upsert: upsertResult,
                insertMany: insertManyResult,
                apiData: apiData
            });
            
        } catch (error) {
            console.error('💥 Error in makeAysaApiCalls:', error);
            resolve({
                success: false,
                error: error.message,
                code: 'API_CALL_ERROR'
            });
        }
    });
}

/**
 * ✅ NEW: Make UPSERT call to AYSA API
 */
async function makeUpsertCall(apiData, apiKey) {
    return new Promise((resolve, reject) => {
        if (!window.jQuery) {
            resolve({ success: false, error: 'jQuery not available' });
            return;
        }
        
        // ✅ Better nonce handling with debug
        let nonce = '';
        if (typeof aysaParams !== 'undefined' && aysaParams.nonce) {
            nonce = aysaParams.nonce;
            console.log('✅ Using aysaParams nonce:', nonce.substring(0, 10) + '...');
        } else {
            console.warn('⚠️ aysaParams not available, trying alternative nonce sources');
            
            // Try to get nonce from other sources
            const metaboxNonce = document.querySelector('input[name="aysa_metabox_nonce"]');
            const wpNonce = document.querySelector('#_wpnonce');
            
            if (metaboxNonce) {
                nonce = metaboxNonce.value;
                console.log('✅ Using metabox nonce:', nonce.substring(0, 10) + '...');
            } else if (wpNonce) {
                nonce = wpNonce.value;
                console.log('✅ Using WordPress nonce:', nonce.substring(0, 10) + '...');
            } else {
                console.error('❌ No nonce found anywhere!');
            }
        }
        
        const upsertData = {
            action: 'aysa_upsert_entity', // WordPress AJAX action
            
            // ✅ CRITICAL: Include association ID if exists (for update)
            association_id: apiData.association_id,
            entity_id: apiData.entity_id,
            entity_type: apiData.entity_type,
            project_id: apiData.project_id,
            
            // GENERAL
            keyword: apiData.keyword,
            meta_title: apiData.meta_title,
            meta_description: apiData.meta_description,
            meta_keywords: apiData.meta_keywords,
            track: apiData.track,
            
            // SEO SETTINGS
            targeted_search_engine: apiData.targeted_search_engine,
            targeted_country: apiData.targeted_country,
            targeted_region: apiData.targeted_region,
            targeted_city: apiData.targeted_city,
            update_frequency: apiData.update_frequency,
            language_optimize: apiData.language_optimize,
            device_optimize: apiData.device_optimize,
            
            // ADVANCED
            index: apiData.index,
            no_follow: apiData.no_follow,
            no_archive: apiData.no_archive,
            no_image_index: apiData.no_image_index,
            no_snippet: apiData.no_snippet,
            max_snippet: apiData.max_snippet,
            max_video_preview: apiData.max_video_preview,
            max_image_preview: apiData.max_image_preview,
            canonical_url: apiData.canonical_url,
            
            // WordPress specific
            nonce: nonce,
            api_key: apiKey
        };
        
        console.log('📤 Making UPSERT AJAX call with data:', upsertData);
        
        // ✅ Additional debug info
        console.log('🔍 AJAX URL:', typeof aysaParams !== 'undefined' ? aysaParams.ajax_url : ajaxurl);
        console.log('🔍 Nonce being sent:', nonce ? nonce.substring(0, 10) + '...' : 'NONE');
        
        window.jQuery.ajax({
            url: typeof aysaParams !== 'undefined' ? aysaParams.ajax_url : ajaxurl,
            type: 'POST',
            data: upsertData,
            timeout: 30000, // 30 seconds timeout
            success: async function(response) {
                console.log('📥 UPSERT response:', response);
                
                if (response.success) {
                    resolve({
                        success: true,
                        data: response.data,
                        message: response.data.message || 'UPSERT successful'
                    });
                } else {
                    // Check if this is a keyword conflict error from the backend
                    const errorData = response.data;
                    const errorMessage = errorData ? errorData.message || '' : '';
                    
                    // Check for both new format and legacy format from API error
                    const isNewFormatConflict = errorData && errorData.conflict_detected && errorData.conflicting_entities;
                    const isLegacyApiConflict = errorMessage.includes('already associated with other entities') && 
                                               errorMessage.includes('conflictingEntities');
                    
                    if (isNewFormatConflict || isLegacyApiConflict) {
                        console.log('⚠️ Keyword conflict detected via AJAX:', errorData);
                        
                        let conflictEntities = [];
                        let keyword = upsertData.keyword;
                        
                        if (isNewFormatConflict) {
                            // New format - direct access
                            conflictEntities = errorData.conflicting_entities;
                            keyword = errorData.keyword || upsertData.keyword;
                        } else if (isLegacyApiConflict) {
                            // Legacy format - parse from error message
                            try {
                                // Extract JSON from the error message
                                const jsonMatch = errorMessage.match(/\{.*\}/);
                                if (jsonMatch) {
                                    const conflictInfo = JSON.parse(jsonMatch[0]);
                                    conflictEntities = conflictInfo.conflictingEntities || [];
                                    keyword = conflictInfo.message.match(/'([^']+)'/)?.[1] || upsertData.keyword;
                                }
                            } catch (e) {
                                console.warn('Failed to parse conflict info from error message:', e);
                                // Fallback - extract keyword from message
                                const keywordMatch = errorMessage.match(/Keyword '([^']+)'/);
                                keyword = keywordMatch ? keywordMatch[1] : upsertData.keyword;
                                conflictEntities = ['Unknown conflicting entity'];
                            }
                        }
                        
                        // Show modern confirmation dialog with conflict details
                        const conflictEntitiesText = conflictEntities.join('</li><li>');
                        
                        const userConfirmed = await showModernConfirmDialog({
                            title: '⚠️ Keyword Conflict Detected',
                            message: `The keyword <strong>"${keyword}"</strong> is already associated with other entities.`,
                            conflictEntities: conflictEntities,
                            confirmText: 'Move Keyword',
                            cancelText: 'Cancel',
                            type: 'warning'
                        });
                        
                        if (userConfirmed) {
                            console.log('✅ User confirmed keyword override, retrying with ForceOverride=true');
                            
                            // Retry the AJAX call with ForceOverride flag
                            const retryData = { ...upsertData, force_override: true };
                            
                            window.jQuery.ajax({
                                url: typeof aysaParams !== 'undefined' ? aysaParams.ajax_url : ajaxurl,
                                type: 'POST',
                                data: retryData,
                                timeout: 30000,
                                success: function(retryResponse) {
                                    console.log('📥 RETRY UPSERT response:', retryResponse);
                                    
                                    if (retryResponse.success) {
                                        console.log('✅ Keyword conflict resolved - association updated successfully');
                                        // Show success notification
                                        if (typeof showNotification === 'function') {
                                            showNotification(`Keyword "${keyword}" moved successfully! Conflicts resolved.`, 'success');
                                        } else if (typeof showToast === 'function') {
                                            showToast(`Keyword "${keyword}" moved successfully! Conflicts resolved.`, 'success');
                                        }
                                        
                                        resolve({
                                            success: true,
                                            data: retryResponse.data,
                                            message: retryResponse.data.message || 'UPSERT successful with conflict resolution'
                                        });
                                    } else {
                                        resolve({
                                            success: false,
                                            error: retryResponse.data ? retryResponse.data.message : 'RETRY UPSERT failed',
                                            response: retryResponse
                                        });
                                    }
                                },
                                error: function(xhr, status, error) {
                                    console.error('❌ RETRY UPSERT AJAX error:', error, xhr.responseText);
                                    resolve({
                                        success: false,
                                        error: 'RETRY AJAX error: ' + error,
                                        status: status,
                                        responseText: xhr.responseText
                                    });
                                }
                            });
                        } else {
                            console.log('❌ User cancelled keyword override');
                            // Show cancellation notification
                            if (typeof showNotification === 'function') {
                                showNotification(`Association cancelled. Keyword "${keyword}" remains with existing entities.`, 'info');
                            } else if (typeof showToast === 'function') {
                                showToast(`Association cancelled. Keyword "${keyword}" remains with existing entities.`, 'info');
                            }
                            
                            resolve({
                                success: false,
                                error: 'User cancelled keyword association due to conflicts',
                                response: response,
                                user_cancelled: true
                            });
                        }
                    } else {
                        // Regular error handling for non-conflict errors
                        resolve({
                            success: false,
                            error: response.data ? response.data.message : 'UPSERT failed',
                            response: response
                        });
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('❌ UPSERT AJAX error:', error, xhr.responseText);
                resolve({
                    success: false,
                    error: 'AJAX error: ' + error,
                    status: status,
                    responseText: xhr.responseText
                });
            }
        });
    });
}

/**
 * ✅ NEW: Make INSERT MANY call to AYSA API for secondary keywords
 */
async function makeInsertManyCall(entityId, entityType, secondaryKeywords, projectId, apiKey, apiData = null) {
    return new Promise((resolve, reject) => {
        if (!window.jQuery) {
            resolve({ success: false, error: 'jQuery not available' });
            return;
        }
        
        // ✅ Better nonce handling with debug
        let nonce = '';
        if (typeof aysaParams !== 'undefined' && aysaParams.nonce) {
            nonce = aysaParams.nonce;
            console.log('✅ Using aysaParams nonce for INSERT MANY:', nonce.substring(0, 10) + '...');
        } else {
            console.warn('⚠️ aysaParams not available for INSERT MANY, trying alternative nonce sources');
            
            // Try to get nonce from other sources
            const metaboxNonce = document.querySelector('input[name="aysa_metabox_nonce"]');
            const wpNonce = document.querySelector('#_wpnonce');
            
            if (metaboxNonce) {
                nonce = metaboxNonce.value;
                console.log('✅ Using metabox nonce for INSERT MANY:', nonce.substring(0, 10) + '...');
            } else if (wpNonce) {
                nonce = wpNonce.value;
                console.log('✅ Using WordPress nonce for INSERT MANY:', nonce.substring(0, 10) + '...');
            } else {
                console.error('❌ No nonce found anywhere for INSERT MANY!');
            }
        }
        
        const insertManyData = {
            action: 'aysa_insert_many_keywords', // WordPress AJAX action
            entity_id: entityId,
            entity_type: entityType,
            project_id: projectId,
            secondary_keywords: secondaryKeywords,
            
            // ✅ Include SEO and Advanced settings if available
            ...(apiData && {
                // SEO SETTINGS
                targeted_search_engine: apiData.targeted_search_engine,
                targeted_country: apiData.targeted_country,
                targeted_region: apiData.targeted_region,
                targeted_city: apiData.targeted_city,
                update_frequency: apiData.update_frequency,
                language_optimize: apiData.language_optimize,
                device_optimize: apiData.device_optimize,
                
                // ADVANCED
                index: apiData.index,
                no_follow: apiData.no_follow,
                no_archive: apiData.no_archive,
                no_image_index: apiData.no_image_index,
                no_snippet: apiData.no_snippet,
                max_snippet: apiData.max_snippet,
                max_video_preview: apiData.max_video_preview,
                max_image_preview: apiData.max_image_preview,
                canonical_url: apiData.canonical_url,
                
                // TRACKING
                track: apiData.track
            }),
            
            nonce: nonce,
            api_key: apiKey
        };
        
        console.log('📤 Making INSERT MANY AJAX call with data:', insertManyData);
        console.log('🔍 INSERT MANY nonce being sent:', nonce ? nonce.substring(0, 10) + '...' : 'NONE');
        
        window.jQuery.ajax({
            url: typeof aysaParams !== 'undefined' ? aysaParams.ajax_url : ajaxurl,
            type: 'POST',
            data: insertManyData,
            timeout: 30000, // 30 seconds timeout
            success: function(response) {
                console.log('📥 INSERT MANY response:', response);
                
                if (response.success) {
                    resolve({
                        success: true,
                        data: response.data,
                        message: response.data.message || 'INSERT MANY successful',
                        keywords_processed: secondaryKeywords.length
                    });
                } else {
                    // Check if this is a keyword conflict error for secondary keywords
                    const errorData = response.data;
                    if (errorData && errorData.conflicts_detected && errorData.conflicting_keywords) {
                        console.log('⚠️ Secondary keyword conflicts detected via AJAX:', errorData);
                        
                        // For secondary keywords, show a warning but don't block the process
                        const conflictKeywords = errorData.conflicting_keywords.join(', ');
                        const warningMessage = `⚠️ Some secondary keywords have conflicts:\n\n${conflictKeywords}\n\nThese conflicts were automatically resolved by moving the keywords to the current entity.`;
                        
                        // Show warning but continue
                        if (typeof showNotification === 'function') {
                            showNotification(`Secondary keywords conflicts resolved: ${conflictKeywords}`, 'warning');
                        } else if (typeof showToast === 'function') {
                            showToast(`Secondary keywords conflicts resolved: ${conflictKeywords}`, 'warning');
                        }
                        
                        // Treat as success since conflicts were automatically resolved
                        resolve({
                            success: true,
                            data: response.data,
                            message: 'INSERT MANY successful with automatic conflict resolution',
                            keywords_processed: secondaryKeywords.length,
                            conflicts_resolved: true
                        });
                    } else {
                        // Regular error handling for non-conflict errors
                        resolve({
                            success: false,
                            error: response.data ? response.data.message : 'INSERT MANY failed',
                            response: response
                        });
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('❌ INSERT MANY AJAX error:', error, xhr.responseText);
                resolve({
                    success: false,
                    error: 'AJAX error: ' + error,
                    status: status,
                    responseText: xhr.responseText
                });
            }
        });
    });
}

// Include other functionality files
// These would typically be included via import in modern JS
// or via enqueuing in WordPress
// For this demo, assume these functions are defined elsewhere
// and included in the final script 

// ✅ DEBUGGING: Test simple AJAX call
function testAjaxConnection() {
    console.log('🧪 TESTING: Making simple AJAX test call...');
    
    jQuery.ajax({
        url: aysaParams.ajax_url,
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'aysa_save_seo_data',
            nonce: aysaParams.nonce,
            entity_id: 123,
            entity_type: 'test',
            meta_title: 'test_value'
        },
        success: function(response) {
            console.log('🧪 AJAX TEST: Success response:', response);
        },
        error: function(xhr, status, error) {
            console.error('🧪 AJAX TEST: Error occurred');
            console.error('🧪 Status:', status);
            console.error('🧪 Error:', error);
            console.error('🧪 Response Text:', xhr.responseText);
            console.error('🧪 Status Code:', xhr.status);
        }
    });
}

// ✅ Call test function on page load
jQuery(document).ready(function() {
    console.log('🧪 Page loaded, running AJAX test in 2 seconds...');
    setTimeout(testAjaxConnection, 2000);
});

/**
 * Initialize new SEO generator classes alongside existing functionality
 * This function demonstrates how to integrate the new classes without removing existing code
 */
function initializeNewSeoGeneratorClasses() {
    console.log('🚀 Initializing new SEO generator classes...');
    
    // Check if the new classes are available
    if (typeof AysaSeoGenerator === 'undefined' || typeof AysaSeoIntegration === 'undefined') {
        console.log('🚀 New SEO generator classes not loaded yet, will retry...');
        // Retry after a delay to allow scripts to load
        setTimeout(initializeNewSeoGeneratorClasses, 1000);
        return;
    }
    
    try {
        // Determine entity type based on current page
        const entityType = getEntityTypeForNewGenerator();
        
        if (!entityType) {
            console.log('🚀 Entity type not recognized for new SEO generator');
            return;
        }
        
        console.log(`🚀 Initializing new SEO generator for entity type: ${entityType}`);
        
        // Create integration instance
        const seoIntegration = new AysaSeoIntegration();
        
        // Store reference globally for cleanup if needed
        window.aysaNewSeoIntegration = seoIntegration;
        
        // Add a toggle button to switch between old and new generators
        addGeneratorToggleButton(seoIntegration, entityType);
        
        // Initialize the new generator (but don't override existing functionality)
        const integrationId = seoIntegration.initializeMetaboxIntegration({
            buttonSelector: '.aysa-generate-suggestions-new', // Different selector to avoid conflicts
            entityType: entityType,
            callbacks: {
                onProgress: (message) => {
                    console.log(`🚀 New SEO Progress: ${message}`);
                    // Show progress in existing UI if available
                    if (typeof showToast === 'function') {
                        showToast(`New Generator: ${message}`, 'info');
                    }
                },
                onSuccess: (results) => {
                    console.log('🚀 New SEO generation completed:', results);
                    
                    // Add revert buttons for the new generator
                    addRevertButtonsForNewGenerator(seoIntegration, entityType);
                    
                    // Show success message
                    if (typeof showToast === 'function') {
                        showToast('SEO suggestions generated successfully with new generator!', 'success');
                    }
                    
                    // Trigger versioning if available
                    if (window.aysaVersioningService && typeof window.aysaVersioningService.logSeoSuggestions === 'function') {
                        try {
                            window.aysaVersioningService.logSeoSuggestions({
                                entityType: entityType,
                                suggestions: results,
                                timestamp: new Date().toISOString(),
                                generator: 'new'
                            });
                        } catch (error) {
                            console.warn('🚀 New generator versioning failed:', error);
                        }
                    }
                },
                onError: (error) => {
                    console.error('🚀 New SEO generation failed:', error);
                    if (typeof showToast === 'function') {
                        showToast(`New generator failed: ${error.message}`, 'error');
                    }
                },
                onComplete: () => {
                    console.log('🚀 New SEO generation completed (success or failure)');
                }
            }
        });
        
        // Store integration ID for cleanup
        window.aysaNewSeoIntegrationId = integrationId;
        
        console.log('🚀 New SEO generator classes initialized successfully');
        
    } catch (error) {
        console.error('🚀 Failed to initialize new SEO generator classes:', error);
    }
}

/**
 * Determine entity type for the new generator based on current page
 */
function getEntityTypeForNewGenerator() {
    // Check for product page
    if (document.querySelector('#product-type') || 
        document.querySelector('.post-type-product') ||
        document.querySelector('body.post-type-product')) {
        return 'Product';
    }
    
    // Check for category page
    if (document.querySelector('#edittag') || 
        document.querySelector('.taxonomy-product_cat') ||
        document.querySelector('body.taxonomy-product_cat')) {
        return 'Category';
    }
    
    // Check for page
    if (document.querySelector('.post-type-page') ||
        document.querySelector('body.post-type-page')) {
        return 'Page';
    }
    
    // Check for post
    if (document.querySelector('.post-type-post') ||
        document.querySelector('body.post-type-post')) {
        return 'Post';
    }
    
    return null;
}

/**
 * Add a toggle button to switch between old and new SEO generators
 */
function addGeneratorToggleButton(seoIntegration, entityType) {
    // Find the existing generate button
    const existingButton = document.querySelector('.aysa-generate-suggestions');
    if (!existingButton) {
        console.log('🚀 Existing generate button not found, cannot add toggle');
        return;
    }
    
    // Create container for both buttons
    const buttonContainer = document.createElement('div');
    buttonContainer.className = 'aysa-generator-buttons';
    buttonContainer.style.cssText = 'display: flex; gap: 10px; align-items: center; margin-top: 10px;';
    
    // Clone the existing button for the new generator
    const newButton = existingButton.cloneNode(true);
    newButton.className = 'aysa-generate-suggestions-new button button-primary';
    newButton.textContent = 'Generate SEO (New)';
    newButton.style.backgroundColor = '#00a32a';
    
    // Create toggle switch
    const toggleContainer = document.createElement('div');
    toggleContainer.style.cssText = 'display: flex; align-items: center; gap: 5px; margin-left: 10px;';
    
    const toggleLabel = document.createElement('label');
    toggleLabel.textContent = 'Use New Generator:';
    toggleLabel.style.fontSize = '12px';
    
    const toggleSwitch = document.createElement('input');
    toggleSwitch.type = 'checkbox';
    toggleSwitch.id = 'aysa-generator-toggle';
    
    // Add info button
    const infoButton = document.createElement('button');
    infoButton.type = 'button';
    infoButton.className = 'button button-small';
    infoButton.textContent = '?';
    infoButton.title = 'Click to see the differences between generators';
    infoButton.style.cssText = 'width: 24px; height: 24px; padding: 0; margin-left: 5px;';
    
    infoButton.onclick = () => {
        const message = `
SEO Generator Comparison:

🔵 Original Generator:
• Proven, stable implementation
• Full integration with existing workflow
• All current features and validations

🟢 New Generator (Experimental):
• Modular, reusable class-based approach
• Enhanced error handling and timeouts
• Better progress feedback
• Designed for future extensibility
• Can be used in other contexts (like optimization schedule)

Both generators use the same APIs and produce similar results.
The new generator is designed to eventually replace the original while maintaining compatibility.`;
        
        alert(message);
    };
    
    // Handle toggle change
    let useNewGenerator = false;
    toggleSwitch.onchange = () => {
        useNewGenerator = toggleSwitch.checked;
        
        if (useNewGenerator) {
            existingButton.style.display = 'none';
            newButton.style.display = 'inline-block';
            toggleLabel.style.color = '#00a32a';
            toggleLabel.style.fontWeight = 'bold';
        } else {
            existingButton.style.display = 'inline-block';
            newButton.style.display = 'none';
            toggleLabel.style.color = '';
            toggleLabel.style.fontWeight = '';
        }
    };
    
    // Initially hide the new button
    newButton.style.display = 'none';
    
    // Assemble toggle container
    toggleContainer.appendChild(toggleLabel);
    toggleContainer.appendChild(toggleSwitch);
    toggleContainer.appendChild(infoButton);
    
    // Insert the new button and toggle after the existing button
    existingButton.parentNode.insertBefore(buttonContainer, existingButton.nextSibling);
    buttonContainer.appendChild(newButton);
    buttonContainer.appendChild(toggleContainer);
    
    console.log('🚀 Generator toggle button added successfully');
}

/**
 * Add revert buttons specifically for the new generator
 */
function addRevertButtonsForNewGenerator(seoIntegration, entityType) {
    // Add revert buttons to appropriate fields based on entity type
    switch (entityType) {
        case 'Product':
            seoIntegration.addRevertButtons('content', entityType);
            seoIntegration.addRevertButtons('excerpt', entityType);
            break;
            
        case 'Category':
            seoIntegration.addRevertButtons('description', entityType);
            break;
            
        case 'Page':
        case 'Post':
            seoIntegration.addRevertButtons('content', entityType);
            break;
    }
    
    // Add a note about the new generator's revert functionality
    const noteContainer = document.createElement('div');
    noteContainer.className = 'aysa-new-generator-note';
    noteContainer.style.cssText = 'margin-top: 10px; padding: 8px; background: #e7f3ff; border-left: 3px solid #00a32a; font-size: 12px;';
    noteContainer.innerHTML = `
        <strong>New Generator Features:</strong>
        • Enhanced revert functionality with session storage backup
        • Better error handling and partial failure recovery
        • Improved progress tracking and user feedback
    `;
    
    // Find a good place to insert the note
    const metaboxContent = document.querySelector('.aysa-metabox-content') || 
                          document.querySelector('#aysa-metabox') ||
                          document.querySelector('.aysa-generate-suggestions')?.parentNode;
    
    if (metaboxContent) {
        metaboxContent.appendChild(noteContainer);
        
        // Auto-remove the note after 10 seconds
        setTimeout(() => {
            if (noteContainer.parentNode) {
                noteContainer.parentNode.removeChild(noteContainer);
            }
        }, 10000);
    }
}

/**
 * Create a custom SEO generator for use in other contexts (like optimization schedule)
 * This demonstrates how the new classes can be used outside of the metabox
 */
function createCustomSeoGeneratorForSchedule() {
    if (typeof AysaSeoIntegration === 'undefined') {
        console.warn('🚀 AysaSeoIntegration not available for custom generator');
        return null;
    }
    
    const seoIntegration = new AysaSeoIntegration();
    
    // Create a custom generator function
    const customGenerator = seoIntegration.createCustomGenerator({
        defaultTimeout: 15000, // Shorter timeout for schedule
        onProgress: (message) => {
            console.log(`🚀 Schedule SEO Progress: ${message}`);
        },
        onError: (error) => {
            console.error(`🚀 Schedule SEO Error: ${error.message}`);
        }
    });
    
    // Return a function that can be used by the optimization schedule
    return async function generateForSchedule(keyword, entityType, associationId) {
        try {
            console.log(`🚀 Generating SEO for schedule: ${keyword} (${entityType})`);
            
            const results = await customGenerator({
                entityId: associationId,
                entityType: entityType,
                keyword: keyword,
                entityName: keyword, // Use keyword as entity name for schedule
                language: 'en',
                websiteName: 'WordPress'
            });
            
            // Return formatted results for the schedule table
            return {
                keyword: keyword,
                entityType: entityType,
                metaTitle: results.metaTitle || `${keyword} | WordPress`,
                metaDescription: results.metaDescription || `Discover ${keyword} and related content.`,
                status: 'Generated',
                timestamp: new Date().toLocaleString(),
                generator: 'new'
            };
            
        } catch (error) {
            console.error('🚀 Schedule SEO generation failed:', error);
            
            // Return fallback data
            return {
                keyword: keyword,
                entityType: entityType,
                metaTitle: `${keyword} | WordPress`,
                metaDescription: `Discover ${keyword} and related content.`,
                status: 'Failed',
                timestamp: new Date().toLocaleString(),
                error: error.message,
                generator: 'new'
            };
        }
    };
}

// Make the custom generator available globally for use in optimization schedule
if (typeof window !== 'undefined') {
    window.createCustomSeoGeneratorForSchedule = createCustomSeoGeneratorForSchedule;
}

/**
 * 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');
                        } else if (typeof showToast === 'function') {
                            showToast(`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');
                    } else if (typeof showToast === 'function') {
                        showToast(`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;
    }
}

/**
 * Show a modern confirmation dialog with beautiful styling
 * @param {Object} options - Dialog options
 * @param {string} options.title - Dialog title
 * @param {string} options.message - Main message
 * @param {Array} options.conflictEntities - List of conflicting entities
 * @param {string} options.confirmText - Confirm button text
 * @param {string} options.cancelText - Cancel button text
 * @param {string} options.type - Dialog type (warning, error, info)
 * @returns {Promise<boolean>} - User confirmation result
 */
function showModernConfirmDialog(options) {
    return new Promise((resolve) => {
        // Create modal HTML
        const modalId = 'aysa-conflict-modal';
        const modalHTML = `
            <div id="${modalId}" class="aysa-modal-overlay">
                <div class="aysa-modal-container">
                    <div class="aysa-modal-header ${options.type}">
                        <div class="aysa-modal-icon">
                            ${options.type === 'warning' ? '⚠️' : options.type === 'error' ? '❌' : 'ℹ️'}
                        </div>
                        <h3 class="aysa-modal-title">${options.title}</h3>
                    </div>
                    
                    <div class="aysa-modal-body">
                        <p class="aysa-modal-message">${options.message}</p>
                        
                        ${options.conflictEntities && options.conflictEntities.length > 0 ? `
                            <div class="aysa-conflict-details">
                                <p><strong>Conflicting entities:</strong></p>
                                <ul class="aysa-conflict-list">
                                    ${options.conflictEntities.map(entity => `<li>${entity}</li>`).join('')}
                                </ul>
                            </div>
                        ` : ''}
                        
                        <div class="aysa-modal-warning">
                            <strong>⚠️ Warning:</strong> This will remove the keyword from the conflicting entities and move it to the current entity.
                        </div>
                    </div>
                    
                    <div class="aysa-modal-footer">
                        <button type="button" class="aysa-modal-btn aysa-btn-cancel">
                            ${options.cancelText || 'Cancel'}
                        </button>
                        <button type="button" class="aysa-modal-btn aysa-btn-confirm">
                            ${options.confirmText || 'Confirm'}
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        // Add modal styles if not already added
        if (!document.getElementById('aysa-modal-styles')) {
            const styles = `
                <style id="aysa-modal-styles">
                    .aysa-modal-overlay {
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background: rgba(0, 0, 0, 0.6);
                        backdrop-filter: blur(4px);
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        z-index: 999999;
                        opacity: 0;
                        animation: aysa-modal-fade-in 0.3s ease-out forwards;
                    }
                    
                    @keyframes aysa-modal-fade-in {
                        to { opacity: 1; }
                    }
                    
                    .aysa-modal-container {
                        background: #fff;
                        border-radius: 12px;
                        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
                        max-width: 500px;
                        width: 90%;
                        max-height: 80vh;
                        overflow: hidden;
                        transform: translateY(-20px) scale(0.95);
                        animation: aysa-modal-slide-in 0.3s ease-out 0.1s forwards;
                    }
                    
                    @keyframes aysa-modal-slide-in {
                        to { 
                            transform: translateY(0) scale(1); 
                        }
                    }
                    
                    .aysa-modal-header {
                        padding: 24px 24px 16px;
                        border-bottom: 1px solid #e8e8e8;
                        display: flex;
                        align-items: center;
                        gap: 12px;
                    }
                    
                    .aysa-modal-header.warning {
                        background: linear-gradient(135deg, #fff3cd 0%, #fef7e3 100%);
                        border-bottom-color: #f0c674;
                    }
                    
                    .aysa-modal-header.error {
                        background: linear-gradient(135deg, #f8d7da 0%, #fde8ea 100%);
                        border-bottom-color: #f5c6cb;
                    }
                    
                    .aysa-modal-icon {
                        font-size: 24px;
                        flex-shrink: 0;
                    }
                    
                    .aysa-modal-title {
                        margin: 0;
                        font-size: 18px;
                        font-weight: 600;
                        color: #333;
                        line-height: 1.3;
                    }
                    
                    .aysa-modal-body {
                        padding: 24px;
                    }
                    
                    .aysa-modal-message {
                        margin: 0 0 16px;
                        font-size: 14px;
                        line-height: 1.5;
                        color: #555;
                    }
                    
                    .aysa-conflict-details {
                        background: #f8f9fa;
                        border: 1px solid #e9ecef;
                        border-radius: 8px;
                        padding: 16px;
                        margin: 16px 0;
                    }
                    
                    .aysa-conflict-details p {
                        margin: 0 0 8px;
                        font-size: 13px;
                        color: #666;
                    }
                    
                    .aysa-conflict-list {
                        margin: 0;
                        padding-left: 20px;
                        list-style: none;
                    }
                    
                    .aysa-conflict-list li {
                        position: relative;
                        padding: 4px 0;
                        font-size: 13px;
                        color: #444;
                    }
                    
                    .aysa-conflict-list li:before {
                        content: "•";
                        color: #ff6b6b;
                        font-weight: bold;
                        position: absolute;
                        left: -16px;
                    }
                    
                    .aysa-modal-warning {
                        background: #fff3cd;
                        border: 1px solid #f0c674;
                        border-radius: 6px;
                        padding: 12px;
                        margin-top: 16px;
                        font-size: 13px;
                        color: #856404;
                    }
                    
                    .aysa-modal-footer {
                        padding: 16px 24px 24px;
                        display: flex;
                        gap: 12px;
                        justify-content: flex-end;
                    }
                    
                    .aysa-modal-btn {
                        padding: 10px 20px;
                        border: none;
                        border-radius: 6px;
                        font-size: 13px;
                        font-weight: 500;
                        cursor: pointer;
                        transition: all 0.2s ease;
                        text-transform: none;
                        min-width: 80px;
                    }
                    
                    .aysa-btn-cancel {
                        background: #f8f9fa;
                        color: #6c757d;
                        border: 1px solid #dee2e6;
                    }
                    
                    .aysa-btn-cancel:hover {
                        background: #e9ecef;
                        border-color: #adb5bd;
                        transform: translateY(-1px);
                    }
                    
                    .aysa-btn-confirm {
                        background: #ff6b6b;
                        color: white;
                        box-shadow: 0 2px 4px rgba(255, 107, 107, 0.3);
                    }
                    
                    .aysa-btn-confirm:hover {
                        background: #ff5252;
                        transform: translateY(-1px);
                        box-shadow: 0 4px 8px rgba(255, 107, 107, 0.4);
                    }
                    
                    .aysa-btn-confirm:active {
                        transform: translateY(0);
                    }
                </style>
            `;
            document.head.insertAdjacentHTML('beforeend', styles);
        }
        
        // Add modal to DOM
        document.body.insertAdjacentHTML('beforeend', modalHTML);
        
        const modal = document.getElementById(modalId);
        const confirmBtn = modal.querySelector('.aysa-btn-confirm');
        const cancelBtn = modal.querySelector('.aysa-btn-cancel');
        
        // Handle clicks
        const handleConfirm = () => {
            closeModal();
            resolve(true);
        };
        
        const handleCancel = () => {
            closeModal();
            resolve(false);
        };
        
        const closeModal = () => {
            modal.style.animation = 'aysa-modal-fade-in 0.2s ease-in reverse';
            setTimeout(() => {
                if (modal.parentNode) {
                    modal.parentNode.removeChild(modal);
                }
            }, 200);
        };
        
        // Event listeners
        confirmBtn.addEventListener('click', handleConfirm);
        cancelBtn.addEventListener('click', handleCancel);
        
        // Close on overlay click
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                handleCancel();
            }
        });
        
        // Close on Escape key
        const handleKeyPress = (e) => {
            if (e.key === 'Escape') {
                handleCancel();
                document.removeEventListener('keydown', handleKeyPress);
            } else if (e.key === 'Enter') {
                handleConfirm();
                document.removeEventListener('keydown', handleKeyPress);
            }
        };
        
        document.addEventListener('keydown', handleKeyPress);
        
        // Focus the confirm button
        setTimeout(() => {
            confirmBtn.focus();
        }, 300);
    });
}

// ✅ CRITICAL: Initialize the post update handler when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    console.log('🔍 AYSA metabox: DOM ready, initializing post update handler...');
    
    // Only setup for post/page edit screens
    if (window.location.href.includes('post.php') || window.location.href.includes('post-new.php')) {
        console.log('🔍 AYSA metabox: Detected post/page edit screen, setting up handler...');
        setupPostUpdateHandler();
    } else {
        console.log('🔍 AYSA metabox: Not a post/page edit screen, skipping setup');
    }
});
