/**
 * Flavor Menu – Admin Scripts
 * Handles price variant repeater and drag-to-sort
 */
(function ($) {
    'use strict';

    $(document).ready(function () {
        var $list = $('#flavor-prices-list');
        var $addBtn = $('#flavor-add-price');

        if (!$list.length) return;

        // Make price rows sortable
        $list.sortable({
            handle: '.flavor-drag-handle',
            placeholder: 'ui-sortable-placeholder',
            tolerance: 'pointer',
            update: function () {
                reindexRows();
            }
        });

        // Add new price row
        $addBtn.on('click', function () {
            var index = $list.children('.flavor-price-row').length;
            var $row = $(
                '<div class="flavor-price-row" data-index="' + index + '">' +
                '  <span class="flavor-drag-handle dashicons dashicons-menu"></span>' +
                '  <input type="text" name="flavor_prices[' + index + '][label]" value="" placeholder="Bezeichnung (z.B. Klein)" class="flavor-price-label" />' +
                '  <input type="text" name="flavor_prices[' + index + '][price]" value="" placeholder="Preis (z.B. 12,90 €)" class="flavor-price-value" />' +
                '  <button type="button" class="button flavor-remove-price" title="Entfernen">' +
                '    <span class="dashicons dashicons-trash"></span>' +
                '  </button>' +
                '</div>'
            );

            $list.append($row);
            $row.find('.flavor-price-label').focus();
        });

        // Remove price row
        $list.on('click', '.flavor-remove-price', function () {
            var $rows = $list.children('.flavor-price-row');
            if ($rows.length <= 1) {
                // Don't remove last row, just clear it
                $(this).closest('.flavor-price-row').find('input').val('');
                return;
            }
            $(this).closest('.flavor-price-row').slideUp(200, function () {
                $(this).remove();
                reindexRows();
            });
        });

        // Re-index names after sorting or removing
        function reindexRows() {
            $list.children('.flavor-price-row').each(function (i) {
                $(this).attr('data-index', i);
                $(this).find('.flavor-price-label').attr('name', 'flavor_prices[' + i + '][label]');
                $(this).find('.flavor-price-value').attr('name', 'flavor_prices[' + i + '][price]');
            });
        }
    });
})(jQuery);
