@props([
    'name',
    'label' => '',
    'options' => [],
])

<div class="mb-4">
    @if($label)
        <label class="block font-main text-size-small-heading leading-normal mb-2">{{ $label }}</label>
    @endif
    <div x-data="optionsList({{ json_encode(old($name, $options)) }})" class="space-y-2">
        <template x-for="(option, index) in options" :key="index">
            <div class="flex gap-2">
                <input type="text" 
                       :name="`{{ $name }}[${index}][key]`" 
                       x-model="option.key" 
                       class="flex-1 input-primary-input input-general" 
                       placeholder="Clave">
                <input type="text" 
                       :name="`{{ $name }}[${index}][value]`" 
                       x-model="option.value" 
                       class="flex-1 input-primary-input input-general" 
                       placeholder="Valor">
                <x-controls.button type="button" variant="remove" @click="removeOption(index)">Eliminar</x-controls.button>
            </div>
        </template>
        <x-controls.button type="button" variant="optional" @click="addOption()">Agregar opción</x-controls.button>
    </div>
</div>

<script>
    function optionsList(initial = []) {
        return {
            options: initial.length 
                ? initial.map(opt => ({ key: opt.key ?? '', value: opt.value ?? '' })) 
                : [{ key: '', value: '' }], // 👈 siempre empieza con uno
            addOption() {
                this.options.push({ key: '', value: '' });
            },
            removeOption(index) {
                this.options.splice(index, 1);
                if (this.options.length === 0) {
                    // 👇 evita que quede vacío, siempre deja al menos uno
                    this.options.push({ key: '', value: '' });
                }
            }
        }
    }
</script>