/**
 * AYSA Keywords Management
 * Functions for handling keywords in the 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';
}

/**
 * Initialize keyword management
 */
function initKeywordManagement() {
    // Skip initialization if we're in WordPress form submission mode
    if (window.aysaBypassValidation === true) {
        console.log('Skipping AYSA keyword management initialization due to WordPress form submission');
        return;
    }
    
    // Find WordPress form elements
    const wordpressSubmitButton = document.querySelector('#submit, input[name="submit"]');
    if (wordpressSubmitButton) {
        // Add a click handler to bypass AYSA validation on WordPress submit
        wordpressSubmitButton.addEventListener('click', function(e) {
            console.log('WordPress submit button clicked, bypassing AYSA validation');
            window.aysaBypassValidation = true;
        });
    }
    
    // Check if we're in a new entity creation mode
    const entityId = getEntityId();
    const isNewEntity = (entityId === 0);
    
    // Get entity name if available (for new entities)
    let entityName = '';
    const entityType = getEntityTypeGood();
    if (entityType === 'Product' || entityType === 'Page') {
        entityName = document.getElementById('title')?.value || '';
    } else {
        entityName = document.getElementById('name')?.value || '';
    }
    
    // For new entities, prefill keyword with entity name if available
    if (isNewEntity && entityName) {
        const keywordInput = document.getElementById('aysa-entity-keyword');
        if (keywordInput && !keywordInput.value) {
            // Only set if the field is empty
            keywordInput.value = entityName;
        }
    }
    
    // Setup secondary keywords container
    setupSecondaryKeywordsTags();
    
    // Only load keywords from API for existing entities (not new ones)
    if (entityId !== 0) {
        // Load keywords from API only for existing entities
        loadKeywordsFromApi();
    }
    
    // Setup dropdown for keyword selection
    setupKeywordDropdown();
    
    // Bind keyword event listeners
    bindKeywordEventListeners();
    
    // Add a listener to sync the entity name with the keyword field for new entities
    if (isNewEntity) {
        const nameInput = document.getElementById('name') || document.getElementById('title');
        const keywordInput = document.getElementById('aysa-entity-keyword');
        
        if (nameInput && keywordInput) {
            // Add listener to update keyword when name changes (if keyword is still empty)
            nameInput.addEventListener('input', function() {
                // Don't overwrite existing keywords that the user has manually entered
                if (!keywordInput.value || keywordInput.value === nameInput.value.trim()) {
                    keywordInput.value = nameInput.value.trim();
                }
            });
        }
    }
    
    // Ensure WordPress form submission still works
    const wordpressForm = document.querySelector('#addtag, #edittag');
    if (wordpressForm) {
        console.log('Found WordPress form, ensuring normal submission works');
        
        // Make sure submit works normally
        const originalSubmit = wordpressForm.onsubmit;
        wordpressForm.onsubmit = function(e) {
            // Set bypass flag
            window.aysaBypassValidation = true;
            
            // Continue with WordPress processing
            return originalSubmit ? originalSubmit.call(this, e) : true;
        };
    }
}

/**
 * Set up the secondary keywords tags container
 */
function setupSecondaryKeywordsTags() {
    const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
    const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
    
    if (!secondaryKeywordInput || !secondaryKeywordsContainer) {
        console.log('Secondary keywords elements not found');
        return;
    }
    
    // Initial render of existing tags
    renderSecondaryKeywordTags();
}

/**
 * Render the secondary keywords as tags
 */
function renderSecondaryKeywordTags() {
    const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
    const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
    
    if (!secondaryKeywordInput || !secondaryKeywordsContainer) return;
    
    // Clear the container
    secondaryKeywordsContainer.innerHTML = '';
    
    // Get the current secondary keywords
    const secondaryKeywordsValue = secondaryKeywordInput.value;
    if (!secondaryKeywordsValue) return;
    
    // Split into array, trim each keyword, and filter out empty entries
    const secondaryKeywords = secondaryKeywordsValue.split(',')
        .map(keyword => keyword.trim())
        .filter(keyword => keyword !== '');
    
    // Create a tag for each keyword
    secondaryKeywords.forEach(keyword => {
        createKeywordTag(keyword);
    });
}

// Add functions to window object to make them globally accessible
window.renderSecondaryKeywordTags = renderSecondaryKeywordTags;
window.initKeywordManagement = initKeywordManagement;
window.removeKeywordTag = removeKeywordTag;
window.customConfirm = customConfirm;
window.loadKeywordsFromApi = loadKeywordsFromApi;

/**
 * Create a keyword tag
 * @param {string} keyword - The keyword text
 * @param {string|null} associationId - Optional association ID
 * @param {boolean} isTracked - Whether the keyword is tracked
 */
function createKeywordTag(keyword, associationId = null, isTracked = false) {
    const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
    if (!secondaryKeywordsContainer) return;
    
    const tag = document.createElement('div');
    tag.className = 'keyword-tag';
    if (isTracked) {
        tag.classList.add('is-tracked');
    }
    tag.innerHTML = `
        <span class="tag-text">${keyword}</span>
        ${isTracked ? '<span class="track-icon" title="Tracked">📊</span>' : ''}
        <span class="tag-remove">×</span>
    `;
    
    // Store the association ID if available
    if (associationId) {
        tag.dataset.associationId = associationId;
    }
    
    // Store tracking status
    tag.dataset.isTracked = isTracked ? 'true' : 'false';
    
    // Add click event to show context menu
    tag.querySelector('.tag-text').addEventListener('click', function(e) {
        e.stopPropagation();
        showKeywordContextMenu(e, keyword, tag);
    });
    
    // Add click event to remove the tag
    tag.querySelector('.tag-remove').addEventListener('click', function(e) {
        e.stopPropagation();
        removeKeywordTag(tag, keyword);
    });
    
    // Add to container
    secondaryKeywordsContainer.appendChild(tag);
}

/**
 * Show a modern toast notification
 * @param {string} message - The message to show
 * @param {string} type - The type of notification (success, error, warning, info)
 * @param {number} duration - Duration in milliseconds
 */
