@props([
    'sections' => [], // Secciones existentes (para edición)
    'namePrefix' => 'sections', // Prefijo del input
    'allRules' => [],
])

{{-- Modal oculto por defecto --}}
<div id="rules-modal" class="hidden fixed inset-0 bg-black/40 flex items-center justify-center z-50">
    <div class="bg-white rounded-xl flex flex-col shadow-lg p-6 min-h-[400px] w-[400px]">
        <div class="flex-1">
            <h3 class="text-size-subtitle text-primary100 mb-4">Asignar Controles - Reglas</h3>
            <div id="rules-container" class="space-y-2 max-h-60 overflow-y-auto border border-optional p-2 rounded">
                @foreach($allRules as $rule)
                    <x-controls.checkbox 
                        :label="$rule->label" 
                        class="rule-checkbox" 
                        classCheckbox="rule-checkbox" 
                        :value="$rule->id"
                    />
                @endforeach
            </div>
        </div>
        <div class="flex justify-end gap-2 mt-4">
            <x-controls.button type="button" variant="cancel" onclick="closeRulesModal()">Cancelar</x-controls.button>
            <x-controls.button type="button" variant="add" onclick="saveRules()">Agregar</x-controls.button>
        </div>
    </div>
</div>

<div class="flex flex-col">
    <ul id="sections-container" class="space-y-2">
        @if(count($sections) > 0)
            @foreach($sections as $index => $section)
                <li class="section-item item-list-dinamic" data-index="{{ $index }}">
                    <span class="icon-drag drag-handle">☰</span>
                    {{-- ID oculto --}}
                    @if(!empty($section['id']))
                        <input type="hidden" name="{{ $namePrefix }}[{{ $index }}][id]" value="{{ $section['id'] }}">
                    @endif
                    <input type="text" name="{{ $namePrefix }}[{{ $index }}][title]"  
                           placeholder="Título de la sección"
                           class="flex-1 input-primary-input input-general" 
                           value="{{ $section['title'] }}" required>
                    <input type="number" name="{{ $namePrefix }}[{{ $index }}][order]" 
                           value="{{ $section['order'] ?? $index + 1 }}"
                           class="!w-20 input-primary-input input-general text-center" required>
                    {{-- reglas ya asignadas --}}
                    @if(!empty($section['rules']))
                        @foreach($section['rules'] as $ruleId)
                            <input type="hidden" name="{{ $namePrefix }}[{{ $index }}][rules][]" value="{{ $ruleId }}">
                        @endforeach
                    @endif
                    {{-- Botón para abrir modal --}}
                    <x-controls.button type="button" variant="optional" onclick="openRulesModal({{ $index }})">Asignar reglas</x-controls.button>
                    <x-controls.button type="button" variant="remove" onclick="removeSection(this)">Eliminar</x-controls.button>
                </li>
            @endforeach
        @else
            {{-- Sección inicial --}}
            <li class="section-item item-list-dinamic" data-index="0">
                <span class="icon-drag drag-handle">☰</span>
                <input type="text" name="{{ $namePrefix }}[0][title]" placeholder="Título de la sección"
                    class="flex-1 input-primary-input input-general" required>
                <input type="number" name="{{ $namePrefix }}[0][order]" value="1"
                    class="!w-20 input-primary-input input-general text-center" required>
                {{-- Botón para abrir modal de reglas --}}
                <x-controls.button type="button" variant="optional" onclick="openRulesModal(0)">Asignar reglas</x-controls.button>
                <x-controls.button type="button" variant="remove" onclick="removeSection(this)">Eliminar</x-controls.button>
            </li>
        @endif
    </ul>
    <div class="mt-6">
        <x-controls.button type="button" variant="optional" onclick="addSection()">Agregar sección</x-controls.button>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
    let sectionIndex = {{ count($sections) > 0 ? count($sections) : 1 }};
    let currentSectionIndex = null;

    function addSection() {
        const container = document.getElementById('sections-container');
        const li = document.createElement('li');
        li.classList.add('section-item', 'item-list-dinamic');
        li.setAttribute("data-index", sectionIndex);

        li.innerHTML = `
            <span class="icon-drag drag-handle">☰</span>
            <input type="text" name="{{ $namePrefix }}[${sectionIndex}][title]" 
                   placeholder="Título de la sección" 
                   class="flex-1 input-primary-input input-general" required>
            <input type="number" name="{{ $namePrefix }}[${sectionIndex}][order]" 
                   value="${sectionIndex + 1}" 
                   class="!w-20 input-primary-input input-general text-center" required>
            <x-controls.button type="button" variant="optional" onclick="openRulesModal(${sectionIndex})">Asignar reglas</x-controls.button>
            <button type="button" onclick="removeSection(this)" class="btn parrafo btn-remove">Eliminar</button>
        `;
        container.appendChild(li);
        sectionIndex++;
        updateOrderInputs();
    }

    function removeSection(button) {
        button.parentElement.remove();
        updateOrderInputs();
    }

    const sortable = Sortable.create(document.getElementById('sections-container'), {
        handle: '.drag-handle',
        animation: 150,
        onEnd: function () {
            updateOrderInputs();
        }
    });

    function updateOrderInputs() {
        document.querySelectorAll('#sections-container .section-item').forEach((li, index) => {
            li.querySelector('input[type="number"]').value = index + 1;
        });
    }

    // Modal de reglas
    function openRulesModal(sectionIdx) {
        currentSectionIndex = sectionIdx;

        // Limpiar checkboxes
        document.querySelectorAll('#rules-container .rule-checkbox').forEach(cb => cb.checked = false);

        // Marcar los que ya existen
        const hiddenInputs = document.querySelectorAll(
            `input[name='sections[${sectionIdx}][rules][]']`
        );
        hiddenInputs.forEach(input => {
            const cb = document.querySelector(`#rules-container .rule-checkbox[value="${input.value}"]`);
            if (cb) cb.checked = true;
        });

        document.getElementById('rules-modal').classList.remove('hidden');
    }

    function closeRulesModal() {
        document.getElementById('rules-modal').classList.add('hidden');
        currentSectionIndex = null;
    }

    function saveRules() {
        if (currentSectionIndex === null) return;

        const sectionItem = document.querySelector(`#sections-container .section-item[data-index="${currentSectionIndex}"]`);

        // Eliminar inputs previos
        sectionItem.querySelectorAll(`input[name^="sections[${currentSectionIndex}][rules]"]`).forEach(el => el.remove());

        // Agregar inputs hidden con las reglas seleccionadas
        document.querySelectorAll('#rules-container .rule-checkbox:checked').forEach(cb => {
            const hidden = document.createElement('input');
            hidden.type = "hidden";
            hidden.name = `sections[${currentSectionIndex}][rules][]`;
            hidden.value = cb.value;
            sectionItem.appendChild(hidden);
        });

        closeRulesModal();
    }
</script>
@endpush