(function($){
    // Populate hierarchical checklists via AJAX terms list endpoint
    function loadChecklist($ul, postId){
        var tax = $ul.data('tax');
        $.post(ajaxurl, { action: 'wp_ajax_wp_list_table', _ajax_nonce: inlineEditL10n.inlineEditNonce }, function(){ });
        // Fallback simple fetch of terms
        $.getJSON(ajaxurl, { action: 'query-attachments', tax: tax }, function(){ /* placeholder */ });
    }

    // When QE opens, try to prefill
    var $wp_inline = inlineEditPost ? $(inlineEditPost.what) : null;
    $(document).on('click', 'button.editinline', function(){
        var postId = $(this).closest('tr').attr('id').replace('post-', '');
        $('.cat-checklist').each(function(){
            loadChecklist($(this), postId);
        });
    });

    // Media: open inline template
    $(document).on('click', 'a.ironseo3-media-quick-tax', function(e){
        e.preventDefault();
        var $tr = $(this).closest('tr');
        var id = $tr.attr('id').replace('post-', '');
        // close others
        $('tr.ironseo3-media-inline').remove();
        // insert inline after row
        var $tmpl = $($('#tmpl-ironseo3-media-qe').html());
        $tr.after($tmpl);
        // TODO: load current terms for each taxonomy via REST
        $tmpl.find('button.cancel').on('click', function(){
            $tmpl.remove();
        });
        $tmpl.find('button.save').on('click', function(){
            var payload = { action:'ironseo3_media_quick_tax', nonce: ironseo3QE.nonce, post_id: id, tax_input:{} };
            $tmpl.find('[data-tax]').each(function(){
                var tax = $(this).data('tax');
                if ($(this).is('ul')) {
                    var vals = [];
                    $(this).find('input[type=checkbox]:checked').each(function(){ vals.push($(this).val()); });
                    payload.tax_input[tax] = vals;
                } else {
                    payload.tax_input[tax] = $(this).val();
                }
            });
            $.post(ajaxurl, payload, function(resp){
                if (resp && resp.success) { $tmpl.remove(); }
            });
        });
    });

    // Hide WordPress native "tags_input" text field so that only checkbox UIs are visible
    function ironseo3HideNativeTagField(){
        // Quick Edit row
        jQuery('.inline-edit-row .tags_input').closest('label').hide();
        // Bulk Edit panel
        jQuery('#bulk-edit .tags_input').closest('label').hide();
    }
    jQuery(document).on('click', 'button.editinline, #bulk_edit', ironseo3HideNativeTagField);
    jQuery(document).ready(ironseo3HideNativeTagField);
})(jQuery);