function showToast(message, type = 'info', duration = 3000) {
    console.log('SHOWING TOAST:', message, type); // DEBUG
    
    // Create container if it doesn't exist
    let container = document.getElementById('aysa-toast-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'aysa-toast-container';
        container.style.position = 'fixed';
        container.style.top = '20px';
        container.style.right = '20px';
        container.style.zIndex = '9999';
        container.style.display = 'flex';
        container.style.flexDirection = 'column';
        container.style.alignItems = 'flex-end';
        container.style.gap = '10px';
        document.body.appendChild(container);
        console.log('Created toast container'); // DEBUG
    }
    
    // Create toast element
    const toast = document.createElement('div');
    toast.className = `aysa-toast aysa-toast-${type}`;
    toast.style.minWidth = '250px';
    toast.style.maxWidth = '350px';
    toast.style.padding = '12px 16px';
    toast.style.borderRadius = '4px';
    toast.style.boxShadow = '0 3px 6px rgba(0,0,0,0.16)';
    toast.style.marginBottom = '10px';
    toast.style.fontSize = '14px';
    toast.style.animation = 'aysa-toast-in 0.3s ease, aysa-toast-out 0.3s ease forwards';
    toast.style.animationDelay = '0s, ' + (duration - 300) + 'ms';
    toast.style.display = 'flex';
    toast.style.alignItems = 'center';
    toast.style.justifyContent = 'space-between';
    
    // Set styles based on type
    switch (type) {
        case 'success':
            toast.style.backgroundColor = '#d4edda';
            toast.style.color = '#155724';
            toast.style.borderLeft = '4px solid #28a745';
            break;
        case 'error':
            toast.style.backgroundColor = '#f8d7da';
            toast.style.color = '#721c24';
            toast.style.borderLeft = '4px solid #dc3545';
            break;
        case 'warning':
            toast.style.backgroundColor = '#fff3cd';
            toast.style.color = '#856404';
            toast.style.borderLeft = '4px solid #ffc107';
            break;
        default: // info
            toast.style.backgroundColor = '#d1ecf1';
            toast.style.color = '#0c5460';
            toast.style.borderLeft = '4px solid #17a2b8';
            break;
    }
    
    // Add icon based on type
    let icon = '';
    switch (type) {
        case 'success':
            icon = '✓';
            break;
        case 'error':
            icon = '✕';
            break;
        case 'warning':
            icon = '!';
            break;
        default: // info
            icon = 'i';
            break;
    }
    
    // Create message content
    const content = document.createElement('div');
    content.style.flex = '1';
    content.innerHTML = `<strong>${icon}</strong> ${message}`;
    
    // Create close button
    const closeBtn = document.createElement('button');
    closeBtn.innerHTML = '×';
    closeBtn.style.background = 'none';
    closeBtn.style.border = 'none';
    closeBtn.style.color = 'inherit';
    closeBtn.style.fontSize = '18px';
    closeBtn.style.marginLeft = '10px';
    closeBtn.style.cursor = 'pointer';
    closeBtn.style.padding = '0';
    closeBtn.style.lineHeight = '1';
    closeBtn.onclick = function() {
        container.removeChild(toast);
    };
    
    // Add content and close button to toast
    toast.appendChild(content);
    toast.appendChild(closeBtn);
    
    // Add toast to container
    container.appendChild(toast);
    console.log('Added toast to container'); // DEBUG
    
    // Add animation styles if not already added
    if (!document.getElementById('aysa-toast-styles')) {
        const styleSheet = document.createElement('style');
        styleSheet.id = 'aysa-toast-styles';
        styleSheet.textContent = `
            @keyframes aysa-toast-in {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes aysa-toast-out {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(styleSheet);
        console.log('Added toast animation styles'); // DEBUG
    }
    
    // Remove toast after duration
    setTimeout(() => {
        if (container.contains(toast)) {
            container.removeChild(toast);
        }
    }, duration);
    
    return toast;
}

/**
 * Custom confirm dialog instead of browser alert
 * @param {string} message - The confirmation message
 * @returns {Promise<boolean>} - Resolves to true if confirmed, false if canceled
 */
function customConfirm(message) {
    return new Promise((resolve) => {
        // Create modal backdrop
        const backdrop = document.createElement('div');
        backdrop.style.position = 'fixed';
        backdrop.style.top = '0';
        backdrop.style.left = '0';
        backdrop.style.right = '0';
        backdrop.style.bottom = '0';
        backdrop.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
        backdrop.style.zIndex = '9998';
        backdrop.style.display = 'flex';
        backdrop.style.alignItems = 'center';
        backdrop.style.justifyContent = 'center';
        
        // Create modal dialog
        const dialog = document.createElement('div');
        dialog.style.backgroundColor = '#fff';
        dialog.style.borderRadius = '6px';
        dialog.style.boxShadow = '0 3px 7px rgba(0, 0, 0, 0.3)';
        dialog.style.padding = '20px';
        dialog.style.maxWidth = '400px';
        dialog.style.width = '100%';
        dialog.style.textAlign = 'center';
        
        // Create message
        const messageEl = document.createElement('p');
        messageEl.textContent = message;
        messageEl.style.marginBottom = '20px';
        messageEl.style.fontSize = '16px';
        
        // Create buttons container
        const buttons = document.createElement('div');
        buttons.style.display = 'flex';
        buttons.style.justifyContent = 'center';
        buttons.style.gap = '10px';
        
        // Create confirm button
        const confirmBtn = document.createElement('button');
        confirmBtn.textContent = 'Confirm';
        confirmBtn.style.backgroundColor = '#dc3545';
        confirmBtn.style.color = '#fff';
        confirmBtn.style.border = 'none';
        confirmBtn.style.borderRadius = '4px';
        confirmBtn.style.padding = '8px 16px';
        confirmBtn.style.cursor = 'pointer';
        confirmBtn.style.fontSize = '14px';
        
        // Create cancel button
        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = 'Cancel';
        cancelBtn.style.backgroundColor = '#6c757d';
        cancelBtn.style.color = '#fff';
        cancelBtn.style.border = 'none';
        cancelBtn.style.borderRadius = '4px';
        cancelBtn.style.padding = '8px 16px';
        cancelBtn.style.cursor = 'pointer';
        cancelBtn.style.fontSize = '14px';
        
        // Add button events
        confirmBtn.onclick = function() {
            document.body.removeChild(backdrop);
            resolve(true);
        };
        
        cancelBtn.onclick = function() {
            document.body.removeChild(backdrop);
            resolve(false);
        };
        
        // Assemble dialog
        buttons.appendChild(cancelBtn);
        buttons.appendChild(confirmBtn);
        dialog.appendChild(messageEl);
        dialog.appendChild(buttons);
        backdrop.appendChild(dialog);
        
        // Show dialog
        document.body.appendChild(backdrop);
        
        // Focus confirm button
        confirmBtn.focus();
    });
}

/**
 * Remove a keyword tag
 * @param {HTMLElement} tag - The tag element to remove
 * @param {string} keyword - The keyword to remove
 */
function removeKeywordTag(tag, keyword) {
    // CRITICAL DEBUG - VERSION 5.0 (Custom confirm + toast)
    console.log('REMOVE FUNCTION TRIGGERED - V5.0', { 
        keyword: keyword, 
        tag_id: tag.dataset.associationId,
        timestamp: new Date().toISOString() 
    });
    
    const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
    if (!secondaryKeywordInput) return;
    
    // Get current keywords
    const secondaryKeywordsValue = secondaryKeywordInput.value;
    const secondaryKeywords = secondaryKeywordsValue.split(',')
        .map(k => k.trim())
        .filter(k => k !== '');
    
    // Remove the keyword
    const updatedKeywords = secondaryKeywords.filter(k => k !== keyword);
    
    // Update the input value
    secondaryKeywordInput.value = updatedKeywords.join(', ');
    
    // Set tag to loading state first
    tag.style.backgroundColor = '#fff3cd';
    tag.style.borderColor = '#ffeeba';
    tag.style.color = '#856404';
    
    // If we have an association ID, try to delete from API
    if (tag.dataset.associationId) {
        // FORCE DELETE - Critical debug code - Version 5 with custom UI
        const associationId = tag.dataset.associationId;
        console.log('⚠️ FORCING DELETE API CALL FOR ID:', associationId);
        
        // Get project ID from WordPress params or localStorage
        let projectId = 0;
        if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
            projectId = parseInt(aysaParams.project_id);
            console.log('Using project ID from WordPress for deletion:', 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 for deletion:', projectId);
            } else {
                console.warn('No project ID found!');
            }
        }
        
        // Try alternative delete approach - using direct endpoint with API project
        let deleteUrl = `${getAysaApiBaseUrl()}/api/Association/${associationId}`;
        
        // Add projectId parameter if available
        if (projectId > 0) {
            deleteUrl += `?projectId=${projectId}`;
        }
        
        console.log('DEBUG: DELETE URL:', deleteUrl);
        
        // Show custom confirmation dialog
        customConfirm(`Delete keyword "${keyword}"?`).then(confirmed => {
            if (confirmed) {
                showToast(`Deleting keyword "${keyword}"...`, 'info');
                console.log("🔴 Attempting to delete association...");
                
                // Create a new XMLHttpRequest object for more control
                const xhr = new XMLHttpRequest();
                xhr.open('DELETE', deleteUrl);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.setRequestHeader('Accept', '*/*');
                xhr.setRequestHeader('Cache-Control', 'no-cache, no-store');
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                
                // Add event listeners
                xhr.onload = function() {
                    console.log('🟢 XHR RESPONSE:', {
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText
                    });
                    
                    if (xhr.status >= 200 && xhr.status < 300) {
                        console.log('✅ DELETE SUCCESS VIA XHR');
                        tag.remove();
                        showToast(`Successfully deleted keyword "${keyword}"`, 'success');
                    } else {
                        console.error('❌ XHR DELETE ERROR:', xhr.statusText);
                        tag.remove();
                        showToast(`Error deleting keyword (${xhr.status}). Tag removed from UI.`, 'error');
                    }
                };
                
                xhr.onerror = function() {
                    console.error('❌ XHR NETWORK ERROR');
                    tag.remove();
                    showToast('Network error when deleting keyword. Tag removed from UI.', 'error');
                };
                
                // Send with empty body
                xhr.send(JSON.stringify({}));
            } else {
                // User canceled the delete operation
                console.log('Delete operation canceled by user');
                tag.style.backgroundColor = '';
                tag.style.borderColor = '';
                tag.style.color = '';
                showToast('Deletion canceled', 'info');
            }
        });
    } else {
        console.log('No association ID, removing from UI only');
        tag.remove();
        showToast(`Removed "${keyword}" from UI only (no DB record)`, 'warning');
    }
}

/**
 * Set up the keyword dropdown
 */
function setupKeywordDropdown() {
    const keywordDropdown = document.getElementById('keyword-suggestions');
    const mainKeywordInput = document.getElementById('aysa-entity-keyword');
    
    if (!keywordDropdown || !mainKeywordInput) {
        console.log('Keyword dropdown elements not found');
        return;
    }
    
    // Dropdown selection event
    keywordDropdown.addEventListener('change', function() {
        const selectedKeyword = this.value;
        if (selectedKeyword) {
            // Get association ID from the selected option
            const associationId = this.options[this.selectedIndex].dataset.associationId;
            
            // Get project ID from WordPress params instead of 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);
                }
            }
            
            console.log('Selected keyword:', selectedKeyword, 'Association ID:', associationId, 'Project ID:', projectId);
            
            // Check if we have valid association ID
            if (!associationId || isNaN(parseInt(associationId))) {
                console.warn('Missing association ID, trying to recover...');
                loadAssociationIdAndSetMain(selectedKeyword);
            } else {
                // Process the keyword change with the association ID
                processSwitchToMainKeyword(selectedKeyword, associationId, projectId);
            }
        }
    });
}

/**
 * Load association ID and set as main keyword
 * @param {string} keyword - The keyword to set as main
 */
function loadAssociationIdAndSetMain(keyword) {
    // Get entity ID and type
    const entityId = getEntityId();
    const entityType = getEntityTypeGood();
    
    // Get project ID from WordPress params instead of localStorage
    let projectId = 0;
    if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
        projectId = parseInt(aysaParams.project_id);
        console.log('Using project ID from WordPress:', projectId);
    } else {
        // Fallback to localStorage if needed
        const storedProjectId = localStorage.getItem('aysa_project_id');
        if (storedProjectId) {
            projectId = parseInt(storedProjectId);
            console.log('Using project ID from localStorage:', projectId);
        } else {
            console.warn('No project ID found!');
        }
    }
    
    if (entityId === 0 || !projectId) {
        showToast('Cannot set main keyword: Missing entity ID or project ID', 'error');
        return;
    }
    
    // Show loading state
    const keywordDropdown = document.getElementById('keyword-suggestions');
    const container = keywordDropdown.parentNode;
    const loadingIndicator = document.createElement('span');
    loadingIndicator.className = 'spinner is-active';
    loadingIndicator.style.float = 'none';
    loadingIndicator.style.marginLeft = '5px';
    container.appendChild(loadingIndicator);
    
    // Build API URL
    const apiUrl = `${getAysaApiBaseUrl()}/api/Association/GetAllByAssociatedOnAndIdIntern?associatedOn=${encodeURIComponent(entityType)}&idIntern=${entityId}&projectId=${projectId}`;
    
    // Call API to get associations
    fetch(apiUrl, {
        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('API data received:', data);
        
        // Check if we have valid data
        if (!data || (Array.isArray(data) && data.length === 0)) {
            throw new Error('No associations found');
        }
        
        // Convert to array if needed
        const associations = Array.isArray(data) ? data : [data];
        
        // Find the association with the keyword
        const association = associations.find(a => a.keyword === keyword);
        
        if (!association || !association.id) {
            throw new Error('Association not found for keyword: ' + keyword);
        }
        
        // Process the keyword change with the association ID
        processSwitchToMainKeyword(keyword, association.id, projectId);
    })
    .catch(error => {
        console.error('Error loading association ID:', error);
        showToast('Error setting main keyword: ' + error.message, 'error');
        
        // Remove loading indicator
        if (loadingIndicator.parentNode) {
            loadingIndicator.parentNode.removeChild(loadingIndicator);
        }
        
        // Reset dropdown
        keywordDropdown.selectedIndex = 0;
    });
}

/**
 * Process switching to a main keyword
 * @param {string} selectedKeyword - The keyword to set as main
 * @param {string} associationId - The association ID
 * @param {string} projectId - The project ID
 */
function processSwitchToMainKeyword(selectedKeyword, associationId, projectId) {
    if (!projectId || isNaN(parseInt(projectId))) {
        console.error('Invalid project ID:', { projectId });
        showToast('Missing project ID. Please check if you are correctly logged in.', 'error');
        return;
    }

    // Show loading indicator
    const keywordDropdown = document.getElementById('keyword-suggestions');
    const container = keywordDropdown.parentNode;
    const loadingIndicator = document.createElement('span');
    loadingIndicator.className = 'spinner is-active';
    loadingIndicator.style.float = 'none';
    loadingIndicator.style.marginLeft = '5px';
    container.appendChild(loadingIndicator);
    
    // Build URL for setismain
    const url = `${getAysaApiBaseUrl()}/api/Association/setismain/${projectId}/${associationId}`;
    
    // API call
    fetch(url, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Origin': window.location.origin
        },
        mode: 'cors'
    })
    .then(response => {
        console.log('API response:', {
            status: response.status,
            statusText: response.statusText,
            url: response.url
        });
        
        if (!response.ok) {
            return response.text().then(text => {
                console.error('API error:', text);
                throw new Error(`API error: ${response.status}`);
            });
        }
        return response.json();
    })
    .then(data => {
        console.log('API success response:', data);
        
        // Check if we have valid data
        if (!data) {
            console.error('Invalid API response (null or undefined)');
            throw new Error('Invalid response from API.');
        }
        
        // Ensure we're working with an array
        const associations = Array.isArray(data) ? data : [data];
        
        if (associations.length === 0) {
            console.error('API returned an empty array');
            throw new Error('No associations found.');
        }
        
        // Update UI with the new main keyword
        updateUIWithMainKeyword(associations);
        
        // Show success message
        showToast(`Keyword "${selectedKeyword}" has been set as main.`, 'success');
        
        // Instead of reloading the page, just refresh the keywords from API
        loadKeywordsFromApi();
        
        // Re-render the secondary keyword tags
        renderSecondaryKeywordTags();
    })
    .catch(error => {
        console.error('API error:', error);
        showToast(`Error setting main keyword: ${error.message}`, 'error');
    })
    .finally(() => {
        // Reset dropdown selection
        keywordDropdown.selectedIndex = 0;
        
        // Remove loading indicator
        if (loadingIndicator.parentNode) {
            loadingIndicator.parentNode.removeChild(loadingIndicator);
        }
    });
}

/**
 * Update UI with main keyword from associations
 * @param {Array} associations - The associations from API
 */
function updateUIWithMainKeyword(associations) {
    // Get main keyword input
    const mainKeywordInput = document.getElementById('aysa-entity-keyword');
    if (!mainKeywordInput) return;
    
    // Find the main association (marked with isMain=true)
    const mainAssociation = associations.find(a => a.isMain === true);
    
    if (mainAssociation && mainAssociation.keyword) {
        // Update main keyword input
        mainKeywordInput.value = mainAssociation.keyword;
    } else if (associations.length > 0 && associations[0].keyword) {
        // Fallback to first association
        mainKeywordInput.value = associations[0].keyword;
    }
    
    // Refresh keywords from API
    loadKeywordsFromApi();
}

/**
 * Set a keyword as the main keyword
 * @param {string} keyword - The keyword to set as main
 */
function setMainKeyword(keyword) {
    // Get entity ID and type
    const entityId = getEntityId();
    const entityType = getEntityTypeGood();
    
    if (entityId === 0) {
        showToast('Cannot set main keyword: Entity ID is missing', 'error');
        return;
    }
    
    // Show loading indicator 
    showToast(`Setting "${keyword}" as main keyword...`, 'info');
    
    // Get project ID from WordPress params instead of localStorage
    let projectId = 0;
    if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
        projectId = parseInt(aysaParams.project_id);
        console.log('Using project ID from WordPress:', projectId);
    } else {
        // Fallback to localStorage if needed
        const storedProjectId = localStorage.getItem('aysa_project_id');
        if (storedProjectId) {
            projectId = parseInt(storedProjectId);
            console.log('Using project ID from localStorage:', projectId);
        } else {
            console.warn('No project ID found!');
            showToast('Cannot set main keyword: Project ID is missing', 'error');
            return;
        }
    }
    
    // Prepare API data for setmain
    const mainKeywordInput = document.getElementById('aysa-entity-keyword');
    const apiData = {
        IdIntern: entityId,
        AssociatedOn: entityType,
        ProjectId: projectId,
        OldKeyword: mainKeywordInput.value.trim(),
        NewKeyword: keyword
    };
    
    console.log('Setting main keyword with data:', apiData);
    
    // Call API to set main keyword
    fetch(`${getAysaApiBaseUrl()}/api/Association/setmain`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Origin': window.location.origin
        },
        body: JSON.stringify(apiData),
        mode: 'cors'
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                console.error('API error response:', text);
                throw new Error(`API error: ${response.status}`);
            });
        }
        return response.json();
    })
    .then(data => {
        console.log('API response:', data);
        
        // Update main keyword input
        mainKeywordInput.value = keyword;
        
        // Refresh keywords from API
        loadKeywordsFromApi();
        
        // Show success message
        showToast(`Successfully set "${keyword}" as main keyword`, 'success');
        
        // Update the UI without page reload
        // 1. Find the old main keyword tag and remove the main-keyword class
        const mainKeywordTag = document.querySelector('.keyword-tag.main-keyword');
        if (mainKeywordTag) {
            mainKeywordTag.classList.remove('main-keyword');
        }
        
        // 2. Find the new main keyword tag and add the main-keyword class
        const allKeywordTags = document.querySelectorAll('.keyword-tag');
        allKeywordTags.forEach(tag => {
            const tagText = tag.querySelector('.tag-text').textContent;
            if (tagText === keyword) {
                tag.classList.add('main-keyword');
            }
        });
        
        // 3. Re-render the secondary keyword tags
        renderSecondaryKeywordTags();
    })
    .catch(error => {
        console.error('Error setting main keyword:', error);
        showToast(`Error setting main keyword: ${error.message}`, 'error');
    });
}

/**
 * Load keywords from API and render tags
 */
function loadKeywordsFromApi() {
    const entityId = getEntityId();
    const entityType = getEntityTypeGood();
    
    // Get project ID from WordPress params instead of localStorage
    let projectId = 0;
    if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
        projectId = parseInt(aysaParams.project_id);
        console.log('Using project ID from WordPress:', projectId);
    } else {
        // Fallback to localStorage if needed
        const storedProjectId = localStorage.getItem('aysa_project_id');
        if (storedProjectId) {
            projectId = parseInt(storedProjectId);
            console.log('Using project ID from localStorage:', projectId);
        } else {
            console.warn('No project ID found!');
        }
    }
    
    if (entityId === 0 || projectId === 0) {
        console.log('Cannot load keywords: Invalid entity or project ID');
        return;
    }
    
    const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
    if (!secondaryKeywordsContainer) return;
    
    // Show loading state
    secondaryKeywordsContainer.innerHTML = '<div class="loading-placeholder" style="color: #999; font-style: italic;">Loading keywords...</div>';
    
    // Build API URL
    const apiUrl = `${getAysaApiBaseUrl()}/api/Association/GetAllByAssociatedOnAndIdIntern?associatedOn=${encodeURIComponent(entityType)}&idIntern=${entityId}&projectId=${projectId}`;
    
    // Call API to get associations
    fetch(apiUrl, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Origin': window.location.origin
        },
        mode: 'cors'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`API error: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Loaded associations:', data);
        
        // Store data in global variable if it exists
        if (typeof aysaAPIData !== 'undefined') {
            aysaAPIData = data;
        }
        
        // Check if we have valid data
        if (!data || (Array.isArray(data) && data.length === 0)) {
            secondaryKeywordsContainer.innerHTML = '<div class="empty-placeholder" style="color: #999; font-style: italic;">No keywords found</div>';
            return;
        }
        
        // Populate keyword dropdown
        populateKeywordDropdown(data);
        
        // Update secondary keywords
        updateSecondaryKeywords(data);
    })
    .catch(error => {
        console.error('Error loading keywords:', error);
        
        // Instead of showing "Error: API error: 404", show a more friendly message
        secondaryKeywordsContainer.innerHTML = '<div class="empty-placeholder" style="color: #999; font-style: italic;">No keywords yet. Add keywords using "Generate SEO Suggestions".</div>';
        
        // Clear any error from the hidden secondary keywords field
        const suggestedField = document.getElementById('aysa-entity-suggested-second-keyword');
        if (suggestedField) {
            suggestedField.value = '';
            
            // Also hide any error message container that might be around it
            const parentEl = suggestedField.parentNode;
            if (parentEl) {
                const errorMsg = parentEl.querySelector('.error-message');
                if (errorMsg) {
                    errorMsg.remove();
                }
            }
        }
    });
}

