<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Template for the category metabox
 * 
 * @var array $keyword_data Keyword data for the category
 */

// Default values
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
$keyword_data = isset($keyword_data) ? $keyword_data : array();
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.Security.NonceVerification.Recommended -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
$term_id = isset($_GET['tag_ID']) ? intval(wp_unslash($_GET['tag_ID'])) : 0;

// Define plugin text domain

// (Localization of aysaParams is handled in the controller; not repeated here.)
?>

<!-- Critical script to ensure WordPress form submission works properly -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Global flag to indicate we're in WordPress form submission mode
    window.aysaBypassValidation = false;
    
    // ✅ CRITICAL: Check if we're on a page edit screen - DON'T bypass AYSA for pages!
    const isPageEditScreen = window.location.href.includes('post.php') && 
                             document.querySelector('#post_type') && 
                             document.querySelector('#post_type').value === 'page';
    
    // Find WordPress forms (addtag and edittag)
    const wpForms = document.querySelectorAll('#addtag, #edittag');
    if (wpForms.length > 0) {
        console.log('Found WordPress category forms, applying AYSA compatibility...');
        
        // Process each WordPress form
        wpForms.forEach(function(form) {
            // Get the original submit handler
            const originalSubmit = form.onsubmit;
            
            // Save the submit button for later use
            const submitButton = form.querySelector('input[name="submit"], #submit');
            
            // DON'T override the form's submit handler for edit forms - let AYSA handle it
            if (form.id === 'addtag' && !isPageEditScreen) {
                // Only override for new category form (not for pages)
                form.onsubmit = function(e) {
                    // Set bypass flag for WordPress validation (API calls handled by aysa-metabox.js)
                    window.aysaBypassValidation = true;
                    console.log('WordPress add category form submitted, AYSA validation bypassed');
                    
                    // Continue with normal WordPress form processing
                    return originalSubmit ? originalSubmit.call(this, e) : true;
                };
            }
            
            // Add click handler for the WordPress submit button only for add forms
            if (submitButton && form.id === 'addtag' && !isPageEditScreen) {
                submitButton.addEventListener('click', function(e) {
                    // Set bypass flag
                    window.aysaBypassValidation = true;
                    console.log('WordPress add category submit button clicked, AYSA validation bypassed');
                    
                    // Let WordPress handle the submit normally
                });
            }
            
            // Handle the Enter key in any form field to allow WordPress default behavior
            form.querySelectorAll('input, textarea').forEach(function(input) {
                input.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter' && !isPageEditScreen) {
                        // Only handle if this is part of the WordPress form (not AYSA fields) and not a page
                        if (!e.target.closest('.aysa-metabox-container')) {
                            window.aysaBypassValidation = true;
                            console.log('Enter key pressed in WordPress form field, AYSA validation bypassed');
                        }
                    }
                });
            });
        });
    }
    
    // Handle "Add New Category" button separately
    const addNewCategoryButton = document.querySelector('#category-add-submit');
    if (addNewCategoryButton && !isPageEditScreen) {
        addNewCategoryButton.addEventListener('click', function(e) {
            window.aysaBypassValidation = true;
            console.log('Add New Category button clicked, AYSA validation bypassed');
        });
    }
    
    // Make sure AYSA never activates on Enter key press in WordPress fields (but not for pages)
    if (!isPageEditScreen) {
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                // Find the active element
                const activeElement = document.activeElement;
                
                // If the active element is a WordPress form field (not in AYSA container)
                if (activeElement && 
                    (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') && 
                    !activeElement.closest('.aysa-metabox-container')) {
                    
                    window.aysaBypassValidation = true;
                    console.log('Enter key pressed in WordPress field, AYSA validation bypassed');
                }
            }
        });
    }
    
    // Format Meta keywords to ensure space after comma
    const metaKeywordsField = document.getElementById('aysa-entity-meta-keywords');
    if (metaKeywordsField) {
        // Format on blur (when field loses focus)
        metaKeywordsField.addEventListener('blur', function() {
            formatMetaKeywords(this);
        });
        
        // Format on input with slight delay to avoid interfering with typing
        metaKeywordsField.addEventListener('input', function() {
            clearTimeout(this.formatTimer);
            this.formatTimer = setTimeout(() => {
                formatMetaKeywords(this);
            }, 500);
        });
        
        // Format initially if there's existing content
        if (metaKeywordsField.value.trim()) {
            formatMetaKeywords(metaKeywordsField);
        }
    }
    
    // Function to format meta keywords
    function formatMetaKeywords(field) {
        // Ensure there's a space after each comma
        let value = field.value;
        if (value) {
            // Replace any instances of comma without a space after it
            value = value.replace(/,(?!\s)/g, ', ');
            // Avoid double spaces
            value = value.replace(/,\s{2,}/g, ', ');
            field.value = value;
        }
    }

    
    // Function to toggle Generate SEO Suggestions button based on keyword field and entity name
    function toggleGenerateButton() {
        const keywordField = document.getElementById('aysa-entity-keyword');
        const generateBtn = document.getElementById('generate-suggestions-btn');
        
        if (keywordField && generateBtn) {
            const isKeywordEmpty = !keywordField.value.trim();
            
            // Check if this is a new category page and if category name is provided
            const isNewCategoryPage = window.location.pathname.includes('edit-tags.php') && !window.location.search.includes('tag_ID');
            const isPageEditScreen = window.location.pathname.includes('post.php') || window.location.pathname.includes('post-new.php');
            let isEntityNameMissing = false;
            
            if (isNewCategoryPage) {
                const categoryNameInput = document.querySelector('input[name="tag-name"]') || document.querySelector('#tag-name');
                const categoryName = categoryNameInput ? categoryNameInput.value.trim() : '';
                isEntityNameMissing = !categoryName;
            } else if (isPageEditScreen) {
                // For pages, check if we have a title
                const pageTitleInput = document.querySelector('input[name="post_title"]') || 
                                     document.getElementById('title') ||
                                     document.querySelector('.editor-post-title__input');
                let pageTitle = '';
                if (pageTitleInput) {
                    pageTitle = pageTitleInput.value?.trim() || pageTitleInput.textContent?.trim() || '';
                }
                
                // Also try Gutenberg API
                if (!pageTitle && typeof wp !== 'undefined' && wp.data && wp.data.select) {
                    try {
                        const currentPost = wp.data.select('core/editor').getCurrentPost();
                        if (currentPost && currentPost.title) {
                            pageTitle = currentPost.title.trim();
                        }
                    } catch (e) {
                        // Silently fail
                    }
                }
                
                isEntityNameMissing = !pageTitle;
                console.log('🚀 PAGE DEBUG: Page title detection:', {
                    pageTitle: pageTitle || 'empty',
                    isEntityNameMissing: isEntityNameMissing,
                    pageTitleInput: pageTitleInput ? pageTitleInput.tagName : 'not found'
                });
            }
            
            // Always keep button enabled - show warning message instead
            generateBtn.disabled = false;
            
            // Always use active button styling - GREEN
            generateBtn.style.backgroundColor = '#2ea043 !important';
            generateBtn.style.borderColor = '#2ea043 !important';
            generateBtn.style.color = 'white !important';
            generateBtn.style.cursor = 'pointer';
            generateBtn.style.opacity = '1';
            generateBtn.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2) !important';
            generateBtn.style.transform = '';
            
            // Update title and show/hide messages based on conditions
            if (isEntityNameMissing) {
                generateBtn.title = isPageEditScreen ? 'Will use page title when available' : 'Will use category name when available';
                // Show warning message if no entity name
                if (typeof showKeywordWarningMessage === 'function') {
                    showKeywordWarningMessage();
                }
            } else if (isKeywordEmpty) {
                generateBtn.title = isPageEditScreen ? 'Will use page title as keyword' : 'Will use category name as keyword';
                // Show warning message if no keyword
                if (typeof showKeywordWarningMessage === 'function') {
                    showKeywordWarningMessage();
                }
            } else {
                generateBtn.title = 'Click to generate automated SEO suggestions';
                // Hide warning messages if keyword is set
                if (typeof hideKeywordWarningMessage === 'function') {
                    hideKeywordWarningMessage();
                }
            }
        }
    }
    
    // Monitor keyword field and entity name changes
    const keywordField = document.getElementById('aysa-entity-keyword');
    const categoryNameInput = document.querySelector('input[name="tag-name"]') || document.querySelector('#tag-name');
    const pageTitleInput = document.querySelector('input[name="post_title"]') || 
                          document.getElementById('title') ||
                          document.querySelector('.editor-post-title__input');
    
    if (keywordField) {
        // Check initial state
        toggleGenerateButton();
        
        // Monitor keyword field changes
        keywordField.addEventListener('input', toggleGenerateButton);
        keywordField.addEventListener('change', toggleGenerateButton);
        keywordField.addEventListener('keyup', toggleGenerateButton);
        keywordField.addEventListener('paste', function() {
            setTimeout(toggleGenerateButton, 10);
        });
    }
    
    // Monitor category name changes for new categories
    if (categoryNameInput) {
        categoryNameInput.addEventListener('input', toggleGenerateButton);
        categoryNameInput.addEventListener('change', toggleGenerateButton);
        categoryNameInput.addEventListener('keyup', toggleGenerateButton);
        categoryNameInput.addEventListener('paste', function() {
            setTimeout(toggleGenerateButton, 10);
        });
    }
    
    // Monitor page title changes for pages
    if (pageTitleInput) {
        console.log('🚀 PAGE DEBUG: Found page title input, adding event listeners');
        pageTitleInput.addEventListener('input', toggleGenerateButton);
        pageTitleInput.addEventListener('change', toggleGenerateButton);
        pageTitleInput.addEventListener('keyup', toggleGenerateButton);
        pageTitleInput.addEventListener('paste', function() {
            setTimeout(toggleGenerateButton, 10);
        });
    }
    
    // For Gutenberg, also listen to wp.data changes
    if (typeof wp !== 'undefined' && wp.data && wp.data.subscribe) {
        try {
            wp.data.subscribe(() => {
                // Delay the update to allow Gutenberg to finish updating
                setTimeout(toggleGenerateButton, 100);
            });
            console.log('🚀 PAGE DEBUG: Subscribed to Gutenberg data changes for toggleGenerateButton');
        } catch (e) {
            console.warn('🚀 PAGE DEBUG: Could not subscribe to Gutenberg data changes:', e);
        }
    }
    
    // Additional delayed checks for pages (Gutenberg might load title later)
    setTimeout(toggleGenerateButton, 1000);
    setTimeout(toggleGenerateButton, 3000);
     
     // Disable all revert buttons
     function disableRevertButtons() {
         const revertButtons = document.querySelectorAll(
             '#reject-meta-fields, #reject-description-field, #reject-category-fields, ' +
             '.aysa-button[id*="reject"], .aysa-button[id*="revert"]'
         );
         
         revertButtons.forEach(function(button) {
             button.disabled = false;
             
             // Remove existing event listeners by cloning the button
             const newButton = button.cloneNode(true);
             button.parentNode.replaceChild(newButton, button);
             
             // Add a dummy click handler that does nothing
             newButton.addEventListener('click', function(e) {
                 e.preventDefault();
                 e.stopPropagation();
                 return false;
             });
         });
     }
     
     // Disable revert buttons on load
     disableRevertButtons();
     
     // Also disable any dynamically created revert buttons
     const observer = new MutationObserver(function(mutations) {
         mutations.forEach(function(mutation) {
             mutation.addedNodes.forEach(function(node) {
                 if (node.nodeType === 1) { // Element node
                     const revertButtons = node.querySelectorAll ? 
                         node.querySelectorAll('#reject-meta-fields, #reject-description-field, #reject-category-fields, .aysa-button[id*="reject"], .aysa-button[id*="revert"]') : [];
                     
                     revertButtons.forEach(function(button) {
                         button.disabled = false;
                         button.addEventListener('click', function(e) {
                             e.preventDefault();
                             e.stopPropagation();
                             return false;
                         });
                     });
                 }
             });
         });
     });
     
     observer.observe(document.body, {
         childList: true,
         subtree: true
     });
     
     // ✅ Category Name Warning Banner for New Categories
    initCategoryNameWarning();
    
    function initCategoryNameWarning() {
        // Only show warning on new category page
        const isNewCategoryPage = window.location.pathname.includes('edit-tags.php') && !window.location.search.includes('tag_ID');
        
        if (isNewCategoryPage) {
            const metaboxContainer = document.querySelector('.aysa-metabox-container');
            const categoryNameInput = document.querySelector('input[name="tag-name"]') || document.querySelector('#tag-name');
            
            if (metaboxContainer && categoryNameInput) {
                // Create warning banner
                const warningBanner = document.createElement('div');
                warningBanner.id = 'aysa-category-name-warning';
                warningBanner.style.cssText = `
                    background: #fff3cd;
                    border: 1px solid #ffeaa7;
                    color: #856404;
                    padding: 12px 15px;
                    margin-bottom: 15px;
                    border-radius: 4px;
                    border-left: 4px solid #ffc107;
                    font-size: 14px;
                    display: none;
                `;
                warningBanner.innerHTML = `
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" style="flex-shrink: 0;">
                            <path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>
                        </svg>
                        <span><strong>Notice:</strong> Please enter a category name above before adding SEO data. Without a category name, the SEO data cannot be saved.</span>
                    </div>
                `;
                
                // Insert banner at the top of metabox content
                const metaboxContent = metaboxContainer.querySelector('.aysa-metabox-content');
                if (metaboxContent) {
                    metaboxContent.insertBefore(warningBanner, metaboxContent.firstChild);
                }
                
                // Function to show/hide warning
                function updateWarningVisibility() {
                    const categoryName = categoryNameInput.value.trim();
                    const aysaFields = document.querySelectorAll('#aysa-entity-keyword, #aysa-entity-meta-title, #aysa-entity-meta-description');
                    const hasAysaData = Array.from(aysaFields).some(field => field.value.trim());
                    
                    if (!categoryName && hasAysaData) {
                        warningBanner.style.display = 'block';
                    } else {
                        warningBanner.style.display = 'none';
                    }
                }
                
                // Monitor changes
                categoryNameInput.addEventListener('input', updateWarningVisibility);
                
                // Monitor AYSA fields
                document.querySelectorAll('#aysa-entity-keyword, #aysa-entity-meta-title, #aysa-entity-meta-description').forEach(field => {
                    field.addEventListener('input', updateWarningVisibility);
                });
                
                // Initial check
                updateWarningVisibility();
            }
        }
    }
    
    // ✅ Character Count Functionality
     initCharacterCount();
     
     function initCharacterCount() {
         const metaboxContainer = document.querySelector('.aysa-metabox-container');
         if (!metaboxContainer) {
             return;
         }

         // Meta Title Character Count (50-60 optimal)
         const metaTitleInput = metaboxContainer.querySelector('#aysa-entity-meta-title');
         const metaTitleCount = metaboxContainer.querySelector('#aysa-meta-title-char-count');
         
         if (metaTitleInput && metaTitleCount) {
             function updateMetaTitleCount() {
                 const length = metaTitleInput.value.length;
                 const charSpan = metaTitleCount.querySelector('.char-count');
                 const statusSpan = metaTitleCount.querySelector('.char-status');
                 if (charSpan) charSpan.textContent = length;
                 
                 // Color coding for meta title (50-60 optimal)
                 metaTitleCount.classList.remove('is-optimal', 'is-warning', 'is-error');
                 if (length >= 50 && length <= 60) {
                     metaTitleCount.classList.add('is-optimal');
                     if (statusSpan) statusSpan.textContent = 'In recommended range (50-60)';
                 } else if ((length >= 40 && length < 50) || (length > 60 && length <= 70)) {
                     metaTitleCount.classList.add('is-warning');
                     if (statusSpan) statusSpan.textContent = 'Close to recommended range (50-60)';
                 } else if (length < 40 || length > 70) {
                     metaTitleCount.classList.add('is-error');
                     if (statusSpan) statusSpan.textContent = 'Outside recommended range (50-60)';
                 }
             }
             
             metaTitleInput.addEventListener('input', updateMetaTitleCount);
             metaTitleInput.addEventListener('keyup', updateMetaTitleCount);
             metaTitleInput.addEventListener('paste', () => setTimeout(updateMetaTitleCount, 10));
             updateMetaTitleCount(); // Initial count
         }
         
         // Meta Description Character Count (150-160 optimal)
         const metaDescInput = metaboxContainer.querySelector('#aysa-entity-meta-description');
         const metaDescCount = metaboxContainer.querySelector('#aysa-meta-description-char-count');
         
         if (metaDescInput && metaDescCount) {
             function updateMetaDescCount() {
                 const length = metaDescInput.value.length;
                 const charSpan = metaDescCount.querySelector('.char-count');
                 const statusSpan = metaDescCount.querySelector('.char-status');
                 if (charSpan) charSpan.textContent = length;
                 
                 // Color coding for meta description (150-160 optimal)
                 metaDescCount.classList.remove('is-optimal', 'is-warning', 'is-error');
                 if (length >= 150 && length <= 160) {
                     metaDescCount.classList.add('is-optimal');
                     if (statusSpan) statusSpan.textContent = 'In recommended range (150-160)';
                 } else if ((length >= 140 && length < 150) || (length > 160 && length <= 170)) {
                     metaDescCount.classList.add('is-warning');
                     if (statusSpan) statusSpan.textContent = 'Close to recommended range (150-160)';
                 } else if (length < 140 || length > 170) {
                     metaDescCount.classList.add('is-error');
                     if (statusSpan) statusSpan.textContent = 'Outside recommended range (150-160)';
                 }
             }
             
             metaDescInput.addEventListener('input', updateMetaDescCount);
             metaDescInput.addEventListener('keyup', updateMetaDescCount);
             metaDescInput.addEventListener('paste', () => setTimeout(updateMetaDescCount, 10));
             updateMetaDescCount(); // Initial count
         }
         
         console.log('✅ Character count functionality initialized');
     }
});
</script>

