jQuery(document).ready(function($) {
    let debounceTimer;
    const debounceDelay = 500; // 500ms delay
    
    // Function to collect form data
    function getFormData() {
        const formData = {};
        
        // Get post types
        formData.post_types = {};
        $('input[name^="wpsummarize_batch_options[post_types]"]:checked').each(function() {
            const name = $(this).attr('name');
            const match = name.match(/\[post_types\]\[([^\]]+)\]/);
            if (match) {
                formData.post_types[match[1]] = '1';
            }
        });
        
        // Get categories
        formData.categories = {};
        $('input[name^="wpsummarize_batch_options[categories]"]:checked').each(function() {
            const name = $(this).attr('name');
            const match = name.match(/\[categories\]\[([^\]]+)\]/);
            if (match) {
                formData.categories[match[1]] = '1';
            }
        });
        
        // Get tags
        formData.tags = {};
        $('input[name^="wpsummarize_batch_options[tags]"]:checked').each(function() {
            const name = $(this).attr('name');
            const match = name.match(/\[tags\]\[([^\]]+)\]/);
            if (match) {
                formData.tags[match[1]] = '1';
            }
        });
        
        // Get minimum words
        formData.minimum_words = $('input[name="wpsummarize_batch_options[minimum_words]"]').val() || '0';
        
        // Get update existing summaries
        formData.update_existing_summaries = $('input[name="wpsummarize_batch_options[update_existing_summaries]"]:checked').length ? '1' : '0';
        
        // Get update manually edited summaries
        formData.update_manually_edited_summaries = $('input[name="wpsummarize_batch_options[update_manually_edited_summaries]"]:checked').length ? '1' : '0';
        
        // Get excluded post IDs
        formData.excluded_post_ids = $('textarea[name="wpsummarize_batch_options[excluded_post_ids]"]').val() || '';
        
        return formData;
    }
    
    // Function to update the count
    function updateCount() {
        const formData = getFormData();
        
        // Show loader
        $('#wpsummarize-count-loader').show();
        $('#wpsummarize-posts-count').css('opacity', '0.5');
        
        $.ajax({
            url: wpSummarizeCount.ajax_url,
            type: 'POST',
            data: {
                action: 'wpsummarize_update_posts_count',
                nonce: wpSummarizeCount.nonce,
                form_data: formData
            },
            success: function(response) {
                if (response.success) {
                    $('#wpsummarize-posts-count').text(response.data.count).css('opacity', '1');
                }
            },
            error: function() {
                $('#wpsummarize-posts-count').css('opacity', '1');
            },
            complete: function() {
                $('#wpsummarize-count-loader').hide();
            }
        });
    }
    
    // Function to trigger debounced update
    function debouncedUpdate() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(function() {
            updateCount();
        }, debounceDelay);
    }
    
    // Listen to all relevant form changes
    $(document).on('change', 'input[name^="wpsummarize_batch_options[post_types]"]', debouncedUpdate);
    $(document).on('change', 'input[name^="wpsummarize_batch_options[categories]"]', debouncedUpdate);
    $(document).on('change', 'input[name^="wpsummarize_batch_options[tags]"]', debouncedUpdate);
    $(document).on('change', 'input[name="wpsummarize_batch_options[update_existing_summaries]"]', debouncedUpdate);
    $(document).on('change', 'input[name="wpsummarize_batch_options[update_manually_edited_summaries]"]', debouncedUpdate);
    $(document).on('keyup', 'input[name="wpsummarize_batch_options[minimum_words]"]', debouncedUpdate);
    $(document).on('keyup', 'textarea[name="wpsummarize_batch_options[excluded_post_ids]"]', debouncedUpdate);
});