/**
 * Populate keyword dropdown from API data
 * @param {Array} data - The associations from API
 */
function populateKeywordDropdown(data) {
    const keywordDropdown = document.getElementById('keyword-suggestions');
    if (!keywordDropdown) return;
    
    // Convert to array if needed
    const associations = Array.isArray(data) ? data : [data];
    
    // Clear dropdown except first option
    keywordDropdown.disabled = false;
    while (keywordDropdown.options.length > 1) {
        keywordDropdown.remove(1);
    }
    
    // Find the main keyword
    const mainKeywordInput = document.getElementById('aysa-entity-keyword');
    const mainKeyword = mainKeywordInput ? mainKeywordInput.value.trim() : '';
    
    // Add secondary keywords as options (excluding the main keyword)
    let secondaryKeywordsCount = 0;
    associations.forEach(assoc => {
        if (assoc.keyword && assoc.keyword.trim() !== mainKeyword) {
            const option = document.createElement('option');
            option.value = assoc.keyword;
            option.text = assoc.keyword;
            
            // Store the association ID as a data attribute
            option.dataset.associationId = assoc.id;
            
            keywordDropdown.add(option);
            secondaryKeywordsCount++;
        }
    });
    
    // Add a message if no secondary keywords found
    if (secondaryKeywordsCount === 0) {
        const noKeywordsOption = document.createElement('option');
        noKeywordsOption.text = "No secondary keywords available";
        noKeywordsOption.disabled = true;
        keywordDropdown.add(noKeywordsOption);
    }
}

