/**
 * Flavor Menu – Category Sort (Drag & Drop)
 * Parents are sortable among themselves; children move with their parent
 * because they are nested inside the parent <li>.
 * Children are sortable within their parent's <ul>.
 */
(function ($) {
    'use strict';

    $(document).ready(function () {
        var $feedback   = $('#flavor-cat-sort-feedback');
        var $parentList = $('#flavor-cat-sort-list');

        if (!$parentList.length) return;

        // Make parent items sortable (children move with them automatically)
        $parentList.sortable({
            items:       '> .flavor-cat-sort-item--parent',
            handle:      '> .flavor-cat-sort-row > .flavor-cat-sort-handle',
            placeholder: 'flavor-cat-sort-placeholder',
            tolerance:   'pointer',
            cursor:      'grabbing',
            update: function () {
                saveAllOrders();
            }
        });

        // Make each child list independently sortable within its parent
        $parentList.find('.flavor-cat-sort-children').each(function () {
            $(this).sortable({
                items:       '> .flavor-cat-sort-item--child',
                handle:      '> .flavor-cat-sort-handle',
                placeholder: 'flavor-cat-sort-placeholder flavor-cat-sort-placeholder--child',
                tolerance:   'pointer',
                cursor:      'grabbing',
                update: function () {
                    saveAllOrders();
                }
            });
        });

        function saveAllOrders() {
            var order = [];

            $parentList.children('.flavor-cat-sort-item--parent').each(function () {
                order.push($(this).data('term-id'));

                $(this).find('.flavor-cat-sort-children > .flavor-cat-sort-item--child').each(function () {
                    order.push($(this).data('term-id'));
                });
            });

            $parentList.css('opacity', '0.6');

            $.ajax({
                url:  flavorCatSort.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'flavor_save_cat_order',
                    nonce:  flavorCatSort.nonce,
                    order:  order
                },
                success: function (response) {
                    $parentList.css('opacity', '1');
                    if (response.success) {
                        $feedback.slideDown(200);
                        setTimeout(function () { $feedback.slideUp(200); }, 2000);
                    }
                },
                error: function () {
                    $parentList.css('opacity', '1');
                    alert('Error saving order.');
                }
            });
        }
    });
})(jQuery);