<!-- Include styles and scripts -->
<?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- Admin-only legacy metabox asset is conditionally loaded at this render boundary; moving it would change the established load order, and its plugin-local URL is escaped. ?>
<link rel="stylesheet" href="<?php echo esc_url(plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/css/aysa-metabox.css'); ?>">
<?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- Admin-only legacy metabox dependency is conditionally loaded before its consumers at this render boundary; its fixed plugin-local URL is escaped. ?>
<script src="<?php echo esc_url(AYSA_PLUGIN_URL . 'assets/js/vendor/chartjs-stub.js'); ?>"></script>

<!-- Custom styles to ensure buttons are colored correctly -->
<style>
    /* Critical button styles that must be applied */
    .aysa-button-primary {
        background-color: #2ea043 !important;
        color: white !important;
        border: 1px solid #2ea043 !important;
        transition: background-color 0.2s ease !important;
    }
    
    .aysa-button-primary:hover {
        background-color: #238636 !important;
        border-color: #238636 !important;
    }
    
    .aysa-button-action {
        background-color: #ff6b6b !important;
        color: white !important;
        border: 1px solid #ff6b6b !important;
        transition: background-color 0.2s ease !important;
    }
    
    .aysa-button-action:hover {
        background-color: #e74c3c !important;
        border-color: #e74c3c !important;
    }
    
    .aysa-button-success {
        background-color: #00a32a !important;
        color: white !important;
        border: 1px solid #00a32a !important;
        transition: background-color 0.2s ease !important;
    }
    
    .aysa-button-success:hover {
        background-color: #008a20 !important;
        border-color: #008a20 !important;
    }
    
    /* Force WordPress admin to respect our button styles */
    .wp-core-ui .aysa-button {
        background-image: none !important;
        text-shadow: none !important;
        font-weight: 500 !important;
        color: white !important;
    }
    
    /* Fix for SVG icons */
    .aysa-button svg {
        display: inline-block !important;
        vertical-align: middle !important;
        margin-right: 8px !important;
        fill: currentColor !important;
    }
    
    /* Ensure buttons stand out */
    .aysa-button {
        box-shadow: 0 2px 5px rgba(0,0,0,0.2) !important;
        border-radius: 4px !important;
        padding: 8px 16px !important;
    }
    
    /* Improve spinner visibility */
    .spinner.is-active {
        visibility: visible !important;
        opacity: 1 !important;
    }
    
    /* Fix text visibility issue and ensure green color */
    #generate-suggestions-btn {
        background-color: #2ea043 !important;
        border-color: #2ea043 !important;
        color: white !important;
        font-weight: 500 !important;
        font-size: 13px !important;
        text-shadow: none !important;
    }
    
    #generate-suggestions-btn:hover {
        background-color: #238636 !important;
        border-color: #238636 !important;
    }
    
    /* Override WordPress button-primary for Generate SEO buttons */
    .button-primary[id*="generate"],
    button.button-primary[onclick*="handleGenerateSuggestions"] {
        background: #2ea043 !important;
        border-color: #2ea043 !important;
        color: white !important;
    }
    
    .button-primary[id*="generate"]:hover,
    button.button-primary[onclick*="handleGenerateSuggestions"]:hover {
        background: #238636 !important;
        border-color: #238636 !important;
        color: white !important;
    }
    
    /* Make button smaller in sidebar */
    #side-sortables #generate-suggestions-btn {
        font-size: 12px !important;
        padding: 6px 10px !important;
        width: auto !important;
        min-width: 0 !important;
        max-width: 100% !important;
    }
    
    /* Adjust button group layout in sidebar */
    #side-sortables .button-group {
        flex-direction: column !important;
        margin-top: 10px !important;
        width: 100% !important;
    }
    
    /* Make all buttons in sidebar full width and properly sized */
    #side-sortables .button-group button {
        width: 100% !important;
        margin-bottom: 5px !important;
    }
    
    /* Sidebar specific adjustments */
    @media screen and (min-width: 851px) {
        #side-sortables .text-box {
            text-align: center;
        }
        
        #side-sortables #generate-suggestions-btn {
            display: inline-block !important;
            width: 100% !important;
            margin: 8px 0 !important;
            font-size: 13px !important;
        }
    }
    
    /* Ensure buttons are visible in sidebar */
    #side-sortables .accept-btn-container {
        background: transparent !important;
        border: none !important;
        padding: 10px 0 !important;
    }
    
    /* Disable and style revert buttons */
    .aysa-button[id*="reject"],
    .aysa-button[id*="revert"],
    #reject-meta-fields,
    #reject-description-field,
    #reject-category-fields {
        background-color: #ddd !important;
        border-color: #ddd !important;
        color: #999 !important;
        cursor: not-allowed !important;
        opacity: 0.5 !important;
        box-shadow: none !important;
        transform: none !important;
        pointer-events: none !important;
    }
    
    /* Ensure hover effects don't work on disabled revert buttons */
    .aysa-button[id*="reject"]:hover,
    .aysa-button[id*="revert"]:hover,
    #reject-meta-fields:hover,
    #reject-description-field:hover,
    #reject-category-fields:hover {
        background-color: #ddd !important;
        border-color: #ddd !important;
        color: #999 !important;
        transform: none !important;
        box-shadow: none !important;
    }
    
    #side-sortables .aysa-button {
        width: 100% !important;
        margin-bottom: 8px !important;
        display: block !important;
        text-align: center !important;
        font-size: 12px !important;
        padding: 8px 12px !important;
    }
    
    #side-sortables #generate-suggestions-btn {
        margin-bottom: 8px !important;
        margin-right: 0 !important;
    }
    
    /* Spinning animation for loading state */
    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
    
    /* Secondary keywords styling */
    #secondary-keywords-container {
        margin-top: 8px;
    }
    
    /* Add and secondary keyword button */
    #add-secondary-keyword-btn {
        background-color: #f0f0f0;
        border-color: #ddd;
        color: #333;
        transition: all 0.2s ease;
    }
    
    #add-secondary-keyword-btn:hover {
        background-color: #e0e0e0;
        border-color: #ccc;
    }
    
    /* Main container styles - apply border except in sidebar */
    .aysa-metabox-container {
        border: 1px solid #ccd0d4;
        border-radius: 4px;
        background-color: #fff;
        padding: 15px;
        margin-top: 20px;
        margin-bottom: 0;
        box-shadow: 0 1px 1px rgba(0,0,0,0.04);
        position: relative;
        z-index: 1;
    }
    
    /* No borders in sidebar */
    #side-sortables .aysa-metabox-container {
        border: none;
        border-radius: 0;
        background-color: transparent;
        padding: 0;
        margin-top: 0;
        box-shadow: none;
    }
    
    /* Remove borders and reduce padding for panels */
    .panel {
        border: none !important;
        padding: 10px 0 !important;
        box-shadow: none !important;
        background: transparent !important;
        margin-top: 5px !important;
    }
    
    /* Adjust inner boxes */
    .inner-box {
        border: none !important;
        padding: 0 !important;
        box-shadow: none !important;
        margin-bottom: 10px !important;
    }
    
    /* Make text boxes more compact */
    .text-box {
        margin-top: 0 !important;
        padding-top: 0 !important;
    }
    
    /* Optimize margins and spacing */
    .sub-group {
        margin-bottom: 15px !important;
    }
    
    /* Optimize tab container spacing */
    .tab-container {
        margin-bottom: 5px !important;
    }
    
    /* Optimize tab margins */
    .tabs {
        margin-bottom: 10px !important;
    }
    
    /* Add important: Hide required field indicators if any */
    .required {
        display: none !important;
    }
    
    /* Hide any error messages that might prevent form submission */
    .aysa-metabox-container .error-message,
    .aysa-metabox-container .has-error {
        display: none !important;
    }

    /* Advanced tab specific styles */
    .meta-group.robots-meta {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 15px;
        margin-bottom: 20px;
    }

    .meta-form {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px;
        background: #f9f9f9;
        border-radius: 4px;
    }

    .meta-form .label-container {
        flex: 1;
    }

    .meta-form select,
    .meta-form input[type="text"],
    .meta-form input[type="number"] {
        width: 100%;
        padding: 6px 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }

    .form-group {
        margin-bottom: 15px;
        padding: 10px;
        background: #f9f9f9;
        border-radius: 4px;
    }

    .form-group .label-container {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 8px;
    }

    .form-group input[type="text"],
    .form-group input[type="number"],
    .form-group select {
        width: 100%;
        padding: 6px 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }
</style>

<!-- Empty div for keyword modal -->
<div id="replace-keyword-modal" style="display: none;"></div>

<!-- Add a hidden field to track whether this metabox has been initialized -->
<input type="hidden" id="aysa-metabox-initialized" name="aysa_metabox_initialized" value="1">

<!-- Include scripts in correct order -->
<?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- Admin-only legacy metabox asset preserves the established conditional load order; its plugin-local URL is escaped. ?>
<script src="<?php echo esc_url(plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/js/aysa-actions.js?v=' . wp_rand(1000, 9999)); ?>"></script>
<?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- Admin-only legacy metabox asset preserves the established conditional load order; its plugin-local URL is escaped. ?>
<script src="<?php echo esc_url(plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/js/aysa-keywords.js?v=' . wp_rand(1000, 9999)); ?>"></script>
<?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- Admin-only legacy metabox asset preserves the established conditional load order; its plugin-local URL is escaped. ?>
<script src="<?php echo esc_url(plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/js/aysa-seo-chart.js?v=' . wp_rand(1000, 9999)); ?>"></script>
<?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- Admin-only legacy metabox asset preserves the established conditional load order; its plugin-local URL is escaped. ?>
<script src="<?php echo esc_url(plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/js/aysa-scoring.js?v=' . wp_rand(1000, 9999)); ?>"></script>
<?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- Admin-only legacy metabox asset preserves the established conditional load order; its plugin-local URL is escaped. ?>
<script src="<?php echo esc_url(plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/js/aysa-metabox.js?v=' . wp_rand(1000, 9999)); ?>"></script>