/**
 * Update secondary keywords from API data
 * @param {Array} data - The associations from API
 */
function updateSecondaryKeywords(data) {
    // Convert to array if needed
    const associations = Array.isArray(data) ? data : [data];
    
    // Find the main keyword/association
    const mainAssociation = associations.find(a => a.isMain === true);
    const mainKeyword = mainAssociation ? mainAssociation.keyword : null;
    
    // Filter to secondary keywords (not main)
    const secondaryAssociations = associations.filter(a => {
        // If we found a main association by isMain flag, exclude by comparing IDs
        if (mainAssociation) {
            return a.id !== mainAssociation.id;
        }
        // Otherwise, filter by keyword comparison
        return a.keyword !== mainKeyword;
    });
    
    // Get secondary keyword input and container
    const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
    const secondaryKeywordsContainer = document.getElementById('secondary-keywords-container');
    
    if (!secondaryKeywordInput || !secondaryKeywordsContainer) return;
    
    // Update secondary keywords input
    const secondaryKeywords = secondaryAssociations.map(a => a.keyword).filter(Boolean);
    secondaryKeywordInput.value = secondaryKeywords.join(', ');
    
    // Clear container
    secondaryKeywordsContainer.innerHTML = '';
    
    // Create tags for secondary keywords
    secondaryAssociations.forEach(assoc => {
        if (assoc.keyword) {
            // Pass both the association ID and the tracking status
            createKeywordTag(assoc.keyword, assoc.id, assoc.isTracked);
        }
    });
    
    // Show a message if no secondary keywords
    if (secondaryAssociations.length === 0) {
        secondaryKeywordsContainer.innerHTML = '<div class="empty-placeholder" style="color: #999; font-style: italic;">No secondary keywords</div>';
    }
}

