/**
 * Taxonomy Filter Column JavaScript
 *
 * Handles the taxonomy term selection in the checklist table
 */
jQuery(document).ready(function($) {
    /**
     * Initialize Select2 for taxonomy dropdowns
     */
    const initializeSelect2 = function() {
        if ($('.ppc-taxonomies-select').length > 0 && typeof $.fn.select2 !== 'undefined') {
            $('.ppc-taxonomies-select').select2({
                width: 'resolve',
                placeholder: 'Select terms to exclude',
                allowClear: true
            });
        }
    };

    /**
     * Save taxonomy selections via AJAX
     */
    const saveTaxonomySelections = function() {
        $(document).on('change', '.ppc-taxonomies-select', function() {
            const $select = $(this);
            const requirementId = $select.data('requirement');
            const terms = $select.val() || [];
            const postType = $select.data('post_type') || $('input[name="post_type"]').val() || 'post';

            $.post(ajaxurl, {
                action: 'ppc_save_checklist_taxonomies',
                nonce: window.ppcTaxonomyFilterData?.nonce || '',
                requirement_id: requirementId,
                terms: terms,
                post_type: postType
            }, function(response) {
                if (!response.success) {
                    alert('Failed to save taxonomy exclusions.');
                }
            });
        });
    };

    // Initialize components
    initializeSelect2();
    saveTaxonomySelections();
});
