@props([
    'name' => '',
    'label' => '',
    'placeholder' => 'Search...',
    'options' => [],
    'selected' => null,
    'required' => false,
    'valueKey' => 'id',
    'labelKey' => 'name',
    'prefixKey' => null, // For emoji/icon prefix like flag_emoji
    'watchValue' => null, // For dynamic value updates (use with x-bind:watch-value)
])

<div class="searchable-select-wrapper"
    x-data="searchableSelect({
        name: '{{ $name }}',
        selected: {{ json_encode($selected) }},
        options: {{ json_encode($options) }},
        valueKey: '{{ $valueKey }}',
        labelKey: '{{ $labelKey }}',
        prefixKey: {{ $prefixKey ? "'$prefixKey'" : 'null' }},
        placeholder: '{{ $placeholder }}'
    })"
    @if($watchValue !== null)
        x-init="$watch('{{ $watchValue }}', (newValue) => {
            if (newValue !== undefined && newValue !== selectedValue) {
                selectedValue = newValue;
                updateSelectedDisplay();
            }
        })"
    @endif
>
    @if($label)
        <label class="block text-sm font-medium text-tertiary mb-1">{{ $label }}</label>
    @endif

    <!-- Hidden Input for Form Submission -->
    <input type="hidden" name="{{ $name }}" x-model="selectedValue">

    <!-- Custom Select Dropdown -->
    <div class="relative">
        <!-- Selected Display / Trigger -->
        <button
            type="button"
            @click="open = !open"
            @click.away="open = false"
            class="input text-sm w-full flex items-center justify-between cursor-pointer"
            style="padding-{{ is_rtl() ? 'left' : 'right' }}: 2.5rem;"
        >
            <span x-show="!selectedValue" class="text-tertiary" x-text="placeholder"></span>
            <span x-show="selectedValue" class="flex items-center gap-2">
                <span x-show="selectedPrefix" x-text="selectedPrefix"></span>
                <span x-text="selectedLabel"></span>
            </span>
            <svg class="w-4 h-4 text-tertiary absolute {{ is_rtl() ? 'left-3' : 'right-3' }} top-1/2 -translate-y-1/2 transition-transform" :class="{ 'rotate-180': open }" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
            </svg>
        </button>

        <!-- Dropdown Menu -->
        <div
            x-show="open"
            x-transition:enter="transition ease-out duration-100"
            x-transition:enter-start="opacity-0 scale-95"
            x-transition:enter-end="opacity-100 scale-100"
            x-transition:leave="transition ease-in duration-75"
            x-transition:leave-start="opacity-100 scale-100"
            x-transition:leave-end="opacity-0 scale-95"
            class="absolute z-50 mt-2 w-full rounded-lg shadow-lg border overflow-hidden"
            style="background: var(--color-bg-primary); border-color: var(--color-border); max-height: 300px;"
            x-cloak
        >
            <!-- Search Input -->
            <div class="p-2 border-b" style="border-color: var(--color-border);">
                <input
                    type="text"
                    x-model="search"
                    @input="filterOptions()"
                    class="input text-sm w-full"
                    :placeholder="placeholder"
                    @click.stop
                >
            </div>

            <!-- Options List -->
            <div class="overflow-y-auto" style="max-height: 250px;">
                <!-- Clear/All Option -->
                <div
                    @click="selectOption(null)"
                    class="px-3 py-2 cursor-pointer transition-colors hover:bg-primary-light"
                    :class="{ 'bg-primary-light font-medium': selectedValue === null }"
                >
                    <span class="text-sm text-tertiary">{{ admin_trans('all') }}</span>
                </div>

                <!-- Filtered Options -->
                <template x-for="option in filteredOptions" :key="option[valueKey]">
                    <div
                        @click="selectOption(option)"
                        class="px-3 py-2 cursor-pointer transition-colors hover:bg-primary-light"
                        :class="{ 'bg-primary-light font-medium': selectedValue == option[valueKey] }"
                    >
                        <span class="text-sm text-primary flex items-center gap-2">
                            <span x-show="prefixKey && option[prefixKey]" x-text="option[prefixKey]"></span>
                            <span x-text="option[labelKey]"></span>
                        </span>
                    </div>
                </template>

                <!-- No Results -->
                <div x-show="filteredOptions.length === 0" class="px-3 py-4 text-center">
                    <span class="text-sm text-tertiary">{{ admin_trans('no_results_found') }}</span>
                </div>
            </div>
        </div>
    </div>
</div>

@pushOnce('scripts')
<script>
function searchableSelect(config) {
    return {
        open: false,
        search: '',
        selectedValue: config.selected,
        selectedLabel: '',
        selectedPrefix: '',
        options: config.options,
        filteredOptions: [],
        valueKey: config.valueKey,
        labelKey: config.labelKey,
        prefixKey: config.prefixKey,
        placeholder: config.placeholder,

        init() {
            this.filteredOptions = [...this.options];
            this.updateSelectedDisplay();
        },

        filterOptions() {
            const searchLower = this.search.toLowerCase().trim();

            if (!searchLower) {
                this.filteredOptions = [...this.options];
                return;
            }

            this.filteredOptions = this.options.filter(option => {
                const label = option[this.labelKey]?.toString().toLowerCase() || '';
                return label.includes(searchLower);
            });
        },

        selectOption(option) {
            if (option === null) {
                this.selectedValue = null;
                this.selectedLabel = '';
                this.selectedPrefix = '';
            } else {
                this.selectedValue = option[this.valueKey];
                this.selectedLabel = option[this.labelKey];
                this.selectedPrefix = this.prefixKey ? option[this.prefixKey] : '';
            }

            this.open = false;
            this.search = '';
            this.filterOptions();
        },

        updateSelectedDisplay() {
            if (this.selectedValue) {
                const selected = this.options.find(opt => opt[this.valueKey] == this.selectedValue);
                if (selected) {
                    this.selectedLabel = selected[this.labelKey];
                    this.selectedPrefix = this.prefixKey ? selected[this.prefixKey] : '';
                }
            }
        }
    }
}
</script>
@endPushOnce