/**
 * Add a secondary keyword
 * @param {string} keyword - The keyword to add
 */
function addSecondaryKeyword(keyword) {
    console.log('Adding secondary keyword:', keyword);
    
    // Trim the keyword
    keyword = keyword.trim();
    
    // Don't add empty keywords
    if (!keyword) {
        showToast('Please enter a keyword.', 'warning');
        return;
    }
    
    // Get current secondary keywords
    const secondaryKeywordInput = document.getElementById('aysa-entity-second-keyword');
    if (!secondaryKeywordInput) {
        console.error('Secondary keywords input not found');
        return;
    }
    
    // Split into array, trim each keyword, and filter out empty entries
    const secondaryKeywordsValue = secondaryKeywordInput.value;
    const secondaryKeywords = secondaryKeywordsValue ? 
        secondaryKeywordsValue.split(',')
            .map(k => k.trim())
            .filter(k => k !== '') 
        : [];
    
    // Check if the keyword already exists
    if (secondaryKeywords.includes(keyword)) {
        showToast(`Keyword "${keyword}" already exists.`, 'warning');
        return;
    }
    
    // Check if it matches the main keyword
    const mainKeywordInput = document.getElementById('aysa-entity-keyword');
    const mainKeyword = mainKeywordInput ? mainKeywordInput.value.trim() : '';
    
    if (keyword === mainKeyword) {
        showToast(`Keyword "${keyword}" is already the main keyword.`, 'warning');
        return;
    }
    
    // Show loading state
    const addButton = document.getElementById('add-secondary-keyword-btn');
    const originalButtonText = addButton ? addButton.textContent : 'Add';
    if (addButton) {
        addButton.disabled = true;
        addButton.textContent = 'Adding...';
    }
    
    // Get entity ID and type
    const entityId = getEntityId();
    const entityType = getEntityTypeGood();
    
    // Get project ID from WordPress params or localStorage
    let projectId = 0;
    if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
        projectId = parseInt(aysaParams.project_id);
    } else {
        const storedProjectId = localStorage.getItem('aysa_project_id');
        if (storedProjectId) {
            projectId = parseInt(storedProjectId);
        }
    }
    
    // Find the name element for Value field
    const nameElement = document.getElementById('title') || 
                        document.querySelector('input[name="name"]') || 
                        document.getElementById('name') || 
                        document.querySelector('input[name="post_title"]');
    
    // Check if we should track the keyword
    const trackCheckbox = document.getElementById('track-new-keyword');
    const shouldTrack = trackCheckbox ? trackCheckbox.checked : false;
    
    // If this is a new entity (entityId === 0), don't make API call, just save for later
    if (entityId === 0) {
        console.log('New entity detected - saving secondary keyword for later processing:', keyword);
        
        // Add to UI immediately
        secondaryKeywords.push(keyword);
        secondaryKeywordInput.value = secondaryKeywords.join(', ');
        createKeywordTag(keyword, null, shouldTrack);
        
        // Clear the input
        const newSecondaryKeywordInput = document.getElementById('new-secondary-keyword');
        if (newSecondaryKeywordInput) {
            newSecondaryKeywordInput.value = '';
        }
        
        // Save to localStorage for later processing
        const pendingKey = `aysa_pending_${entityType}_${Date.now()}`;
        const existingPendingData = localStorage.getItem(pendingKey);
        let pendingData;
        
        if (existingPendingData) {
            try {
                pendingData = JSON.parse(existingPendingData);
            } catch (e) {
                pendingData = {
                    entityType: entityType,
                    projectId: projectId,
                    timestamp: new Date().toISOString(),
                    keyword: '',
                    secondaryKeywords: [],
                    metaTitle: '',
                    metaDescription: '',
                    metaKeywords: '',
                    seoSettings: {},
                    advancedSettings: {}
                };
            }
        } else {
            pendingData = {
                entityType: entityType,
                projectId: projectId,
                timestamp: new Date().toISOString(),
                keyword: document.getElementById('aysa-entity-keyword')?.value || '',
                secondaryKeywords: [],
                metaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
                metaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
                metaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
                seoSettings: {
                    targetedSearchEngine: document.getElementById('targeted_se')?.value || '',
                    targetedCountry: document.getElementById('targeted_country')?.value || '',
                    targetedRegion: document.getElementById('targeted_region')?.value || '',
                    targetedCity: document.getElementById('targeted_city')?.value || '',
                    updateFrequency: document.getElementById('update_frequency')?.value || '',
                    languageOptimize: document.getElementById('language_optimize')?.value || '',
                    deviceOptimize: document.getElementById('device_optimize')?.value || ''
                },
                advancedSettings: {
                    index: document.getElementById('robots_index')?.checked || false,
                    noFollow: document.getElementById('robots_nofollow')?.checked || false,
                    noArchive: document.getElementById('robots_noarchive')?.checked || false,
                    noImageIndex: document.getElementById('robots_noimageindex')?.checked || false,
                    noSnippet: document.getElementById('robots_nosnippet')?.checked || false,
                    maxSnippet: parseInt(document.getElementById('max_snippet')?.value) || -1,
                    maxVideoPreview: parseInt(document.getElementById('max_video_preview')?.value) || -1,
                    maxImagePreview: document.getElementById('max_image_preview')?.value || 'small',
                    canonicalUrl: document.getElementById('canonical_url')?.value || ''
                }
            };
        }
        
        // Add the new secondary keyword to the pending data
        const keywordWithTracking = {
            keyword: keyword,
            isTracked: shouldTrack
        };
        
        if (!pendingData.secondaryKeywords.some(k => k.keyword === keyword)) {
            pendingData.secondaryKeywords.push(keywordWithTracking);
        }
        
        // Save back to localStorage
        localStorage.setItem(pendingKey, JSON.stringify(pendingData));
        console.log('Saved secondary keyword to localStorage for later processing:', pendingKey);
        
        // Reset button state
        if (addButton) {
            addButton.disabled = false;
            addButton.textContent = originalButtonText;
        }
        
        // Show success message
        showToast(`Added "${keyword}" - will be saved when entity is created.`, 'info');
        return;
    }
    
    try {
        // Create a new association object - without ID but including all metadata fields
        const newAssociation = {
            IdIntern: entityId,
            AssociatedOn: entityType,
            Value: nameElement ? nameElement.value : '',
            Link: window.location.href,
            Keyword: keyword,
            ProjectId: projectId,
            IsMain: false, // Not a main keyword
            IsTracked: shouldTrack, // Use the value from checkbox
            SecondKeyword: '', // No secondary keywords for this association
            
            // Include all metadata fields from form
            MetaTitle: document.getElementById('aysa-entity-meta-title')?.value || '',
            MetaDescription: document.getElementById('aysa-entity-meta-description')?.value || '',
            MetaKeywords: document.getElementById('aysa-entity-meta-keywords')?.value || '',
            
            // Include SEO settings
            TargetedSearchEngine: document.getElementById('targeted_se')?.value || '',
            TargetedCountry: document.getElementById('targeted_country')?.value || '',
            TargetedRegion: document.getElementById('targeted_region')?.value || '',
            TargetedCity: document.getElementById('targeted_city')?.value || '',
            UpdateFrequency: document.getElementById('update_frequency')?.value || '',
            LanguageOptimize: document.getElementById('language_optimize')?.value || '',
            DeviceOptimize: document.getElementById('device_optimize')?.value || '',
            
            // Include advanced settings
            Index: document.getElementById('robots_index')?.checked || false,
            NoFollow: document.getElementById('robots_nofollow')?.checked || false,
            NoArchive: document.getElementById('robots_noarchive')?.checked || false,
            NoImageIndex: document.getElementById('robots_noimageindex')?.checked || false,
            NoSnippet: document.getElementById('robots_nosnippet')?.checked || false,
            MaxSnippet: parseInt(document.getElementById('max_snippet')?.value) || -1,
            MaxVideoPreview: parseInt(document.getElementById('max_video_preview')?.value) || -1,
            MaxImagePreview: document.getElementById('max_image_preview')?.value || 'small',
            CanonicalUrl: document.getElementById('canonical_url')?.value || ''
        };
        
        console.log('Creating new association for secondary keyword with all metadata:', newAssociation);
        
        // Setup a timeout to reset the button if the API call takes too long
        const resetTimeout = setTimeout(() => {
            if (addButton) {
                addButton.disabled = false;
                addButton.textContent = originalButtonText;
                showToast('API call is taking longer than expected, but we\'ll keep trying...', 'info');
            }
        }, 10000); // 10 seconds timeout
        
        // Make API call to create a new association
        const apiBaseUrl = ((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '');
        fetch(`${apiBaseUrl}/api/Association/upsert`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Origin': window.location.origin
            },
            body: JSON.stringify(newAssociation),
            mode: 'cors'
        })
        .then(response => {
            // Clear the timeout since we got a response
            clearTimeout(resetTimeout);
            
            if (!response.ok) {
                throw new Error('API response status: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            console.log('Secondary keyword association created:', data);
            
            // Add the new keyword to the input
            secondaryKeywords.push(keyword);
            secondaryKeywordInput.value = secondaryKeywords.join(', ');
            
            // Create a tag with the association ID and tracking status
            if (data && data.id) {
                createKeywordTag(keyword, data.id, shouldTrack);
            } else {
                createKeywordTag(keyword, null, shouldTrack);
            }
            
            // Clear the input
            const newSecondaryKeywordInput = document.getElementById('new-secondary-keyword');
            if (newSecondaryKeywordInput) {
                newSecondaryKeywordInput.value = '';
            }
            
            // Show success message
            showToast(`Added "${keyword}" as a new association with all metadata.`, 'success');
        })
        .catch(error => {
            console.error('Error creating secondary keyword association:', error);
            showToast(`Error adding keyword: ${error.message}`, 'error');
            
            // Still add to UI but without association ID
            secondaryKeywords.push(keyword);
            secondaryKeywordInput.value = secondaryKeywords.join(', ');
            createKeywordTag(keyword);
            
            // Clear the input even if there was an error
            const newSecondaryKeywordInput = document.getElementById('new-secondary-keyword');
            if (newSecondaryKeywordInput) {
                newSecondaryKeywordInput.value = '';
            }
        })
        .finally(() => {
            // Reset button state
            if (addButton) {
                addButton.disabled = false;
                addButton.textContent = originalButtonText;
            }
        });
    } catch (error) {
        // Handle any unexpected errors in the function
        console.error('Unexpected error in addSecondaryKeyword function:', error);
        showToast(`Unexpected error: ${error.message}`, 'error');
        
        // Still add to UI if possible
        try {
            secondaryKeywords.push(keyword);
            secondaryKeywordInput.value = secondaryKeywords.join(', ');
            createKeywordTag(keyword);
            
            // Clear the input even if there was an error
            const newSecondaryKeywordInput = document.getElementById('new-secondary-keyword');
            if (newSecondaryKeywordInput) {
                newSecondaryKeywordInput.value = '';
            }
        } catch (e) {
            console.error('Error adding keyword to UI after API error:', e);
        }
        
        // Always reset the button
        if (addButton) {
            addButton.disabled = false;
            addButton.textContent = originalButtonText;
        }
    }
}

