@props(['options' => [], 'model' => '', 'formId' => '', 'placeholder' => 'Rechercher ou sélectionner...', 'required' => false, 'optionsKey' => null, 'allowCreate' => false, 'createLabel' => 'Ajouter un nouveau client'])

@php
    $validationName = '__validate_' . preg_replace('/[^a-zA-Z0-9_]/', '_', (string) $model);
@endphp

<div x-data="{
    open: false,
    search: '',
    selectedValue: null,
    selectedLabel: null,
    staticOptions: @js($options),
    optionsKey: @js($optionsKey),
    allowCreate: @js($allowCreate),
    createLabel: '{{ addslashes($createLabel) }}',
    model: '{{ $model }}',
    formId: '{{ $formId }}',
    placeholder: '{{ addslashes($placeholder) }}',
    parentForm: null,
    parentScope: null,
    get options() {
        const scope = this.optionsKey ? (this.parentScope || this.parentForm) : null;
        if (this.optionsKey && scope && typeof scope[this.optionsKey] !== 'undefined') {
            const arr = scope[this.optionsKey];
            return Array.isArray(arr) ? arr.map(o => typeof o === 'object' && o !== null && ('value' in o || 'label' in o) ? o : { value: o.nom || o, label: o.nom || o }) : this.staticOptions;
        }
        return this.staticOptions;
    },
    getForm() {
        const findForm = (el) => {
            if (!el) return null;
            try {
                const data = typeof Alpine !== 'undefined' && Alpine.$data ? Alpine.$data(el) : (el.__x?.$data ?? el._x_dataStack?.[0]);
                if (!data) return null;
                return data.form ?? data;
            } catch (e) {}
            return null;
        };
        if (this.formId) {
            const el = document.getElementById(this.formId);
            return findForm(el);
        }
        let el = this.$el.parentElement;
        while (el) {
            const form = findForm(el);
            if (form) return form;
            el = el.parentElement;
        }
        return null;
    },
    getParentScope() {
        if (!this.formId) return null;
        try {
            const el = document.getElementById(this.formId);
            if (!el) return null;
            const data = typeof Alpine !== 'undefined' && Alpine.$data ? Alpine.$data(el) : (el.__x?.$data ?? el._x_dataStack?.[0]);
            return data || null;
        } catch (e) {}
        return null;
    },
    init() {
        this.$nextTick(() => {
            this.parentForm = this.getForm();
            if (this.optionsKey) this.parentScope = this.getParentScope();
            if (this.parentForm) {
                const val = this.parentForm[this.model];
                const opt = this.options.find(o => o.value === val || String(o.value) === String(val));
                this.selectedValue = val;
                this.selectedLabel = opt?.label ?? null;
            }
        });
    },
    get filteredOptions() {
        if (!this.search.trim()) return this.options;
        const q = this.search.toLowerCase();
        return this.options.filter(o => (o.label || o.value).toLowerCase().includes(q));
    },
    get displayLabel() {
        if (this.selectedLabel) return this.selectedLabel;
        const form = this.getForm();
        const val = form?.[this.model];
        return this.options.find(o => o.value === val || String(o.value) === String(val))?.label || null;
    },
    select(opt) {
        const form = this.getForm();
        if (form && this.model) {
            form[this.model] = opt.value;
        }
        this.selectedValue = opt.value;
        this.selectedLabel = opt.label;
        this.search = '';
        this.open = false;
    }
}" class="relative" @click.away="open = false" @form-reset.window="if ($event.detail?.formId === formId) { selectedValue = null; selectedLabel = null; }">
    <input
        x-ref="validation"
        x-effect="$refs.validation.value = (getForm()?.[model] ?? '')"
        type="text"
        name="{{ $validationName }}"
        class="absolute left-0 top-0 w-px h-px opacity-0 pointer-events-none"
        aria-hidden="true"
        tabindex="-1"
        autocomplete="off"
        @if($required) required @endif
        @invalid="$event.target.setCustomValidity('Veuillez sélectionner une option.')"
        @input="$event.target.setCustomValidity('')"
    >
    <div @click="open = !open" class="form-input cursor-pointer flex items-center justify-between min-h-[42px]">
        <span class="truncate" :class="displayLabel ? 'text-slate-800' : 'text-slate-400'" x-text="displayLabel || placeholder"></span>
        <svg class="w-4 h-4 text-slate-400 shrink-0 transition-transform" :class="open && 'rotate-180'" 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>
    </div>
    <div x-show="open" x-transition:enter="transition ease-out duration-100" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100" class="absolute z-10 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg overflow-hidden">
        <div class="p-2 border-b border-slate-100">
            <input type="text"
                   x-model="search"
                   @click.stop
                   placeholder="Rechercher..."
                   class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:outline-none">
        </div>
        <div class="max-h-48 overflow-y-auto py-1">
            <template x-for="opt in filteredOptions" :key="opt.value">
                <button type="button"
                        @click="select(opt)"
                        class="w-full px-4 py-2.5 text-left text-sm hover:bg-blue-50 transition-colors flex items-center justify-between"
                        :class="(selectedValue === opt.value || selectedValue === String(opt.value)) ? 'bg-blue-50 text-blue-700 font-medium' : 'text-slate-700'">
                    <span x-text="opt.label"></span>
                    <svg x-show="selectedValue === opt.value || selectedValue === String(opt.value)" class="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
                </button>
            </template>
            <template x-if="allowCreate">
                <button type="button"
                        @click="open = false; $dispatch('create-requested')"
                        class="w-full px-4 py-2.5 text-left text-sm hover:bg-blue-50 transition-colors flex items-center gap-2 text-blue-600 font-medium border-t border-slate-100 mt-1 pt-2">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                    <span x-text="createLabel"></span>
                </button>
            </template>
            <p x-show="filteredOptions.length === 0" class="px-4 py-2 text-sm text-slate-500">Aucun résultat</p>
        </div>
    </div>
</div>
