/**
 * Auto Create Categories JavaScript
 * Handles UI interactions for auto category tree generation
 */

(function($) {
    'use strict';
    
    let categoryTreeData = null;
    
    $(document).ready(function() {
        // Inject meta box into category page - move to left column
        injectMetaBox();
        
        // Also try after a delay to ensure DOM is fully loaded
        setTimeout(function() {
            injectMetaBox();
        }, 500);
        
        // Modal handlers
        $('#open-auto-categories-modal').on('click', openModal);
        $('#close-auto-categories-modal').on('click', closeModal);
        $('#auto-create-categories-overlay').on('click', function(e) {
            // Close modal when clicking on overlay (but not on modal itself)
            if ($(e.target).is('#auto-create-categories-overlay')) {
                closeModal();
            }
        });
        
        // Close modal on ESC key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $('#auto-create-categories-overlay').is(':visible')) {
                closeModal();
            }
        });
        
        // Event handlers
        $('#generate-category-tree').on('click', handleGenerateTree);
        $('#add-categories').on('click', handleAddCategories);
        $('#prev-to-step-1').on('click', handleBackToStep1);
        
        // Handle category editing - click on text to edit
        $(document).on('click', '.category-name.editable', handleEditCategory);
        $(document).on('click', '.edit-category-btn', handleEditCategory);
        $(document).on('click', '.delete-category-btn', handleDeleteCategory);
        $(document).on('blur', '.category-name-input', handleSaveCategoryEdit);
        $(document).on('keypress', '.category-name-input', function(e) {
            if (e.which === 13) { // Enter key
                $(this).blur();
            }
        });
        
        // Auto Write Descriptions handlers
        $('#open-auto-descriptions-modal').on('click', openDescriptionsModal);
        $('#close-auto-descriptions-modal').on('click', closeDescriptionsModal);
        $('#auto-write-descriptions-overlay').on('click', function(e) {
            if ($(e.target).is('#auto-write-descriptions-overlay')) {
                closeDescriptionsModal();
            }
        });
        $('#start-generate-descriptions').on('click', handleStartGenerateDescriptions);
        $('#desc-prev-to-step-1').on('click', handleBackToDescStep1);
        
        // Load categories when modal opens
        $(document).on('click', '#open-auto-descriptions-modal', function() {
            loadCategories();
        });
        
        // Refresh cron status when refresh button clicked
        $('#refresh-cron-status').on('click', function() {
            const $btn = $(this);
            $btn.addClass('loading').prop('disabled', true);
            setTimeout(function() {
                $btn.removeClass('loading').prop('disabled', false);
            }, 1000);
        });
        
        // Cron Status Modal handlers
        $('#open-cron-status-modal').on('click', openCronStatusModal);
        $('#close-cron-status-modal').on('click', closeCronStatusModal);
        $('#cron-status-overlay').on('click', function(e) {
            if ($(e.target).is('#cron-status-overlay')) {
                closeCronStatusModal();
            }
        });
        $('#refresh-cron-status-modal').on('click', function() {
            loadCronStatusModal();
        });
    });
    
    /**
     * Inject meta box into category page - move to left column
     */
    function injectMetaBox() {
        // Check if we're on taxonomy edit page
        if (window.location.href.indexOf('edit-tags.php') === -1) {
            return;
        }
        
        // Check if already moved
        if ($('#auto-create-categories-meta-box').closest('#auto-create-categories-container').length > 0) {
            return;
        }
        
        const $metaBox = $('#auto-create-categories-meta-box');
        
        if (!$metaBox.length) {
            return;
        }
        
        let $target = null;
        let $container = $('#auto-create-categories-container');
        
        // Method 1: Try to find form#addtag or form#edittag and inject before it
        const $form = $('form#addtag, form#edittag').first();
        if ($form.length) {
            if (!$container.length) {
                $container = $('<div id="auto-create-categories-container" class="auto-create-categories-container-left"></div>');
                $container.insertBefore($form);
            }
            $target = $container;
        }
        
        // Method 2: Try to find .form-wrap (WordPress taxonomy form wrapper)
        if (!$target || !$target.length) {
            const $formWrap = $('.form-wrap').first();
            if ($formWrap.length) {
                if (!$container.length) {
                    $container = $('<div id="auto-create-categories-container" class="auto-create-categories-container-left"></div>');
                    $container.insertBefore($formWrap);
                }
                $target = $container;
            }
        }
        
        // Method 3: Try to find #col-left (WordPress left column)
        if (!$target || !$target.length) {
            $target = $('#col-left').first();
            if ($target.length && !$container.length) {
                $container = $('<div id="auto-create-categories-container" class="auto-create-categories-container-left"></div>');
                $container.prependTo($target);
                $target = $container;
            }
        }
        
        // Method 4: Try to find .wrap and prepend to it
        if (!$target || !$target.length) {
            const $wrap = $('.wrap').first();
            if ($wrap.length) {
                if (!$container.length) {
                    $container = $('<div id="auto-create-categories-container" class="auto-create-categories-container-left"></div>');
                    $container.prependTo($wrap);
                }
                $target = $container;
            }
        }
        
        // Move meta box to target
        if ($target && $target.length) {
            $metaBox.detach().appendTo($target).show();
        } else {
            // Fallback: just show it where it is
            $metaBox.show();
        }
    }
    
    /**
     * Open modal
     */
    function openModal() {
        $('#auto-create-categories-overlay').fadeIn(300);
        $('body').css('overflow', 'hidden'); // Prevent body scroll
        // Reset to step 1
        goToStep(1);
        // Clear form
        $('#category-topic').val('');
        $('#error-message').hide();
        categoryTreeData = null;
    }
    
    /**
     * Close modal
     */
    function closeModal() {
        $('#auto-create-categories-overlay').fadeOut(300);
        $('body').css('overflow', ''); // Restore body scroll
    }
    
    /**
     * Handle generate category tree
     */
    function handleGenerateTree() {
        const topic = $('#category-topic').val().trim();
        const language = $('#category-language').val() || 'en';
        
        if (!topic) {
            alert(autoCreateCategories.strings.please_enter_topic || autoCreateCategories.strings.error || 'Please enter a topic');
            return;
        }
        
        // Show loading
        $('#loading-indicator').show();
        $('#error-message').hide();
        $('#generate-category-tree').prop('disabled', true);
        
        // Call AJAX
        $.ajax({
            url: autoCreateCategories.ajaxurl,
            type: 'POST',
            data: {
                action: 'aiautotool_generate_category_tree',
                nonce: autoCreateCategories.nonce,
                topic: topic,
                language: language
            },
            success: function(response) {
                $('#loading-indicator').hide();
                $('#generate-category-tree').prop('disabled', false);
                
                if (response.success) {
                    // Handle nested data structure (response.data.data) or direct (response.data)
                    const categoryData = response.data.data || response.data;
                    categoryTreeData = categoryData;
                    displayCategoryTree(categoryData);
                    // Move to step 2
                    goToStep(2);
                } else {
                    const errorMsg = (response.data && response.data.message) ? response.data.message : (response.data || autoCreateCategories.strings.error);
                    showError(errorMsg);
                }
            },
            error: function(xhr, status, error) {
                $('#loading-indicator').hide();
                $('#generate-category-tree').prop('disabled', false);
                showError(autoCreateCategories.strings.error + ': ' + error);
            }
        });
    }
    
    /**
     * Display category tree
     */
    function displayCategoryTree(data) {
        const $container = $('#category-tree-preview');
        $container.empty();
        
        // Handle nested data structure
        if (data && data.data) {
            data = data.data;
        }
        
        if (!data || !data.categoryTree || !Array.isArray(data.categoryTree)) {
            $container.html('<p class="error-message">' + (autoCreateCategories.strings.invalid_data || 'Invalid data') + '</p>');
            console.error('Invalid category tree data:', data);
            return;
        }
        
        const $treeList = $('<ul class="category-tree-list level-0"></ul>');
        
        data.categoryTree.forEach(function(mainCat, index) {
            const $mainItem = createCategoryItem(mainCat.category, 0, index);
            const $subList = $('<ul class="category-tree-list level-1"></ul>');
            
            if (mainCat.sub && Array.isArray(mainCat.sub)) {
                mainCat.sub.forEach(function(sub1, subIndex) {
                    const $sub1Item = createCategoryItem(sub1.subCategory, 1, index + '-' + subIndex);
                    const $sub2List = $('<ul class="category-tree-list level-2"></ul>');
                    
                    if (sub1.sub && Array.isArray(sub1.sub)) {
                        sub1.sub.forEach(function(sub2, sub2Index) {
                            const $sub2Item = createCategoryItem(sub2, 2, index + '-' + subIndex + '-' + sub2Index);
                            $sub2List.append($sub2Item);
                        });
                    }
                    
                    if ($sub2List.children().length > 0) {
                        $sub1Item.find('.category-row').after($sub2List);
                    }
                    
                    $subList.append($sub1Item);
                });
            }
            
            if ($subList.children().length > 0) {
                $mainItem.find('.category-row').after($subList);
            }
            
            $treeList.append($mainItem);
        });
        
        $container.append($treeList);
    }
    
    /**
     * Create category item element
     */
    function createCategoryItem(name, level, uniqueId) {
        const $item = $('<li class="category-item" data-level="' + level + '" data-id="' + uniqueId + '"></li>');
        const $row = $('<div class="category-row"></div>');
        const $name = $('<span class="category-name editable" data-original="' + escapeHtml(name) + '">' + escapeHtml(name) + '</span>');
        const $actions = $('<div class="category-item-actions"></div>');
        
        // Only show delete button, edit is done by clicking on text
        const deleteText = autoCreateCategories.strings.delete || 'Delete';
        const $deleteBtn = $('<button type="button" class="button delete-category delete-category-btn" title="' + deleteText + '">' +
                            '<i class="fa-solid fa-trash"></i> <span class="sr-only">' + deleteText + '</span></button>');
        
        $actions.append($deleteBtn);
        $row.append($name).append($actions);
        $item.append($row);
        
        return $item;
    }
    
    /**
     * Handle edit category
     */
    function handleEditCategory(e) {
        e.preventDefault();
        e.stopPropagation();
        
        // Check if already editing
        if ($(this).hasClass('category-name-input')) {
            return;
        }
        
        const $target = $(this);
        let $name;
        
        // If clicked on button, find the name element
        if ($target.hasClass('edit-category-btn')) {
            const $item = $target.closest('.category-item');
            $name = $item.find('.category-name');
        } else {
            // Clicked directly on category name
            $name = $target;
        }
        
        // Check if already in edit mode
        if ($name.length === 0 || $name.hasClass('category-name-input')) {
            return;
        }
        
        const originalName = $name.data('original') || $name.text();
        
        // Convert to input
        const $input = $('<input type="text" class="category-name-input regular-text" value="' + escapeHtml(originalName) + '" />');
        $name.replaceWith($input);
        $input.focus().select();
    }
    
    /**
     * Handle save category edit
     */
    function handleSaveCategoryEdit() {
        const $input = $(this);
        const $item = $input.closest('.category-item');
        const newName = $input.val().trim();
        
        if (!newName) {
            // Restore original
            const originalName = $item.find('.category-name').data('original') || $input.val();
            const $name = $('<span class="category-name editable" data-original="' + escapeHtml(originalName) + '">' + escapeHtml(originalName) + '</span>');
            $input.replaceWith($name);
            return;
        }
        
        // Update in tree data
        updateCategoryInTree($item, newName);
        
        // Replace with span
        const $name = $('<span class="category-name editable" data-original="' + escapeHtml(newName) + '">' + escapeHtml(newName) + '</span>');
        $input.replaceWith($name);
    }
    
    /**
     * Update category name in tree data
     */
    function updateCategoryInTree($item, newName) {
        if (!categoryTreeData) return;
        
        const itemId = $item.data('id');
        const level = $item.data('level');
        const parts = itemId.split('-');
        
        if (level === 0) {
            // Main category
            const index = parseInt(parts[0]);
            if (categoryTreeData.categoryTree[index]) {
                categoryTreeData.categoryTree[index].category = newName;
            }
        } else if (level === 1) {
            // Sub category level 1
            const mainIndex = parseInt(parts[0]);
            const subIndex = parseInt(parts[1]);
            if (categoryTreeData.categoryTree[mainIndex] && 
                categoryTreeData.categoryTree[mainIndex].sub[subIndex]) {
                categoryTreeData.categoryTree[mainIndex].sub[subIndex].subCategory = newName;
            }
        } else if (level === 2) {
            // Sub category level 2
            const mainIndex = parseInt(parts[0]);
            const subIndex = parseInt(parts[1]);
            const sub2Index = parseInt(parts[2]);
            if (categoryTreeData.categoryTree[mainIndex] && 
                categoryTreeData.categoryTree[mainIndex].sub[subIndex] &&
                categoryTreeData.categoryTree[mainIndex].sub[subIndex].sub[sub2Index]) {
                categoryTreeData.categoryTree[mainIndex].sub[subIndex].sub[sub2Index] = newName;
            }
        }
    }
    
    /**
     * Handle delete category
     */
    function handleDeleteCategory(e) {
        e.preventDefault();
        
        if (!confirm(autoCreateCategories.strings.confirm_delete || 'Are you sure you want to delete this category?')) {
            return;
        }
        
        const $btn = $(this);
        const $item = $btn.closest('.category-item');
        
        // Remove from tree data
        removeCategoryFromTree($item);
        
        // Remove from DOM
        $item.fadeOut(300, function() {
            $(this).remove();
        });
    }
    
    /**
     * Remove category from tree data
     */
    function removeCategoryFromTree($item) {
        if (!categoryTreeData) return;
        
        const itemId = $item.data('id');
        const level = $item.data('level');
        const parts = itemId.split('-');
        
        if (level === 0) {
            // Remove main category
            const index = parseInt(parts[0]);
            categoryTreeData.categoryTree.splice(index, 1);
            // Re-render tree
            displayCategoryTree(categoryTreeData);
        } else if (level === 1) {
            // Remove sub category level 1
            const mainIndex = parseInt(parts[0]);
            const subIndex = parseInt(parts[1]);
            if (categoryTreeData.categoryTree[mainIndex] && 
                categoryTreeData.categoryTree[mainIndex].sub) {
                categoryTreeData.categoryTree[mainIndex].sub.splice(subIndex, 1);
                // Re-render tree
                displayCategoryTree(categoryTreeData);
            }
        } else if (level === 2) {
            // Remove sub category level 2
            const mainIndex = parseInt(parts[0]);
            const subIndex = parseInt(parts[1]);
            const sub2Index = parseInt(parts[2]);
            if (categoryTreeData.categoryTree[mainIndex] && 
                categoryTreeData.categoryTree[mainIndex].sub[subIndex] &&
                categoryTreeData.categoryTree[mainIndex].sub[subIndex].sub) {
                categoryTreeData.categoryTree[mainIndex].sub[subIndex].sub.splice(sub2Index, 1);
                // Just remove from DOM, no need to re-render
            }
        }
    }
    
    /**
     * Handle add categories
     */
    function handleAddCategories() {
        if (!categoryTreeData || !categoryTreeData.categoryTree) {
            alert(autoCreateCategories.strings.no_data_to_add || 'No category data to add');
            return;
        }
        
        // Show progress
        $('#add-progress').show();
        $('#add-categories').prop('disabled', true);
        $('#success-message').hide();
        
        $('#progress-fill').css('width', '0%').text('0%');
        $('#progress-text').text(autoCreateCategories.strings.creating || 'Creating categories...');
        
        // Get current taxonomy
        const currentTaxonomy = getCurrentTaxonomy();
        
        // Send entire tree to server
        $.ajax({
            url: autoCreateCategories.ajaxurl,
            type: 'POST',
            data: {
                action: 'aiautotool_create_categories',
                nonce: autoCreateCategories.nonce,
                categoryTree: categoryTreeData.categoryTree,
                taxonomy: currentTaxonomy
            },
            success: function(response) {
                $('#add-progress').hide();
                $('#add-categories').prop('disabled', false);
                
                if (response.success) {
                    const total = response.data.total || 0;
                    const categoriesText = autoCreateCategories.strings.categories || 'categories';
                    const errorsText = autoCreateCategories.strings.errors || 'Errors';
                    let message = (autoCreateCategories.strings.created_successfully || 'Created successfully') + ' ' + total + ' ' + categoriesText + '!';
                    if (response.data.errors && response.data.errors.length > 0) {
                        message += '<br><strong>' + errorsText + ':</strong><br>' + response.data.errors.join('<br>');
                    }
                    $('#success-message').html(message).show();
                    
                    // Close modal and reload page after 3 seconds
                    setTimeout(function() {
                        closeModal();
                        window.location.reload();
                    }, 3000);
                } else {
                    showError(response.data.message || (autoCreateCategories.strings.error_occurred || autoCreateCategories.strings.error || 'An error occurred while creating categories'));
                }
            },
            error: function(xhr, status, error) {
                $('#add-progress').hide();
                $('#add-categories').prop('disabled', false);
                showError((autoCreateCategories.strings.error || 'Error') + ': ' + error);
            }
        });
    }
    
    /**
     * Go to specific step
     */
    function goToStep(stepNumber) {
        // Hide all steps
        $('.step-content').hide();
        
        // Show target step
        $('#step-' + stepNumber).show();
        
        // Update step header
        $('.step-item').removeClass('active completed');
        $('.step-connector').removeClass('completed');
        
        if (stepNumber === 1) {
            $('.step-item[data-step="1"]').addClass('active');
        } else if (stepNumber === 2) {
            $('.step-item[data-step="1"]').addClass('completed');
            $('.step-item[data-step="2"]').addClass('active');
            $('.step-connector').addClass('completed');
        }
    }
    
    /**
     * Handle back to step 1
     */
    function handleBackToStep1() {
        $('#category-tree-preview').empty();
        $('#add-progress').hide();
        $('#success-message').hide();
        categoryTreeData = null;
        goToStep(1);
    }
    
    /**
     * Show error message
     */
    function showError(message) {
        $('#error-message').text(message).show();
    }
    
    /**
     * Escape HTML
     */
    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    /**
     * ========================================
     * AUTO WRITE DESCRIPTIONS FEATURE
     * ========================================
     */
    
    let selectedCategories = [];
    let descriptionQueue = [];
    let isProcessing = false;
    let useCron = false;
    
    /**
     * Open descriptions modal
     */
    function openDescriptionsModal() {
        $('#auto-write-descriptions-overlay').fadeIn(300);
        $('body').css('overflow', 'hidden');
        goToDescStep(1);
        selectedCategories = [];
        descriptionQueue = [];
        isProcessing = false;
        $('#desc-error-message').hide();
        $('#desc-success-message').hide();
        $('#desc-progress').hide();
    }
    
    /**
     * Close descriptions modal
     */
    function closeDescriptionsModal() {
        $('#auto-write-descriptions-overlay').fadeOut(300);
        $('body').css('overflow', '');
    }
    
    /**
     * Get current taxonomy from URL or default to 'category'
     */
    function getCurrentTaxonomy() {
        const urlParams = new URLSearchParams(window.location.search);
        const taxonomy = urlParams.get('taxonomy') || 'category';
        return taxonomy;
    }
    
    /**
     * Load categories list
     */
    function loadCategories() {
        $('#categories-loading').show();
        $('#categories-list').hide();
        
        const currentTaxonomy = getCurrentTaxonomy();
        
        $.ajax({
            url: autoCreateCategories.ajaxurl,
            type: 'POST',
            data: {
                action: 'aiautotool_get_categories',
                nonce: autoCreateCategories.nonce,
                taxonomy: currentTaxonomy
            },
            success: function(response) {
                $('#categories-loading').hide();
                
                if (response.success && response.data) {
                    displayCategoriesList(response.data);
                    $('#categories-list').show();
                } else {
                    showDescError(response.data && response.data.message ? response.data.message : 'Failed to load categories');
                }
            },
            error: function(xhr, status, error) {
                $('#categories-loading').hide();
                showDescError('Error loading categories: ' + error);
            }
        });
    }
    
    /**
     * Display categories list with checkboxes
     */
    function displayCategoriesList(categories) {
        const $container = $('#categories-list');
        $container.empty();
        
        // Build hierarchical structure
        const categoryMap = {};
        const rootCategories = [];
        
        categories.forEach(function(cat) {
            categoryMap[cat.id] = cat;
            cat.children = [];
        });
        
        categories.forEach(function(cat) {
            if (cat.parent === 0) {
                rootCategories.push(cat);
            } else if (categoryMap[cat.parent]) {
                categoryMap[cat.parent].children.push(cat);
            }
        });
        
        function renderCategory(cat, level = 0) {
            const indent = level * 20;
            const hasDesc = cat.has_description ? '<span style="color: #00a32a; font-size: 12px; margin-left: 8px;"><i class="fa-solid fa-check"></i> ' + (autoCreateCategories.strings.completed || 'Has description') + '</span>' : '';
            
            const $item = $('<div class="category-select-item" style="padding: 8px 0; padding-left: ' + indent + 'px;"></div>');
            const $checkbox = $('<input type="checkbox" class="category-checkbox" value="' + cat.id + '" data-name="' + escapeHtml(cat.name) + '" style="margin-right: 8px;">');
            const $label = $('<label style="cursor: pointer; font-weight: ' + (level === 0 ? '600' : '400') + ';">' + escapeHtml(cat.name) + ' ' + hasDesc + '</label>');
            
            $label.prepend($checkbox);
            $item.append($label);
            
            if (cat.children && cat.children.length > 0) {
                cat.children.forEach(function(child) {
                    $item.append(renderCategory(child, level + 1));
                });
            }
            
            return $item;
        }
        
        rootCategories.forEach(function(cat) {
            $container.append(renderCategory(cat));
        });
        
        // Handle checkbox changes
        $('.category-checkbox').on('change', function() {
            const categoryId = parseInt($(this).val());
            const categoryName = $(this).data('name');
            
            if ($(this).is(':checked')) {
                if (selectedCategories.indexOf(categoryId) === -1) {
                    selectedCategories.push(categoryId);
                }
            } else {
                selectedCategories = selectedCategories.filter(id => id !== categoryId);
            }
        });
    }
    
    /**
     * Handle start generating descriptions
     */
    function handleStartGenerateDescriptions() {
        if (selectedCategories.length === 0) {
            alert(autoCreateCategories.strings.select_categories_first || 'Please select at least one category');
            return;
        }
        
        useCron = $('#enable-cron-desc').is(':checked');
        
        if (useCron) {
            // Schedule cron job
            scheduleCronDescriptions();
            showDescSuccess('Categories queued for background processing. Descriptions will be generated automatically.');
            setTimeout(function() {
                closeDescriptionsModal();
            }, 2000);
        } else {
            // Process immediately
            descriptionQueue = selectedCategories.slice();
            goToDescStep(2);
            processDescriptionsQueue();
        }
    }
    
    /**
     * Schedule cron job for descriptions
     */
    function scheduleCronDescriptions() {
        const currentTaxonomy = getCurrentTaxonomy();
        
        // Save pending categories to option and schedule cron
        $.ajax({
            url: autoCreateCategories.ajaxurl,
            type: 'POST',
            data: {
                action: 'aiautotool_schedule_cron_descriptions',
                nonce: autoCreateCategories.nonce,
                category_ids: selectedCategories,
                taxonomy: currentTaxonomy
            },
            success: function(response) {
                if (response.success) {
                    // Cron will be scheduled on server side
                    console.log('Cron scheduled successfully');
                } else {
                    showDescError(response.data && response.data.message ? response.data.message : 'Failed to schedule cron');
                }
            },
            error: function(xhr, status, error) {
                showDescError('Error scheduling cron: ' + error);
            }
        });
    }
    
    /**
     * Process descriptions queue
     */
    function processDescriptionsQueue() {
        if (isProcessing || descriptionQueue.length === 0) {
            if (descriptionQueue.length === 0 && !isProcessing) {
                // All done
                showDescSuccess(autoCreateCategories.strings.all_descriptions_completed || 'All descriptions completed!');
                $('#desc-prev-to-step-1').show();
            }
            return;
        }
        
        isProcessing = true;
        const categoryId = descriptionQueue.shift();
        
        // Find category name
        const categoryName = $('.category-checkbox[value="' + categoryId + '"]').data('name') || 'Category #' + categoryId;
        
        // Update progress UI
        updateDescriptionProgress(categoryId, categoryName, 'processing');
        
        // Generate description
        const currentTaxonomy = getCurrentTaxonomy();
        
        $.ajax({
            url: autoCreateCategories.ajaxurl,
            type: 'POST',
            data: {
                action: 'aiautotool_generate_category_description',
                nonce: autoCreateCategories.nonce,
                category_id: categoryId,
                taxonomy: currentTaxonomy
            },
            success: function(response) {
                if (response.success && response.data) {
                    // Save description
                    saveCategoryDescription(categoryId, response.data.description, categoryName);
                } else {
                    updateDescriptionProgress(categoryId, categoryName, 'failed', response.data && response.data.message ? response.data.message : 'Failed to generate');
                    isProcessing = false;
                    processDescriptionsQueue();
                }
            },
            error: function(xhr, status, error) {
                updateDescriptionProgress(categoryId, categoryName, 'failed', 'Error: ' + error);
                isProcessing = false;
                processDescriptionsQueue();
            }
        });
    }
    
    /**
     * Save category description
     */
    function saveCategoryDescription(categoryId, description, categoryName) {
        const currentTaxonomy = getCurrentTaxonomy();
        
        $.ajax({
            url: autoCreateCategories.ajaxurl,
            type: 'POST',
            data: {
                action: 'aiautotool_save_category_description',
                nonce: autoCreateCategories.nonce,
                category_id: categoryId,
                description: description,
                taxonomy: currentTaxonomy
            },
            success: function(response) {
                if (response.success) {
                    updateDescriptionProgress(categoryId, categoryName, 'completed');
                } else {
                    updateDescriptionProgress(categoryId, categoryName, 'failed', response.data && response.data.message ? response.data.message : 'Failed to save');
                }
                isProcessing = false;
                
                // Update overall progress
                updateOverallProgress();
                
                // Process next
                setTimeout(function() {
                    processDescriptionsQueue();
                }, 500);
            },
            error: function(xhr, status, error) {
                updateDescriptionProgress(categoryId, categoryName, 'failed', 'Error saving: ' + error);
                isProcessing = false;
                processDescriptionsQueue();
            }
        });
    }
    
    /**
     * Update description progress for single category
     */
    function updateDescriptionProgress(categoryId, categoryName, status, message = '') {
        let $item = $('#desc-item-' + categoryId);
        
        if ($item.length === 0) {
            $item = $('<div id="desc-item-' + categoryId + '" class="desc-progress-item" style="padding: 12px; margin-bottom: 10px; border: 1px solid #e5e5e5; border-radius: 4px; background: #fff;"></div>');
            $('#descriptions-progress-list').append($item);
        }
        
        let statusIcon = '';
        let statusClass = '';
        
        if (status === 'processing') {
            statusIcon = '<i class="fa-solid fa-spinner fa-spin" style="color: #2271b1;"></i>';
            statusClass = 'processing';
        } else if (status === 'completed') {
            statusIcon = '<i class="fa-solid fa-check-circle" style="color: #00a32a;"></i>';
            statusClass = 'completed';
        } else if (status === 'failed') {
            statusIcon = '<i class="fa-solid fa-times-circle" style="color: #d63638;"></i>';
            statusClass = 'failed';
        }
        
        const statusText = status === 'processing' ? (autoCreateCategories.strings.processing || 'Processing...') :
                          status === 'completed' ? (autoCreateCategories.strings.completed || 'Completed') :
                          (autoCreateCategories.strings.failed || 'Failed');
        
        $item.html(
            '<div style="display: flex; align-items: center; justify-content: space-between;">' +
            '<div><strong>' + escapeHtml(categoryName) + '</strong> ' + statusIcon + ' <span style="margin-left: 8px;">' + statusText + '</span></div>' +
            (message ? '<div style="color: #646970; font-size: 12px;">' + escapeHtml(message) + '</div>' : '') +
            '</div>'
        );
        
        $item.removeClass('processing completed failed').addClass(statusClass);
    }
    
    /**
     * Update overall progress
     */
    function updateOverallProgress() {
        const total = selectedCategories.length;
        const completed = $('.desc-progress-item.completed').length;
        const failed = $('.desc-progress-item.failed').length;
        const processed = completed + failed;
        
        const percentage = total > 0 ? Math.round((processed / total) * 100) : 0;
        
        $('#desc-progress').show();
        $('#desc-progress-fill').css('width', percentage + '%').text(percentage + '%');
        $('#desc-progress-text').text(
            processed + ' / ' + total + ' ' + (autoCreateCategories.strings.categories || 'categories') + 
            ' (' + completed + ' ' + (autoCreateCategories.strings.completed || 'completed') + 
            (failed > 0 ? ', ' + failed + ' ' + (autoCreateCategories.strings.failed || 'failed') : '') + ')'
        );
    }
    
    /**
     * Go to specific description step
     */
    function goToDescStep(stepNumber) {
        $('.step-content[id^="desc-step-"]').hide();
        $('#desc-step-' + stepNumber).show();
        
        $('.step-item').removeClass('active completed');
        $('.step-connector').removeClass('completed');
        
        if (stepNumber === 1) {
            $('.step-item[data-step="1"]').addClass('active');
        } else if (stepNumber === 2) {
            $('.step-item[data-step="1"]').addClass('completed');
            $('.step-item[data-step="2"]').addClass('active');
            $('.step-connector').addClass('completed');
            $('#desc-progress').show();
            updateOverallProgress();
        }
    }
    
    /**
     * Handle back to step 1
     */
    function handleBackToDescStep1() {
        $('#descriptions-progress-list').empty();
        $('#desc-progress').hide();
        $('#desc-success-message').hide();
        selectedCategories = [];
        descriptionQueue = [];
        isProcessing = false;
        goToDescStep(1);
    }
    
    /**
     * Show error message for descriptions
     */
    function showDescError(message) {
        $('#desc-error-message').text(message).show();
    }
    
    /**
     * Show success message for descriptions
     */
    function showDescSuccess(message) {
        $('#desc-success-message').html(message).show();
    }
    
    /**
     * ========================================
     * CRON STATUS MODAL
     * ========================================
     */
    
    /**
     * Open cron status modal
     */
    function openCronStatusModal() {
        $('#cron-status-overlay').fadeIn(300);
        $('body').css('overflow', 'hidden');
        loadCronStatusModal();
    }
    
    /**
     * Close cron status modal
     */
    function closeCronStatusModal() {
        $('#cron-status-overlay').fadeOut(300);
        $('body').css('overflow', '');
    }
    
    /**
     * Load cron status for modal
     */
    function loadCronStatusModal() {
        const taxonomy = getCurrentTaxonomy();
        const $content = $('#cron-status-modal-content');
        
        $content.html('<div class="loading-indicator"><div class="spinner is-active"></div><p>Loading cron status...</p></div>');
        
        $.ajax({
            url: autoCreateCategories.ajaxurl,
            type: 'POST',
            data: {
                action: 'aiautotool_get_cron_descriptions_status',
                nonce: autoCreateCategories.nonce,
                taxonomy: taxonomy
            },
            success: function(response) {
                if (response.success) {
                    displayCronStatusModal(response.data);
                } else {
                    $content.html('<p class="error-message">' + (response.data && response.data.message ? response.data.message : 'Error loading status') + '</p>');
                }
            },
            error: function() {
                $content.html('<p class="error-message">Error loading cron status</p>');
            }
        });
    }
    
    /**
     * Display cron status in modal
     */
    function displayCronStatusModal(data) {
        const taxonomy = getCurrentTaxonomy();
        let html = '';
        
        // Overall summary
        html += '<div class="cron-status-summary" style="margin-bottom: 25px;">';
        html += '<div class="status-item">';
        html += '<span class="status-label">' + (autoCreateCategories.strings.pending || 'Pending:') + '</span>';
        html += '<span class="status-value pending">' + data.pending_count + '</span>';
        html += '</div>';
        html += '<div class="status-item">';
        html += '<span class="status-label">' + (autoCreateCategories.strings.completed_label || 'Completed:') + '</span>';
        html += '<span class="status-value completed">' + data.completed_count + '</span>';
        html += '</div>';
        if (data.cron_active) {
            html += '<div class="status-item">';
            html += '<span class="status-label">' + (autoCreateCategories.strings.next_run || 'Next Run:') + '</span>';
            html += '<span class="status-value">' + escapeHtml(data.next_run) + '</span>';
            html += '</div>';
        } else {
            html += '<div class="status-item">';
            html += '<span class="status-label">' + (autoCreateCategories.strings.cron_status || 'Cron Status:') + '</span>';
            html += '<span class="status-value" style="color: #d63638;">' + (autoCreateCategories.strings.not_scheduled || 'Not Scheduled') + '</span>';
            html += '</div>';
        }
        html += '</div>';
        
        // Next category to process
        if (data.next_category) {
            html += '<div class="cron-status-section" style="background: #f0f7ff; border-left: 4px solid #4facfe; padding: 15px; border-radius: 4px; margin-bottom: 20px;">';
            html += '<h4 style="margin: 0 0 10px 0; display: flex; align-items: center; gap: 8px;">';
            html += '<i class="fa-solid fa-arrow-right" style="color: #4facfe;"></i> ';
            html += (autoCreateCategories.strings.next_category || 'Next Category to Process');
            html += '</h4>';
            html += '<p style="margin: 0; font-size: 15px; font-weight: 600; color: #23282d;">';
            html += '<i class="fa-solid fa-tag"></i> ' + escapeHtml(data.next_category.name);
            html += ' <span style="color: #646970; font-size: 13px; font-weight: normal;">(' + (autoCreateCategories.strings.position || 'Position') + ': ' + (data.next_category.position || 1) + ')</span>';
            html += '</p>';
            html += '</div>';
        }
        
        // Pending list
        if (data.pending && data.pending.length > 0) {
            html += '<div class="cron-status-section">';
            html += '<h4><i class="fa-solid fa-clock"></i> ' + (autoCreateCategories.strings.pending_categories || 'Pending Categories') + ' <span class="badge">' + data.pending.length + '</span></h4>';
            html += '<div style="max-height: 300px; overflow-y: auto;">';
            html += '<table class="widefat" style="margin-top: 10px;">';
            html += '<thead><tr>';
            html += '<th style="width: 50px;">' + (autoCreateCategories.strings.no || 'No.') + '</th>';
            html += '<th>' + (autoCreateCategories.strings.category_name || 'Category Name') + '</th>';
            html += '<th>' + (autoCreateCategories.strings.taxonomy || 'Taxonomy') + '</th>';
            html += '<th>' + (autoCreateCategories.strings.status || 'Status') + '</th>';
            html += '</tr></thead>';
            html += '<tbody>';
            data.pending.forEach(function(cat, index) {
                html += '<tr>';
                html += '<td><strong>' + (cat.position || (index + 1)) + '</strong></td>';
                html += '<td><strong>' + escapeHtml(cat.name) + '</strong></td>';
                html += '<td><code>' + escapeHtml(cat.taxonomy || taxonomy) + '</code></td>';
                html += '<td><span style="padding: 4px 8px; background: #fff3cd; color: #856404; border-radius: 3px; font-size: 11px; font-weight: 600;">';
                html += '<i class="fa-solid fa-hourglass-half"></i> ' + (autoCreateCategories.strings.waiting || 'Waiting');
                html += '</span></td>';
                html += '</tr>';
            });
            html += '</tbody></table>';
            html += '</div>';
            html += '</div>';
        } else {
            html += '<div class="cron-status-section">';
            html += '<p style="padding: 20px; text-align: center; color: #646970; background: #f9f9f9; border-radius: 4px;">';
            html += '<i class="fa-solid fa-check-circle" style="color: #00a32a; font-size: 24px; display: block; margin-bottom: 10px;"></i>';
            html += (autoCreateCategories.strings.no_pending || 'No pending categories. All descriptions have been generated!');
            html += '</p>';
            html += '</div>';
        }
        
        // Completed list
        if (data.completed && data.completed.length > 0) {
            html += '<div class="cron-status-section" style="margin-top: 25px;">';
            html += '<h4><i class="fa-solid fa-check-circle"></i> ' + (autoCreateCategories.strings.recently_completed || 'Recently Completed') + ' <span class="badge">' + data.completed.length + '</span></h4>';
            html += '<div style="max-height: 300px; overflow-y: auto;">';
            html += '<table class="widefat" style="margin-top: 10px;">';
            html += '<thead><tr>';
            html += '<th>' + (autoCreateCategories.strings.category_name || 'Category Name') + '</th>';
            html += '<th>' + (autoCreateCategories.strings.taxonomy || 'Taxonomy') + '</th>';
            html += '<th>' + (autoCreateCategories.strings.status || 'Status') + '</th>';
            html += '</tr></thead>';
            html += '<tbody>';
            // Show only last 20 completed
            const recentCompleted = data.completed.slice(0, 20);
            recentCompleted.forEach(function(cat) {
                html += '<tr>';
                html += '<td><strong>' + escapeHtml(cat.name) + '</strong></td>';
                html += '<td><code>' + escapeHtml(cat.taxonomy || taxonomy) + '</code></td>';
                html += '<td><span style="padding: 4px 8px; background: #e8f5e9; color: #2e7d32; border-radius: 3px; font-size: 11px; font-weight: 600;">';
                html += '<i class="fa-solid fa-check"></i> ' + (autoCreateCategories.strings.completed || 'Completed');
                html += '</span></td>';
                html += '</tr>';
            });
            html += '</tbody></table>';
            if (data.completed.length > 20) {
                html += '<p style="margin-top: 10px; text-align: center; color: #646970; font-size: 12px;">';
                html += (autoCreateCategories.strings.showing_last_20 || 'Showing last 20 completed. Total:') + ' ' + data.completed.length;
                html += '</p>';
            }
            html += '</div>';
            html += '</div>';
        }
        
        $('#cron-status-modal-content').html(html);
    }
    
    
})(jQuery);

