@php $modalId = $modalId ?? 'modal-new-equipment'; @endphp
@php $inputClass = 'w-full px-3 py-2.5 text-sm border border-gray-200 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors'; @endphp
<form class="space-y-6" onsubmit="return false;">
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-5">
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Nom de l'équipement <span class="text-red-500">*</span></label>
            <input type="text" class="{{ $inputClass }}" placeholder="Nom de l'équipement">
        </div>
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Numéro de série</label>
            <input type="text" class="{{ $inputClass }}" placeholder="Optionnel">
        </div>
    </div>
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-5">
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Département</label>
            <div class="relative searchable-select-department" data-departments='@json(collect($departments ?? [])->map(fn($d) => ["id" => $d->id, "name" => $d->name])->values())'>
                <input type="hidden" name="department_id" value="">
                <button type="button" class="{{ $inputClass }} text-left flex items-center justify-between searchable-select-trigger">
                    <span class="searchable-select-label text-gray-500">Choisir un département</span>
                    <svg class="w-4 h-4 text-gray-400 shrink-0 ml-2 searchable-select-chevron transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                    </svg>
                </button>
                <div class="hidden absolute z-50 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg overflow-hidden searchable-select-dropdown">
                    <div class="p-2 border-b border-gray-100">
                        <input type="text" placeholder="Rechercher un département..." class="searchable-select-search w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                    </div>
                    <div class="max-h-48 overflow-y-auto py-1 searchable-select-options"></div>
                </div>
            </div>
        </div>
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Statut</label>
            <select class="{{ $inputClass }}">
                <option value="neuf">Neuf</option>
                <option value="bon">Bon</option>
                <option value="defectueux">Défectueux</option>
                <option value="en_maintenance">En maintenance</option>
                <option value="hors_service">Hors service</option>
            </select>
        </div>
    </div>
    <div>
        <label class="block text-sm font-medium text-gray-700 mb-2">Date d'acquisition</label>
        <input type="date" class="{{ $inputClass }}">
    </div>
    @include('components.modals.modal-actions', ['modalId' => $modalId])
</form>

<script>
    (function() {
        function initSearchableSelects() {
            document.querySelectorAll('.searchable-select-department').forEach(function(container) {
                if (container.dataset.initialized) return;
                container.dataset.initialized = '1';

                var departments = JSON.parse(container.dataset.departments || '[]');
                var hiddenInput = container.querySelector('input[type="hidden"]');
                var trigger = container.querySelector('.searchable-select-trigger');
                var label = container.querySelector('.searchable-select-label');
                var chevron = container.querySelector('.searchable-select-chevron');
                var dropdown = container.querySelector('.searchable-select-dropdown');
                var searchInput = container.querySelector('.searchable-select-search');
                var optionsContainer = container.querySelector('.searchable-select-options');

                var selected = null;

                function renderOptions(filter) {
                    var filtered = departments.filter(function(d) {
                        return !filter || d.name.toLowerCase().indexOf(filter.toLowerCase()) >= 0;
                    });
                    optionsContainer.innerHTML = filtered.length ? filtered.map(function(d) {
                        var active = selected && String(selected.id) === String(d.id) ? ' bg-blue-50 text-blue-700' : '';
                        var name = (d.name || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
                        return '<button type="button" class="w-full px-4 py-2.5 text-left text-sm hover:bg-blue-50 transition-colors' + active + '" data-id="' + d.id + '">' + name + '</button>';
                    }).join('') : '<p class="px-4 py-3 text-sm text-gray-500">Aucun résultat</p>';
                }

                function select(opt) {
                    selected = opt;
                    hiddenInput.value = opt.id;
                    label.textContent = opt.name;
                    label.classList.remove('text-gray-500');
                    dropdown.classList.add('hidden');
                    searchInput.value = '';
                    renderOptions('');
                }

                trigger.addEventListener('click', function(e) {
                    e.preventDefault();
                    var isOpen = !dropdown.classList.contains('hidden');
                    dropdown.classList.toggle('hidden');
                    chevron.classList.toggle('rotate-180', !isOpen);
                    if (!dropdown.classList.contains('hidden')) {
                        renderOptions('');
                        searchInput.value = '';
                        setTimeout(function() {
                            searchInput.focus();
                        }, 10);
                    }
                });

                searchInput.addEventListener('input', function() {
                    renderOptions(this.value);
                });
                searchInput.addEventListener('keydown', function(e) {
                    if (e.key === 'Escape') {
                        dropdown.classList.add('hidden');
                        chevron.classList.remove('rotate-180');
                    }
                });

                optionsContainer.addEventListener('click', function(e) {
                    var btn = e.target.closest('button[data-id]');
                    if (btn) select({
                        id: btn.dataset.id
                        , name: btn.textContent
                    });
                });

                document.addEventListener('click', function(e) {
                    if (!container.contains(e.target)) {
                        dropdown.classList.add('hidden');
                        chevron.classList.remove('rotate-180');
                    }
                });

                renderOptions('');
            });
        }
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initSearchableSelects);
        } else {
            initSearchableSelects();
        }
    })();

</script>
