/**
 * @file assets/js/mbs-book-editor.js
 * Book editor section-order drag-and-drop and arrow-button fallback; loaded on the mbs_book edit screen.
 * @package MyBookShowroom
 * @since   1.0.0
 */

jQuery(document).ready(function($) {
    'use strict';

    // === Section Order logic ===
    const $body = $('#mbs-section-order-body');
    const $hidden = $('#mbs_section_order_input');
    const $sortableList = $('#mbs-section-sortable');

    function updateHidden() {
        const order = [];
        if ($sortableList.length && $sortableList.is(':visible')) {
            $sortableList.find('li').each(function() {
                order.push($(this).data('slug'));
            });
        } else {
            $body.find('tr').each(function() {
                order.push($(this).data('slug'));
            });
        }
        $hidden.val(order.join(','));
    }

    $body.on('click', '.mbs-up', function() {
        const $row = $(this).closest('tr');
        const $prev = $row.prev('tr');
        if ($prev.length) {
            $row.insertBefore($prev);
            updateHidden();
        }
    });

    $body.on('click', '.mbs-down', function() {
        const $row = $(this).closest('tr');
        const $next = $row.next('tr');
        if ($next.length) {
            $row.insertAfter($next);
            updateHidden();
        }
    });

    if (typeof $.fn.sortable !== 'undefined' &&
        $sortableList.find('.mbs-drag-handle').length) {
        $sortableList.sortable({
            handle: '.mbs-drag-handle',
            update: function() {
                updateHidden();
            }
        });
        $('#mbs-section-order-table').hide();
        // FE-007: disable hidden table checkboxes so only the visible sortable
        // list's checkboxes submit with the form. display:none does not prevent
        // input submission; disabled does.
        $('#mbs-section-order-body input[type="checkbox"]').prop('disabled', true);
        $sortableList.show();
    } else {
        $sortableList.hide();
        // FE-007: disable hidden list checkboxes so only the visible table's
        // checkboxes submit with the form.
        $sortableList.find('input[type="checkbox"]').prop('disabled', true);
        $('#mbs-section-order-table').show();
    }

});
