@props([
    'disabled' => false,
    'multiple' => false,
    'searchable' => false,
    // When multiple=true, you can pass an array of selected values via value
    // When multiple=false, pass a single selected value
    'value' => null,
    // Placeholder text for searchable input
    'placeholder' => __('daylight::general.search'),
    // Enable console debugging
    'debug' => false,
])

@php
    $selectClasses = 'block w-full rounded-md h-10 sm:max-w-lg sm:text-sm border-gray-300 ' . ($disabled ? 'bg-gray-100' : '');
@endphp

@if(!$searchable && !$multiple)
    <select
        {{ $disabled ? 'disabled' : '' }}
        {!! $attributes->merge(['class' => $selectClasses]) !!}
        @if(!is_null($value))
            x-data
            x-init="(() => { const el = $el; const v = @js($value); if (v !== null && v !== undefined) el.value = v; })()"
        @endif
    >
       {{ $slot }}
    </select>
@else
    <div class="w-full sm:max-w-lg" x-data="selectEnhance({
            multiple: {{ $multiple ? 'true' : 'false' }},
            disabled: {{ $disabled ? 'true' : 'false' }},
            searchable: {{ $searchable ? 'true' : 'false' }},
            initialValue: @js($value),
            debug: {{ $debug ? 'true' : 'false' }},
        })">
        <select
            {{ $disabled ? 'disabled' : '' }}
            {{ $multiple ? 'multiple' : '' }}
            x-ref="native"
            {!! $attributes->merge(['class' => $selectClasses . ' sr-only absolute left-0 top-0 w-px h-px -m-px p-0 overflow-hidden border-0']) !!}
        >
            {{ $slot }}
        </select>

        <div class="relative" wire:ignore>
            <template x-if="multiple">
                <div class="relative w-full rounded-md border border-gray-300 bg-white min-h-10 px-1 pr-8 sm:text-sm text-gray-900 flex flex-wrap items-center gap-1 focus-within:ring-1 focus-within:ring-indigo-500 focus-within:border-indigo-500"
                     :class="disabled ? 'bg-gray-100 cursor-not-allowed opacity-75' : ''" @click="open = true">
                    <div class="flex flex-wrap py-1 px-0.5 gap-1" x-show="selectedLabels.length">
                        <template x-for="(label, idx) in selectedLabels" :key="idx">
                            <span class="inline-flex items-center gap-1 rounded bg-sky-100 text-sky-700 px-2 py-0.5 text-xs">
                                <span x-text="label"></span>
                                <button type="button" @click.stop="removeAt(idx)" class="hover:text-sky-900">×</button>
                            </span>
                        </template>
                    </div>
                    <input x-show="searchable" type="text" class="flex-1 bg-transparent border-0 focus:ring-0 focus:outline-none focus:border-transparent active:outline-none active:ring-0 sm:text-sm h-10 px-2" :placeholder="placeholder" x-model="query" @keydown.stop @click.stop @focus="open = true" @input="open = true">
                    <button type="button" class="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600" @click.stop="open = !open" aria-label="Toggle options">
                        <svg class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.188l3.71-3.957a.75.75 0 111.08 1.04l-4.24 4.52a.75.75 0 01-1.08 0L5.21 8.27a.75.75 0 01.02-1.06z" clip-rule="evenodd"/></svg>
                    </button>
                    <div class="absolute left-0 right-0 top-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg z-20 max-h-60 overflow-auto" x-show="open" x-transition.opacity x-transition.scale.origin.top @mousedown.prevent>
                        <template x-for="opt in filteredOptions" :key="opt.value">
                            <div class="px-3 py-2 sm:text-sm cursor-pointer hover:bg-gray-50 flex items-center gap-2"
                                 @click.stop="toggle(opt.value, opt.label)">
                                <div class="group grid size-4 grid-cols-1">
                                    <input type="checkbox"
                                           :checked="isSelected(opt.value)"
                                           class="col-start-1 row-start-1 appearance-none rounded border border-gray-300 bg-white checked:border-sky-600 checked:bg-sky-600 indeterminate:border-sky-600 indeterminate:bg-sky-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:border-gray-300 disabled:bg-gray-100 disabled:checked:bg-gray-100 forced-colors:appearance-auto" />
                                    <svg viewBox="0 0 14 14" fill="none" class="pointer-events-none col-start-1 row-start-1 size-3.5 self-center justify-self-center stroke-white">
                                        <path d="M3 8L6 11L11 3.5" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="opacity-0 group-has-[:checked]:opacity-100" />
                                        <path d="M3 7H11" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="opacity-0 group-has-[:indeterminate]:opacity-100" />
                                    </svg>
                                </div>
                                <span x-text="opt.label" class="truncate"></span>
                            </div>
                        </template>
                        <div class="px-3 py-2 sm:text-sm text-gray-500" x-show="filteredOptions.length === 0">{{ __('daylight::general.no_results') }}</div>
                    </div>
                </div>
            </template>

            <template x-if="!multiple">
                <div class="relative w-full rounded-md border border-gray-300 bg-white h-10 px-3 pr-8 sm:text-sm text-gray-900 flex items-center focus-within:ring-1 focus-within:ring-indigo-500 focus-within:border-indigo-500"
                     :class="disabled ? 'bg-gray-100 cursor-not-allowed opacity-75' : ''" @click="open = true">
                    <input x-show="searchable" type="text" class="flex-1 bg-transparent border-0 focus:ring-0 focus:outline-none sm:text-sm h-7 px-0" :placeholder="placeholder" x-model="query" @focus="onFocusSingleSearch()" @blur="onBlurSingleSearch()" @keydown.stop @click.stop @input="open = true">
                    <div x-show="!searchable" class="flex-1 truncate text-gray-900" x-text="selectedLabels[0] || ''"></div>
                    <button type="button" class="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600" @click.stop="open = !open" aria-label="Toggle options">
                        <svg class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.188l3.71-3.957a.75.75 0 111.08 1.04l-4.24 4.52a.75.75 0 01-1.08 0L5.21 8.27a.75.75 0 01.02-1.06z" clip-rule="evenodd"/></svg>
                    </button>
                    <div class="absolute left-0 right-0 top-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg z-20 max-h-60 overflow-auto" x-show="open" x-transition.opacity x-transition.scale.origin.top @mousedown.prevent>
                        <template x-for="opt in filteredOptions" :key="opt.value">
                            <div class="px-3 py-2 sm:text-sm cursor-pointer hover:bg-gray-50"
                                 @click.stop="selectSingle(opt.value, opt.label)" x-text="opt.label"></div>
                        </template>
                        <div class="px-3 py-2 sm:text-sm text-gray-500" x-show="filteredOptions.length === 0">{{ __('daylight::general.no_results') }}</div>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <script>
        document.addEventListener('alpine:init', () => {
            window.selectEnhance = function (config) {
                return {
                    open: false,
                    query: '',
                    multiple: !!config.multiple,
                    searchable: !!config.searchable,
                    disabled: !!config.disabled,
                    placeholder: @js($placeholder),
                    selectedValues: [],
                    selectedLabels: [],
                    optionsVersion: 0,
                    get options() {
                        void this.optionsVersion;
                        const select = this.$refs.native;
                        const list = [];
                        if (!select) return list;
                        for (const o of select.options) {
                            list.push({ value: o.value, label: o.textContent.trim() });
                        }
                        return list;
                    },
                    get filteredOptions() {
                        if (!this.searchable || !this.query) return this.options;
                        const q = this.query.toLowerCase();
                        return this.options.filter(o => o.label.toLowerCase().includes(q));
                    },
                    init() {
                        this.$nextTick(() => {
                            const select = this.$refs.native;
                            if (!select) return;

                            // Initialize from provided initialValue or DOM selected options
                            let initial = config.initialValue;
                            if (this.multiple) {
                                if (Array.isArray(initial) && initial.length) {
                                    this.selectedValues = initial.map(v => String(v));
                                } else {
                                    this.selectedValues = Array.from(select.selectedOptions).map(o => String(o.value));
                                }
                                this.syncLabels();
                                this.syncNativeMultiple();
                            } else {
                                let v = null;
                                if (typeof initial !== 'undefined' && initial !== null) {
                                    v = String(initial);
                                } else if (select.value) {
                                    v = String(select.value);
                                }
                                if (v !== null) {
                                    this.selectSingle(v, this.findLabel(v), false);
                                } else {
                                    this.selectedLabels = [];
                                }
                            }

                            // Observe option changes (Livewire re-render)
                            const observer = new MutationObserver(() => {
                                this.optionsVersion++;
                                if (this.multiple) {
                                    this.syncLabels();
                                } else if (this.selectedValues.length) {
                                    const v = this.selectedValues[0];
                                    this.selectedLabels = [this.findLabel(v)];
                                }
                            });
                            observer.observe(select, { childList: true, subtree: true, attributes: true });

                            // Close on outside click / Escape
                            document.addEventListener('click', (e) => {
                                if (!this.$root.contains(e.target)) {
                                    this.open = false;
                                }
                            });
                            document.addEventListener('keydown', (e) => {
                                if (e.key === 'Escape') this.open = false;
                            });
                        });
                    },
                    onFocusSingleSearch() {
                        this.open = true;
                        // Clear query so all options show, but keep selection state
                        this.query = '';
                    },
                    onBlurSingleSearch() {
                        // Restore the visible text to selected label after leaving
                        if (this.selectedLabels.length) {
                            this.query = this.selectedLabels[0];
                        }
                    },
                    findLabel(value) {
                        const found = this.options.find(o => String(o.value) === String(value));
                        return found ? found.label : '';
                    },
                    isSelected(value) {
                        return this.selectedValues.map(v => String(v)).includes(String(value));
                    },
                    toggle(value, label) {
                        if (!this.multiple) return;
                        const v = String(value);
                        if (this.isSelected(v)) {
                            this.selectedValues = this.selectedValues.filter(x => String(x) !== v);
                        } else {
                            this.selectedValues.push(v);
                        }
                        this.syncLabels();
                        this.syncNativeMultiple();
                    },
                    removeAt(index) {
                        if (!this.multiple) return;
                        this.selectedValues.splice(index, 1);
                        this.syncLabels();
                        this.syncNativeMultiple();
                    },
                    selectSingle(value, label, close = true) {
                        if (this.multiple) return;
                        const select = this.$refs.native;
                        if (!select) return;
                        select.value = value;
                        this.selectedValues = [String(value)];
                        this.selectedLabels = [label ?? this.findLabel(value)];
                        if (this.searchable) {
                            this.query = this.selectedLabels[0] || '';
                        }
                        if (close) this.open = false;
                        select.dispatchEvent(new Event('input', { bubbles: true }));
                        select.dispatchEvent(new Event('change', { bubbles: true }));
                        // Blur input to avoid immediate reopen
                        this.$nextTick(() => {
                            const inputEl = this.$root.querySelector('input');
                            if (inputEl) inputEl.blur();
                        });
                    },
                    syncLabels() {
                        this.selectedLabels = this.selectedValues.map(v => this.findLabel(v));
                    },
                    syncNativeMultiple() {
                        const select = this.$refs.native;
                        if (!select) return;
                        for (const option of select.options) {
                            option.selected = this.selectedValues.includes(String(option.value));
                        }
                        select.dispatchEvent(new Event('input', { bubbles: true }));
                        select.dispatchEvent(new Event('change', { bubbles: true }));
                    },
                }
            }
        });
    </script>
@endif
