/**
 * File Path: assets/js/adminjs/mbs-admin-sort-pref.js
 *
 * F-SORT-2 — Sort preference toggle for Authors, Series, and Collections tabs.
 *
 * Handles clicks on .mbs-sort-toggle buttons, sends an AJAX request to
 * save the user's sort preference (mbs_sort_pref_{tab} user_meta), then
 * reloads the page so the server-side render reflects the new order.
 *
 * Localized object: MBS_SortPref
 *   ajaxUrl (string) — admin-ajax.php URL
 *   nonce   (string) — mbs_sort_pref_nonce value
 *   tab     (string) — current tab slug: authors | series | collections
 *   current (string) — current active pref value
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */
( function () {
    'use strict';

    document.addEventListener( 'DOMContentLoaded', function () {
        var toolbar = document.querySelector( '.mbs-sort-toggle' );
        if ( ! toolbar ) {
            return;
        }

        var buttons = toolbar.querySelectorAll( 'button[data-sort-pref]' );
        if ( ! buttons.length ) {
            return;
        }

        buttons.forEach( function ( btn ) {
            btn.addEventListener( 'click', function () {
                var pref = btn.getAttribute( 'data-sort-pref' );
                if ( pref === MBS_SortPref.current ) {
                    return; // Already the active sort — nothing to do.
                }

                // Disable all buttons while the AJAX request is in flight.
                buttons.forEach( function ( b ) {
                    b.disabled = true;
                } );

                var body = new URLSearchParams();
                body.append( 'action', 'mbs_save_sort_pref' );
                body.append( 'nonce',  MBS_SortPref.nonce );
                body.append( 'tab',    MBS_SortPref.tab );
                body.append( 'pref',   pref );

                fetch( MBS_SortPref.ajaxUrl, {
                    method:      'POST',
                    credentials: 'same-origin',
                    body:        body,
                } )
                .then( function ( res ) {
                    return res.json();
                } )
                .then( function ( data ) {
                    if ( data && data.success ) {
                        window.location.reload();
                    } else {
                        // Re-enable on failure so user can retry.
                        buttons.forEach( function ( b ) {
                            b.disabled = false;
                        } );
                    }
                } )
                .catch( function () {
                    buttons.forEach( function ( b ) {
                        b.disabled = false;
                    } );
                } );
            } );
        } );
    } );
} )();