<div class="aysa-metabox-container aysa-metabox-unified">
    <div class="aysa-metabox-header">
        <div class="aysa-metabox-brand">
            <h2>AYSA SEO</h2>
            <span class="aysa-metabox-badge">AI SEO Co-Pilot</span>
        </div>
        <div class="aysa-metabox-credits">
            <?php 
            // Display credits in metabox with fallback
            try {
                if (class_exists('Aysa_Credits_Component')) {
                    echo wp_kses_post(Aysa_Credits_Component::display());
                } else {
                    echo '<span class="aysa-credits-fallback">Credits: Loading...</span>';
                }
            } catch (Exception $e) {
                echo '<span class="aysa-credits-fallback">Credits: Loading...</span>';
            }
            ?>
        </div>
    </div>
    
    <!-- Credits will be loaded by the main credits component script -->
    
    <div class="aysa-metabox-content">
        <ul class="tabs">
            <li data-toggle="keyword" class="active">Keyword</li>
            <li data-toggle="meta">Meta</li>
            <li data-toggle="score">Score</li>
            <li data-toggle="adv">Adv</li>
        </ul>
        
        <div class="tab-content">
            <!-- Keyword Tab -->
            <div id="keyword" class="tab-pane active">
                <div class="seo-score-box aysa-score-hero">
                    <div class="aysa-score-hero-head">
                        <div class="aysa-score-main">
                            <div class="aysa-score-main-value">
                                <span class="score-value">Calculating...</span>
                            </div>
                            <div class="aysa-score-main-label">
                                SEO Score
                            </div>
                        </div>
                        <div class="aysa-score-divider"></div>
                        <div class="aysa-score-grade-wrap">
                            <div class="aysa-score-grade-value">
                                <span class="score-grade">-</span>
                            </div>
                            <div class="aysa-score-grade-label">
                                Grade
                            </div>
                        </div>
                    </div>
                    <div class="progress-bar-container">
                        <div class="progress-bar"></div>
                    </div>
                </div>

                <!-- Generate SEO Suggestions and Accept/Reject Button for all meta fields -->
                <div class="accept-btn-container meta-fields-buttons" style="text-align: center; margin-top: 10px; margin-bottom: 20px; clear: both; padding: 15px; background: #f9f9f9; border-radius: 5px; border: 1px solid #ddd;">
                    
                    <!-- Force Regenerate Secondary Keywords Option -->
                    <div style="margin-bottom: 10px; text-align: left;">
                        <label style="display: flex; align-items: center; font-size: 13px; color: #666; cursor: pointer;">
                            <input type="checkbox" id="aysa-force-regenerate-secondary" style="margin-right: 8px; margin-top: 0;">
                            <span style="user-select: none;">Force regenerate secondary keywords (even if they exist)</span>
                        </label>
                        <div style="font-size: 11px; color: #999; margin-top: 3px; margin-left: 21px;">
                            Check this to generate new secondary keywords even if you already have some
                        </div>
                    </div>
                    
                    <button class="aysa-button aysa-button-primary" id="generate-suggestions-btn" 
                            style="margin-right: 10px; padding: 12px 24px; font-size: 14px; font-weight: 600; background-color: #2ea043 !important; color: white !important; border: 1px solid #2ea043 !important; border-radius: 5px; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"
                            onmouseover="this.style.backgroundColor='#238636'; this.style.transform='translateY(-1px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.15)';"
                            onmouseout="this.style.backgroundColor='#2ea043'; this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.1)';">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle;">
                            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                        </svg>
                        Generate SEO Suggestions
                        <span class="aysa-credit-badge cost-very-high">75 cr</span>
                    </button>
                    <button class="aysa-button aysa-button-action" id="reject-meta-fields" 
                            style="padding: 12px 20px; font-size: 14px; font-weight: 600; background-color: #ff6b6b !important; color: white !important; border: 1px solid #ff6b6b !important; border-radius: 5px; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"
                            onmouseover="this.style.backgroundColor='#e74c3c'; this.style.transform='translateY(-1px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.15)';"
                            onmouseout="this.style.backgroundColor='#ff6b6b'; this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.1)';">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style="margin-right: 8px; vertical-align: middle;">
                            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11H7v-2h10v2z"/>
                        </svg>
                        Revert
                    </button>
                    <span class="spinner" style="float: none; margin-left: 10px; vertical-align: middle;"></span>
                </div>

                <div class="inner-box">
                    <div class="sub-group">
                        <div class="keyword-row">
                            <div class="keyword-column">
                                <div class="label-container">
                                    <label for="aysa-entity-keyword"><?php esc_html_e('Keyword', 'aysaaiseo'); ?></label>
                                    <div class="tooltip">
                                        <i>i</i>
                                        <div class="tooltip-content">Main keyword for this category (optional)</div>
                                    </div>
                                </div>
                                <input type="text" id="aysa-entity-keyword" name="keyword" data-accepted="keyword"
                                       value="<?php echo isset($keyword_data['keyword']) ? esc_attr($keyword_data['keyword']) : ''; ?>">
                                <div class="bar-container">
                                    <?php 
                                    // Check if the field is empty or not
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $fieldValue = isset($keyword_data['keyword']) ? esc_attr($keyword_data['keyword']) : '';
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $perc = !empty($fieldValue) ? 100 : 0;
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $color = !empty($fieldValue) ? 'green' : 'red';
                                    ?>
                                    <div class="progress-container no-padding"
                                         style="--progress-color: var(--progress-no-padding-<?php echo esc_attr($color); ?>); width: 50%;">
                                        <div class="progress-bar" style="--percentage: <?php echo absint($perc); ?>%;"></div>
                                    </div>
                                </div>
                                <div class="keyword-actions" style="margin-top: 10px; display: flex; gap: 10px;">
                                    <!-- Improved dropdown for keyword selection -->
                                    <div class="keyword-selection-container" style="position: relative; flex: 1;">
                                        <select id="keyword-suggestions" class="keyword-dropdown" style="width: 100%; padding: 6px 20px 6px 6px; border: 1px solid #ddd; border-radius: 4px; background-color: #fff; appearance: none; font-size: 11px; cursor: pointer; background-image: url('data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M6 9l6 6 6-6\"/></svg>'); background-position: right 4px center; background-repeat: no-repeat; background-size: 12px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden;">
                                            <option value="" disabled selected>Set main</option>
                                            <!-- Secondary keywords will be populated from API data -->
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="sub-group">
                        <div class="keyword-row">
                            <div class="keyword-column">
                                <div class="label-container">
                                    <label for="aysa-entity-second-keyword-container"><?php esc_html_e('Secondary Keywords', 'aysaaiseo'); ?></label>
                                    <span id="secondary-keywords-tooltip" style="margin-left: 5px; cursor: help; display: inline-block; width: 16px; height: 16px; line-height: 16px; text-align: center; background: #666; color: #fff; border-radius: 50%; font-size: 12px; font-style: normal; position: relative;">i</span>
                                </div>
                                
                                <script>
                                document.addEventListener('DOMContentLoaded', function() {
                                    const tooltip = document.getElementById('secondary-keywords-tooltip');
                                    let tooltipDiv = null;
                                    
                                    tooltip.addEventListener('mouseenter', function() {
                                        tooltipDiv = document.createElement('div');
                                        tooltipDiv.textContent = 'These keywords are guiding';
                                        tooltipDiv.style.cssText = `
                                            position: absolute;
                                            background: #333;
                                            color: #fff;
                                            padding: 8px 12px;
                                            border-radius: 4px;
                                            font-size: 12px;
                                            white-space: nowrap;
                                            z-index: 10000;
                                            top: 25px;
                                            left: 50%;
                                            transform: translateX(-50%);
                                            pointer-events: none;
                                            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
                                        `;
                                        tooltip.appendChild(tooltipDiv);
                                    });
                                    
                                    tooltip.addEventListener('mouseleave', function() {
                                        if (tooltipDiv) {
                                            tooltipDiv.remove();
                                            tooltipDiv = null;
                                        }
                                    });
                                });
                                </script>
                                
                                <!-- Hidden input to store the actual comma-separated secondary keywords value -->
                                <input type="hidden" id="aysa-entity-second-keyword" name="second_keyword" 
                                       data-accepted="second-keyword" 
                                       value="<?php echo isset($keyword_data['second_keyword']) ? esc_attr($keyword_data['second_keyword']) : ''; ?>">
                                
                                <!-- Tags container for secondary keywords -->
                                <div id="secondary-keywords-container" class="keyword-tags-container" style="display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; min-height: 36px;">
                                    <!-- Tags will be added here dynamically -->
                                </div>
                                
                                <!-- Input for adding new secondary keywords with track checkbox -->
                                <div class="add-keyword-container" style="display: flex; align-items: center; gap: 8px; margin-top: 8px; border: 1px solid #ddd; padding: 5px 10px; border-radius: 4px; background-color: #f9f9f9;">
                                    <input type="text" id="new-secondary-keyword" placeholder="Add a secondary keyword" style="flex: 1; padding: 6px 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 12px;">
                                    
                                    <div style="display: flex; align-items: center; white-space: nowrap; margin-right: 5px;">
                                        <input type="checkbox" id="track-new-keyword" checked style="margin-right: 5px;">
                                        <label for="track-new-keyword" style="font-size: 12px;"><?php esc_html_e('Track Keyword', 'aysaaiseo'); ?></label>
                                    </div>
                                    
                                    <button type="button" id="add-secondary-keyword-btn" class="button button-secondary" style="padding: 3px 8px; font-size: 12px; min-height: 28px;">Add</button>
                                </div>
                                
                                <div class="bar-container" style="margin-top: 8px;">
                                    <?php
                                    // Check if the field is empty or not
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $fieldValue = isset($keyword_data['second_keyword']) ? esc_attr($keyword_data['second_keyword']) : '';
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $perc = !empty($fieldValue) ? 100 : 0;
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $color = !empty($fieldValue) ? 'green' : 'red';
                                    ?>
                                    <div class="progress-container no-padding"
                                         style="--progress-color: var(--progress-no-padding-<?php echo esc_attr($color); ?>); width: 50%;">
                                        <div class="progress-bar" style="--percentage: <?php echo absint($perc); ?>%;"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="sub-group meta-field-group">
                        <div class="keyword-row meta-field-row">
                            <div class="keyword-column" style="width: 100%;">
                                <div class="label-container">
                                    <label for="aysa-entity-meta-title"><?php esc_html_e('Meta title', 'aysaaiseo'); ?></label>
                                    <div class="tooltip">
                                        <i>i</i>
                                        <div class="tooltip-content">Title tag for this category page</div>
                                    </div>
                                </div>
                                <div class="character-count meta-subtitle" id="aysa-meta-title-char-count">
                                    <span class="char-count">0</span>/60 characters
                                    <span class="char-status">Outside recommended range (50-60)</span>
                                </div>
                                <textarea id="aysa-entity-meta-title" name="aysa_meta_title"
                                        data-accepted="meta-title" rows="3"
                                        style="width: 100%;"><?php echo isset($keyword_data['meta_title']) ? esc_textarea($keyword_data['meta_title']) : ''; ?></textarea>
                                <div class="bar-container">
                                    <?php
                                    // Check if the field is empty or not
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $fieldValue = isset($keyword_data['meta_title']) ? esc_attr($keyword_data['meta_title']) : '';
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $perc = !empty($fieldValue) ? 100 : 0;
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $color = !empty($fieldValue) ? 'green' : 'red';
                                    ?>
                                    <div class="progress-container no-padding"
                                         style="--progress-color: var(--progress-no-padding-<?php echo esc_attr($color); ?>); width: 50%;">
                                        <div class="progress-bar" style="--percentage: <?php echo absint($perc); ?>%;"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="sub-group meta-field-group">
                        <div class="keyword-row meta-field-row">
                            <div class="keyword-column" style="width: 100%;">
                                <div class="label-container">
                                    <label for="aysa-entity-meta-description"><?php esc_html_e('Meta description', 'aysaaiseo'); ?></label>
                                    <div class="tooltip">
                                        <i>i</i>
                                        <div class="tooltip-content">Meta description for this category page</div>
                                    </div>
                                </div>
                                <div class="character-count meta-subtitle" id="aysa-meta-description-char-count">
                                    <span class="char-count">0</span>/160 characters
                                    <span class="char-status">Outside recommended range (150-160)</span>
                                </div>
                                <textarea id="aysa-entity-meta-description" name="aysa_meta_description"
                                        data-accepted="meta-description" rows="3"
                                        style="width: 100%;"><?php echo isset($keyword_data['meta_description']) ? esc_textarea($keyword_data['meta_description']) : ''; ?></textarea>
                                <div class="bar-container">
                                    <?php
                                    // Check if the field is empty or not
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $fieldValue = isset($keyword_data['meta_description']) ? esc_attr($keyword_data['meta_description']) : '';
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $perc = !empty($fieldValue) ? 100 : 0;
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $color = !empty($fieldValue) ? 'green' : 'red';
                                    ?>
                                    <div class="progress-container no-padding"
                                         style="--progress-color: var(--progress-no-padding-<?php echo esc_attr($color); ?>); width: 50%;">
                                        <div class="progress-bar" style="--percentage: <?php echo absint($perc); ?>%;"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="sub-group meta-field-group">
                        <div class="keyword-row meta-field-row">
                            <div class="keyword-column" style="width: 100%;">
                                <div class="label-container">
                                    <label for="aysa-entity-meta-keywords"><?php esc_html_e('Meta keywords (optional)', 'aysaaiseo'); ?></label>
                                    <div class="tooltip">
                                        <i>i</i>
                                        <div class="tooltip-content">Meta keywords for this category page</div>
                                    </div>
                                </div>
                                <textarea id="aysa-entity-meta-keywords" name="aysa_meta_keywords"
                                        data-accepted="meta-keywords" rows="3"
                                        style="width: 100%;"><?php echo isset($keyword_data['meta_keywords']) ? esc_textarea($keyword_data['meta_keywords']) : ''; ?></textarea>
                                <div class="bar-container">                        
                                    <?php                        
                                    // Check if the field is empty or not                        
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $fieldValue = isset($keyword_data['meta_keywords']) ? esc_attr($keyword_data['meta_keywords']) : '';                        
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $perc = !empty($fieldValue) ? 100 : 0;                        
                                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
                                    $color = !empty($fieldValue) ? 'green' : 'red';                        
                                    ?>                        
                                    <div class="progress-container no-padding"                             
                                         style="--progress-color: var(--progress-no-padding-<?php echo esc_attr($color); ?>); width: 50%;">                            
                                        <div class="progress-bar" style="--percentage: <?php echo absint($perc); ?>%;"></div>                        
                                    </div>                    
                                </div>                
                            </div>            
                        </div>        
                    </div>
                </div>
            </div>
            
            <!-- Meta Tab -->
            <div id="meta" class="tab-pane">
                <div class="inner-box">
                    <h3>SEO Settings</h3>
                    <div class="seo-settings">
                        <div class="form-group">
                            <label for="targeted_se"><?php esc_html_e('TARGETED SE', 'aysaaiseo'); ?></label>
                            <select name="targeted_se" id="targeted_se">
                                <option value="">Select...</option>
                                <option value="google" <?php selected(isset($keyword_data['targeted_se']) && $keyword_data['targeted_se'] == 'google'); ?>>Google</option>
                                <option value="bing" <?php selected(isset($keyword_data['targeted_se']) && $keyword_data['targeted_se'] == 'bing'); ?>>Bing</option>
                                <option value="yahoo" <?php selected(isset($keyword_data['targeted_se']) && $keyword_data['targeted_se'] == 'yahoo'); ?>>Yahoo</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="targeted_country"><?php esc_html_e('Targeted Country', 'aysaaiseo'); ?></label>
                            <div class="search-input-container">
                                <input type="text" name="targeted_country" id="targeted_country" placeholder="Search..." 
                                       value="<?php echo isset($keyword_data['targeted_country']) ? esc_attr($keyword_data['targeted_country']) : ''; ?>">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="targeted_region"><?php esc_html_e('Targeted Region', 'aysaaiseo'); ?></label>
                            <div class="search-input-container">
                                <input type="text" name="targeted_region" id="targeted_region" placeholder="Search..." 
                                       value="<?php echo isset($keyword_data['targeted_region']) ? esc_attr($keyword_data['targeted_region']) : ''; ?>">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="targeted_city"><?php esc_html_e('Targeted City', 'aysaaiseo'); ?></label>
                            <input type="text" name="targeted_city" id="targeted_city" 
                                   value="<?php echo isset($keyword_data['targeted_city']) ? esc_attr($keyword_data['targeted_city']) : ''; ?>">
                        </div>
                        <div class="form-group">
                            <label for="update_frequency"><?php esc_html_e('Update frequency', 'aysaaiseo'); ?></label>
                            <select name="update_frequency" id="update_frequency">
                                <option value="">Select...</option>
                                <option value="daily" <?php selected(isset($keyword_data['update_frequency']) && $keyword_data['update_frequency'] == 'daily'); ?>>Daily</option>
                                <option value="weekly" <?php selected(isset($keyword_data['update_frequency']) && $keyword_data['update_frequency'] == 'weekly'); ?>>Weekly</option>
                                <option value="monthly" <?php selected(isset($keyword_data['update_frequency']) && $keyword_data['update_frequency'] == 'monthly'); ?>>Monthly</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="language_optimize"><?php esc_html_e('Language Optimize', 'aysaaiseo'); ?></label>
                            <input type="text" name="language_optimize" id="language_optimize" placeholder="Enter language optimization" 
                                   value="<?php echo isset($keyword_data['language_optimize']) ? esc_attr($keyword_data['language_optimize']) : ''; ?>">
                        </div>
                        <div class="form-group">
                            <label for="device_optimize"><?php esc_html_e('Device Optimize', 'aysaaiseo'); ?></label>
                            <select name="device_optimize" id="device_optimize">
                                <option value="">Select...</option>
                                <option value="desktop" <?php selected(isset($keyword_data['device_optimize']) && $keyword_data['device_optimize'] == 'desktop'); ?>>Desktop</option>
                                <option value="mobile" <?php selected(isset($keyword_data['device_optimize']) && $keyword_data['device_optimize'] == 'mobile'); ?>>Mobile</option>
                                <option value="tablet" <?php selected(isset($keyword_data['device_optimize']) && $keyword_data['device_optimize'] == 'tablet'); ?>>Tablet</option>
                                <option value="all" <?php selected(isset($keyword_data['device_optimize']) && $keyword_data['device_optimize'] == 'all'); ?>>All Devices</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Score Tab -->
            <div id="score" class="tab-pane">
                <div class="aysa-score-tab-current">
                    <div class="aysa-score-tab-current-label">Current SEO Score</div>
                    <div class="aysa-score-tab-current-value">
                        <span class="score-value">Calculating...</span><span class="aysa-score-tab-max">/10</span>
                    </div>
                </div>
                
                <!-- Chapter 1 – Page Title (Meta Title) – 8 points -->
                <div class="scoring-category">
                    <h4>Page Title (8p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">Main keyword present at the beginning</span>
                            <span class="criterion-score" data-score="3">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Length between 50–60 characters</span>
                            <span class="criterion-score" data-score="2.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Unique title</span>
                            <span class="criterion-score" data-score="2.5">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 2 – Meta Description – 5 points -->
                <div class="scoring-category">
                    <h4>Meta Description (5p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">Length 150–160 characters</span>
                            <span class="criterion-score" data-score="1.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Keyword included naturally</span>
                            <span class="criterion-score" data-score="1.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Unique</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 3 – URL (Slug) – 5 points -->
                <div class="scoring-category">
                    <h4>URL (Slug) (5p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">Keyword included</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">SEO-friendly format</span>
                            <span class="criterion-score" data-score="1.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Short and descriptive</span>
                            <span class="criterion-score" data-score="1.5">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 4 – Headings (H1–H3) – 8 points -->
                <div class="scoring-category">
                    <h4>Headings (H1–H3) (8p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">Single correct H1</span>
                            <span class="criterion-score" data-score="3">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">H1 contains main keyword</span>
                            <span class="criterion-score" data-score="2.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Logical H2, H3 structure</span>
                            <span class="criterion-score" data-score="2.5">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 5 – Content – 20 points -->
                <div class="scoring-category">
                    <h4>Content (20p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">Minimum 300 words</span>
                            <span class="criterion-score" data-score="3">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Correct keyword density</span>
                            <span class="criterion-score" data-score="3">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Synonyms and LSI terms</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Lists, bold text, short paragraphs</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Unique content</span>
                            <span class="criterion-score" data-score="3">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">TL;DR present</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">No link on main keyword</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Relevant internal and external links</span>
                            <span class="criterion-score" data-score="3">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 6 – Images – 6 points -->
                <div class="scoring-category">
                    <h4>Images (6p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">Each image has alt text</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">SEO-friendly filename</span>
                            <span class="criterion-score" data-score="1">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Optimized dimensions (&lt;200kb)</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Lazy loading active (Images)</span>
                            <span class="criterion-score" data-score="1">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 7 – Internal Links – 4 points -->
                <div class="scoring-category">
                    <h4>Internal Links (4p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">At least one internal link</span>
                            <span class="criterion-score" data-score="1.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Functional links (no 404)</span>
                            <span class="criterion-score" data-score="1.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Optimized anchor text</span>
                            <span class="criterion-score" data-score="1">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 8 – External Links – 4 points (NEW) -->
                <div class="scoring-category">
                    <h4>External Links (4p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">At least one external link</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Links are functional</span>
                            <span class="criterion-score" data-score="1">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Links to authority domains</span>
                            <span class="criterion-score" data-score="1">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 9 – Backlinks – 15 points (NEW) -->
                <div class="scoring-category">
                    <h4>Backlinks (15p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">Backlinks to domain</span>
                            <span class="criterion-score" data-score="7">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Backlinks to page</span>
                            <span class="criterion-score" data-score="6">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Source quality</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 10 – Speed & Performance – 6 points -->
                <div class="scoring-category">
                    <h4>Speed & Performance (6p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">PageSpeed > 80 on mobile</span>
                            <span class="criterion-score" data-score="3">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">CSS/JS minified</span>
                            <span class="criterion-score" data-score="2">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Lazy loading active (Performance)</span>
                            <span class="criterion-score" data-score="1">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 11 – Mobile-Friendly – 4 points -->
                <div class="scoring-category">
                    <h4>Mobile-Friendly (4p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">Responsive (Google test OK)</span>
                            <span class="criterion-score" data-score="2.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Correct UI elements (font, spacing, buttons)</span>
                            <span class="criterion-score" data-score="1.5">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <!-- Chapter 12 – Indexing & Technical SEO – 5 points -->
                <div class="scoring-category">
                    <h4>Indexing & Technical SEO (5p)</h4>
                    <ul class="scoring-criteria">
                        <li>
                            <span class="criterion-label">No unintentional noindex/nofollow tags</span>
                            <span class="criterion-score" data-score="1.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Correct canonical tag</span>
                            <span class="criterion-score" data-score="1.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Valid Schema.org</span>
                            <span class="criterion-score" data-score="1.5">Calculating...</span>
                        </li>
                        <li>
                            <span class="criterion-label">Correct hreflang (if multilingual versions exist)</span>
                            <span class="criterion-score" data-score="0.5">Calculating...</span>
                        </li>
                    </ul>
                </div>
                
                <div class="total-score-container">
                    <h4>Total SEO Score</h4>
                    <div class="score-summary">
                        <div class="score-display">
                            <span id="total-score-value">Calculating...</span>
                            <span class="score-max">/100</span>
                            <span class="score-percentage">(Calculating...)</span>
                        </div>
                        <div class="score-grade" id="score-grade">-</div>
                    </div>
                    <div class="progress-bar-container">
                        <div class="progress-bar" style="width: 0%"></div>
                    </div>
                    <div class="score-description" id="score-description">
                        The scoring system has been updated according to Google Docs. Analysis in progress...
                    </div>
                </div>
                

            </div>
            
            <!-- Advanced Tab -->
            <div id="adv" class="tab-pane">
                <div class="inner-box">
                    <h3>Robots Meta</h3>
                    <div class="meta-group robots-meta">
                        <div class="meta-form">
                            <select name="index" id="index" class="custom-select">
                                <option value="index" <?php selected(isset($keyword_data['robots_meta']['index']) && $keyword_data['robots_meta']['index'] == 'index'); ?>>Index</option>
                                <option value="noindex" <?php selected(isset($keyword_data['robots_meta']['index']) && $keyword_data['robots_meta']['index'] == 'noindex'); ?>>No Index</option>
                            </select>
                            <div class="tooltip">
                                <i>i</i>
                                <div class="tooltip-content">Control whether search engines should index this page</div>
                            </div>
                        </div>
                        <div class="meta-form">
                            <input type="checkbox" name="nofollow" id="nofollow" class="custom-checkbox" 
                                   <?php checked(isset($keyword_data['robots_meta']['nofollow']) && $keyword_data['robots_meta']['nofollow']); ?>>
                            <div class="label-container">
                                <label for="nofollow"><?php esc_html_e('No Follow', 'aysaaiseo'); ?></label>
                                <div class="tooltip">
                                    <i>i</i>
                                    <div class="tooltip-content">Prevent search engines from following links on this page</div>
                                </div>
                            </div>
                        </div>
                        <div class="meta-form">
                            <input type="checkbox" name="noarchive" id="noarchive" class="custom-checkbox" 
                                   <?php checked(isset($keyword_data['robots_meta']['noarchive']) && $keyword_data['robots_meta']['noarchive']); ?>>
                            <div class="label-container">
                                <label for="noarchive"><?php esc_html_e('No Archive', 'aysaaiseo'); ?></label>
                                <div class="tooltip">
                                    <i>i</i>
                                    <div class="tooltip-content">Prevent search engines from showing cached copies of this page</div>
                                </div>
                            </div>
                        </div>
                        <div class="meta-form">
                            <input type="checkbox" name="noimageindex" id="noimageindex" class="custom-checkbox" 
                                   <?php checked(isset($keyword_data['robots_meta']['noimageindex']) && $keyword_data['robots_meta']['noimageindex']); ?>>
                            <div class="label-container">
                                <label for="noimageindex"><?php esc_html_e('No Image Index', 'aysaaiseo'); ?></label>
                                <div class="tooltip">
                                    <i>i</i>
                                    <div class="tooltip-content">Prevent search engines from indexing images on this page</div>
                                </div>
                            </div>
                        </div>
                        <div class="meta-form">
                            <input type="checkbox" name="nosnippet" id="nosnippet" class="custom-checkbox" 
                                   <?php checked(isset($keyword_data['robots_meta']['nosnippet']) && $keyword_data['robots_meta']['nosnippet']); ?>>
                            <div class="label-container">
                                <label for="nosnippet"><?php esc_html_e('No Snippet', 'aysaaiseo'); ?></label>
                                <div class="tooltip">
                                    <i>i</i>
                                    <div class="tooltip-content">Prevent search engines from showing snippets of this page in search results</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <h3>Advanced Robots Meta</h3>
                    <div class="form-group">
                        <div class="label-container">
                            <input type="checkbox" name="max_snippet" id="max_snippet" class="custom-checkbox" 
                                   <?php checked(isset($keyword_data['advanced_robots']['max_snippet']) && $keyword_data['advanced_robots']['max_snippet']); ?>>
                            <label for="max_snippet"><?php esc_html_e('Max Snippet', 'aysaaiseo'); ?></label>
                            <div class="tooltip">
                                <i>i</i>
                                <div class="tooltip-content">Set the maximum text length for a snippet in search results</div>
                            </div>
                        </div>
                        <input type="number" name="number-max-snippet" id="number-max-snippet" 
                               value="<?php echo isset($keyword_data['advanced_robots']['max_snippet_value']) ? esc_attr($keyword_data['advanced_robots']['max_snippet_value']) : '-1'; ?>">
                    </div>
                    <div class="form-group">
                        <div class="label-container">
                            <input type="checkbox" name="max_video_preview" id="max_video_preview" class="custom-checkbox" 
                                   <?php checked(isset($keyword_data['advanced_robots']['max_video_preview']) && $keyword_data['advanced_robots']['max_video_preview']); ?>>
                            <label for="max_video_preview"><?php esc_html_e('Max Video Preview', 'aysaaiseo'); ?></label>
                            <div class="tooltip">
                                <i>i</i>
                                <div class="tooltip-content">Set the maximum second duration for a video snippet</div>
                            </div>
                        </div>
                        <input type="number" name="number-max-video-preview" id="number-max-video-preview" 
                               value="<?php echo isset($keyword_data['advanced_robots']['max_video_preview_value']) ? esc_attr($keyword_data['advanced_robots']['max_video_preview_value']) : '-1'; ?>">
                    </div>
                    <div class="form-group">
                        <div class="label-container">
                            <input type="checkbox" name="max_image_preview" id="max_image_preview" class="custom-checkbox" 
                                   <?php checked(isset($keyword_data['advanced_robots']['max_image_preview']) && $keyword_data['advanced_robots']['max_image_preview']); ?>>
                            <label for="max_image_preview"><?php esc_html_e('Max Image Preview', 'aysaaiseo'); ?></label>
                            <div class="tooltip">
                                <i>i</i>
                                <div class="tooltip-content">Set the maximum size for image previews</div>
                            </div>
                        </div>
                        <select name="image_preview" id="image_preview">
                            <option value="none" <?php selected(isset($keyword_data['advanced_robots']['image_preview']) && $keyword_data['advanced_robots']['image_preview'] == 'none'); ?>>None</option>
                            <option value="standard" <?php selected(isset($keyword_data['advanced_robots']['image_preview']) && $keyword_data['advanced_robots']['image_preview'] == 'standard'); ?>>Standard</option>
                            <option value="large" <?php selected(!isset($keyword_data['advanced_robots']['image_preview']) || $keyword_data['advanced_robots']['image_preview'] == 'large'); ?>>Large</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <div class="label-container">
                            <label for="canonical_url"><?php esc_html_e('Canonical URL', 'aysaaiseo'); ?></label>
                            <div class="tooltip">
                                <i>i</i>
                                <div class="tooltip-content">Specify the preferred URL for this page</div>
                            </div>
                        </div>
                        <input type="text" name="canonical_url" id="canonical_url" 
                               value="<?php echo isset($keyword_data['canonical_url']) ? esc_attr($keyword_data['canonical_url']) : ''; ?>">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- Admin-only legacy metabox asset is conditionally loaded at this render boundary; moving it would change the established load order, and its plugin-local URL is escaped. ?>
<link rel="stylesheet" href="<?php echo esc_url(plugin_dir_url(dirname(dirname(__FILE__))) . 'admin/css/aysa-scoring.css?v=' . wp_rand(1000, 9999)); ?>">
