jQuery(document).ready(function ($) {
    $('#sort-replies').on('change', function (e) {
        e.preventDefault();
        var sort = $(this).val();
        var topic_id = $('section[role="main"]').attr('id') || forumax_localize_script.bbp_topic_id;

        var data = {
            action: 'sort_bbp_replies',
            sort: sort,
            topic_id: topic_id,
            nonce: forumax_localize_script.nonce
        };
        console.log(data);
        $('#topic-' + topic_id + '-replies .reply-result').addClass('loading');
        $.post(forumax_localize_script.ajaxurl, data, function (response) {
            if (response.success) {
                $('#topic-' + topic_id + '-replies .reply-result').html(response.data.html);
                // Re-initialize .bbp-admin-dropdown-menu.frmx-nice-select after AJAX update
                if ($.fn.frmxNiceSelect) {
                    $('.bbp-admin-dropdown-menu.frmx-admin-links-select').each(function () {
                        var $select = $(this);
                        // Robust cleanup before re-init
                        $select.nextAll('.nice-select, .frmx-nice-select').remove();
                        $select.frmxNiceSelect();
                        // Force remove 'nice-select' class from the injected div
                        $select.next('.frmx-nice-select').removeClass('nice-select');
                    });
                }
            }
            $('#topic-' + topic_id + '-replies .reply-result').removeClass('loading');
        });
    });
});