/**
 * Topping Items Sortable functionality
 *
 * @package Foodord
 */

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

    // Initialize sortable functionality
    function initToppingSortable() {
        $('.topping-items-sortable').each(function() {
            const $container = $(this);

            if ($container.hasClass('ui-sortable')) {
                return;
            }

            $container.sortable({
                items: '.topping-item-row',
                handle: '.drag-handle',
                cursor: 'move',
                placeholder: 'topping-item-placeholder',
                axis: 'y',
                tolerance: 'pointer',
                update: function() {
                    updateToppingIndices($container);
                }
            });
        });
    }

    // Update topping indices after reordering
    function updateToppingIndices(container) {
        const $containers = container ? container : $('.topping-items-sortable');

        $containers.each(function() {
            $(this).find('.topping-item-row').each(function(index) {
                const row = $(this);

                // Update data attribute
                row.attr('data-topping-index', index);

                // Update input IDs and labels
                row.find('input[name="topping_item_label[]"]').attr('id', `topping_item_label_${index}`);
                row.find('input[name="topping_item_price[]"]').attr('id', `topping_item_price_${index}`);
                row.find('label[for^="topping_item_label"]').attr('for', `topping_item_label_${index}`);
                row.find('label[for^="topping_item_price"]').attr('for', `topping_item_price_${index}`);

                const groupType = row.data('group-type');
                if (groupType) {
                    const defaultId = `topping_item_default_${groupType}_${index}`;
                    row.find('.topping-default-checkbox').attr({
                        id: defaultId,
                        value: index,
                    });
                    row.find('.topping-default-label').attr('for', defaultId);
                }
            });
        });
    }

    // Make updateToppingIndices globally accessible
    window.updateToppingIndices = updateToppingIndices;


    // Initialize on page load
    initToppingSortable();
    updateToppingIndices();
});