// Add function to window object to make it globally accessible
window.addSecondaryKeyword = addSecondaryKeyword;

/**
 * Bind keyword-related event listeners
 */
function bindKeywordEventListeners() {
    // Add keyword button
    const addSecondaryKeywordBtn = document.getElementById('add-secondary-keyword-btn');
    if (addSecondaryKeywordBtn) {
        addSecondaryKeywordBtn.addEventListener('click', function() {
            const newSecondaryKeywordInput = document.getElementById('new-secondary-keyword');
            if (newSecondaryKeywordInput) {
                const keyword = newSecondaryKeywordInput.value.trim();
                if (keyword) {
                    addSecondaryKeyword(keyword);
                } else {
                    alert('Please enter a keyword.');
                }
            }
        });
    }
    
    // New secondary keyword input
    const newSecondaryKeywordInput = document.getElementById('new-secondary-keyword');
    if (newSecondaryKeywordInput) {
        newSecondaryKeywordInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const keyword = this.value.trim();
                if (keyword) {
                    addSecondaryKeyword(keyword);
                } else {
                    alert('Please enter a keyword.');
                }
            }
        });
    }
}

/**
 * Get entity ID from the current page
 * @returns {number} The entity ID or 0 if not found
 */
function getEntityId() {
    let entityId = 0;
    
    // Check URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('tag_ID')) {
        entityId = parseInt(urlParams.get('tag_ID'));
    } else if (urlParams.get('post')) {
        entityId = parseInt(urlParams.get('post'));
    } else {
        // Try to get from hidden input
        const postIdInput = document.querySelector('input[name="post_ID"]');
        if (postIdInput) {
            entityId = parseInt(postIdInput.value);
        }
    }
    
    // Final fallback to aysaParams
    if (entityId === 0 && typeof aysaParams !== 'undefined') {
        if (aysaParams.postId) {
            entityId = parseInt(aysaParams.postId);
        } else if (aysaParams.termId) {
            entityId = parseInt(aysaParams.termId);
        }
    }
    
    return entityId;
}

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

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

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

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

/**
 * Set a keyword as the main keyword when clicked on a tag
 * @param {string} keyword - The keyword to set as main
 * @param {string} associationId - The association ID (optional)
 */
function setAsMainKeyword(keyword, associationId) {
    console.log(`Trying to set keyword "${keyword}" as main, association ID: ${associationId}`);
    
    // First try to confirm with the user
    customConfirm(`Set "${keyword}" as main keyword?`).then(confirmed => {
        if (!confirmed) {
            console.log('User canceled setting main keyword');
            return;
        }
        
        // Get project ID from WordPress params or localStorage
        let projectId = 0;
        if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
            projectId = parseInt(aysaParams.project_id);
        } else {
            const storedProjectId = localStorage.getItem('aysa_project_id');
            if (storedProjectId) {
                projectId = parseInt(storedProjectId);
            }
        }
        
        // If we have an association ID, use processSwitchToMainKeyword
        if (associationId && !isNaN(parseInt(associationId))) {
            console.log('Using direct association ID to set main keyword');
            processSwitchToMainKeyword(keyword, associationId, projectId);
        } else {
            // Otherwise use the generic setMainKeyword function
            console.log('Using generic method to set main keyword');
            setMainKeyword(keyword);
        }
    });
}

/**
 * Show context menu for a keyword tag
 * @param {Event} event - The click event
 * @param {string} keyword - The keyword text
 * @param {HTMLElement} tagElement - The tag element
 */
function showKeywordContextMenu(event, keyword, tagElement) {
    // Remove any existing context menu
    const existingMenu = document.getElementById('keyword-context-menu');
    if (existingMenu) {
        existingMenu.remove();
    }
    
    // Create context menu element
    const contextMenu = document.createElement('div');
    contextMenu.id = 'keyword-context-menu';
    contextMenu.style.position = 'absolute';
    contextMenu.style.zIndex = '1000';
    contextMenu.style.backgroundColor = 'white';
    contextMenu.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)';
    contextMenu.style.borderRadius = '4px';
    contextMenu.style.padding = '8px 0';
    contextMenu.style.minWidth = '150px';
    
    // Calculate position (below the tag)
    const rect = tagElement.getBoundingClientRect();
    contextMenu.style.left = (rect.left + window.scrollX) + 'px';
    contextMenu.style.top = (rect.bottom + window.scrollY + 5) + 'px';
    
    // Get current tracked status
    const isTracked = tagElement.dataset.isTracked === 'true';
    
    // Add menu items
    contextMenu.innerHTML = `
        <div class="context-menu-item" data-action="set-main">Set as Main Keyword</div>
        <div class="context-menu-item" data-action="toggle-track">
            ${isTracked ? 'Untrack Keyword' : 'Track Keyword'}
        </div>
    `;
    
    // Style menu items
    const menuItems = contextMenu.querySelectorAll('.context-menu-item');
    menuItems.forEach(item => {
        item.style.padding = '8px 15px';
        item.style.cursor = 'pointer';
        item.style.fontSize = '13px';
        
        // Hover effect
        item.addEventListener('mouseover', () => {
            item.style.backgroundColor = '#f0f0f0';
        });
        item.addEventListener('mouseout', () => {
            item.style.backgroundColor = 'transparent';
        });
    });
    
    // Add event listeners for menu items
    contextMenu.querySelector('[data-action="set-main"]').addEventListener('click', () => {
        setAsMainKeyword(keyword, tagElement.dataset.associationId);
        contextMenu.remove();
    });
    
    contextMenu.querySelector('[data-action="toggle-track"]').addEventListener('click', () => {
        toggleKeywordTracking(keyword, tagElement);
        contextMenu.remove();
    });
    
    // Add click outside to close
    document.addEventListener('click', function closeMenu(e) {
        if (!contextMenu.contains(e.target)) {
            contextMenu.remove();
            document.removeEventListener('click', closeMenu);
        }
    });
    
    // Add the menu to the document
    document.body.appendChild(contextMenu);
}

/**
 * Toggle tracking status for a keyword
 * @param {string} keyword - The keyword to toggle tracking for
 * @param {HTMLElement} tagElement - The tag element
 */
function toggleKeywordTracking(keyword, tagElement) {
    const associationId = tagElement.dataset.associationId;
    if (!associationId) {
        showToast(`Cannot track keyword: Missing association ID`, 'error');
        return;
    }
    
    // Get project ID from WordPress params or localStorage
    let projectId = 0;
    if (typeof aysaParams !== 'undefined' && aysaParams.project_id) {
        projectId = parseInt(aysaParams.project_id);
    } else {
        const storedProjectId = localStorage.getItem('aysa_project_id');
        if (storedProjectId) {
            projectId = parseInt(storedProjectId);
        }
    }
    
    if (!projectId) {
        showToast(`Cannot track keyword: Missing project ID`, 'error');
        return;
    }
    
    // Current tracking status
    const isCurrentlyTracked = tagElement.dataset.isTracked === 'true';
    const newTrackingStatus = !isCurrentlyTracked;
    
    // Show loading state
    tagElement.style.opacity = '0.7';
    showToast(`${newTrackingStatus ? 'Enabling' : 'Disabling'} tracking for "${keyword}"...`, 'info');
    
    // Build API URL for toggling tracking status using the setistracked endpoint
    const apiBaseUrl = ((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '');
    const apiUrl = `${apiBaseUrl}/api/Association/setistracked/${projectId}/${associationId}/${newTrackingStatus}`;
    
    // Call API to update tracking status
    fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Origin': window.location.origin
        },
        mode: 'cors'
    })
    .then(response => {
        console.log('API response:', {
            status: response.status,
            statusText: response.statusText,
            url: response.url
        });
        
        if (!response.ok) {
            return response.text().then(text => {
                console.error('API error:', text);
                throw new Error(`API error: ${response.status}`);
            });
        }
        return response.json();
    })
    .then(data => {
        console.log('Tracking status updated:', data);
        
        // Update the tag appearance
        // We toggle the status because the endpoint toggles it on the server
        tagElement.dataset.isTracked = newTrackingStatus ? 'true' : 'false';
        
        if (newTrackingStatus) {
            tagElement.classList.add('is-tracked');
            // Add track icon if it doesn't exist
            if (!tagElement.querySelector('.track-icon')) {
                const trackIcon = document.createElement('span');
                trackIcon.className = 'track-icon';
                trackIcon.title = 'Tracked';
                trackIcon.textContent = '📊';
                tagElement.insertBefore(trackIcon, tagElement.querySelector('.tag-remove'));
            }
        } else {
            tagElement.classList.remove('is-tracked');
            // Remove track icon if it exists
            const trackIcon = tagElement.querySelector('.track-icon');
            if (trackIcon) {
                trackIcon.remove();
            }
        }
        
        // Reset opacity
        tagElement.style.opacity = '1';
        
        // Show success message
        showToast(`${newTrackingStatus ? 'Enabled' : 'Disabled'} tracking for "${keyword}"`, 'success');
    })
    .catch(error => {
        console.error('Error updating tracking status:', error);
        tagElement.style.opacity = '1';
        showToast(`Error updating tracking status: ${error.message}`, 'error');
    });
} 
