<div x-data="{ 
    open: false,
    query: '',
    results: [],
    loading: false,
    selectedIndex: -1,
    async search() {
        if (this.query.length < 2) {
            this.results = [];
            return;
        }
        
        this.loading = true;
        
        try {
            const response = await fetch(`/api/search?q=${encodeURIComponent(this.query)}`);
            const data = await response.json();
            this.results = data.results || [];
        } catch (error) {
            console.error('Search error:', error);
            this.results = [];
        } finally {
            this.loading = false;
        }
    },
    selectResult(index) {
        if (this.results[index]) {
            window.location.href = this.results[index].url;
        }
    },
    handleKeydown(event) {
        if (event.key === 'ArrowDown') {
            event.preventDefault();
            this.selectedIndex = Math.min(this.selectedIndex + 1, this.results.length - 1);
        } else if (event.key === 'ArrowUp') {
            event.preventDefault();
            this.selectedIndex = Math.max(this.selectedIndex - 1, -1);
        } else if (event.key === 'Enter' && this.selectedIndex >= 0) {
            event.preventDefault();
            this.selectResult(this.selectedIndex);
        }
    }
}" 
@keydown.escape.window="open = false; query = ''; results = []"
@click.away="open = false"
class="relative">
    
    <!-- Search Input -->
    <div class="relative">
        <input type="text"
               x-model="query"
               @input.debounce.300ms="search()"
               @focus="open = true"
               @keydown="handleKeydown($event)"
               placeholder="Search docs, features, help..."
               class="w-full md:w-64 px-4 py-2 pl-10 pr-4 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
               aria-label="Search"
               aria-autocomplete="list"
               aria-controls="search-results">
        
        <!-- Search Icon -->
        <div class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
            <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="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
            </svg>
        </div>

        <!-- Loading Spinner -->
        <div x-show="loading" class="absolute right-3 top-1/2 transform -translate-y-1/2">
            <svg class="animate-spin h-4 w-4 text-blue-600" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
        </div>
    </div>

    <!-- Search Results Dropdown -->
    <div x-show="open && (results.length > 0 || (query.length >= 2 && !loading))"
         x-cloak
         x-transition:enter="transition ease-out duration-200"
         x-transition:enter-start="opacity-0 translate-y-1"
         x-transition:enter-end="opacity-100 translate-y-0"
         x-transition:leave="transition ease-in duration-150"
         x-transition:leave-start="opacity-100 translate-y-0"
         x-transition:leave-end="opacity-0 translate-y-1"
         id="search-results"
         class="absolute z-50 w-full md:w-96 mt-2 bg-white rounded-lg shadow-2xl border border-gray-200 max-h-96 overflow-y-auto"
         role="listbox">
        
        <!-- Results -->
        <template x-if="results.length > 0">
            <div class="py-2">
                <template x-for="(result, index) in results" :key="result.id">
                    <a :href="result.url"
                       @mouseenter="selectedIndex = index"
                       :class="selectedIndex === index ? 'bg-blue-50' : 'hover:bg-gray-50'"
                       class="block px-4 py-3 transition duration-150"
                       role="option"
                       :aria-selected="selectedIndex === index">
                        <div class="flex items-start">
                            <!-- Icon based on type -->
                            <div class="flex-shrink-0 mt-1">
                                <div class="w-8 h-8 rounded-lg flex items-center justify-center"
                                     :class="{
                                         'bg-blue-100 text-blue-600': result.type === 'page',
                                         'bg-green-100 text-green-600': result.type === 'feature',
                                         'bg-purple-100 text-purple-600': result.type === 'doc',
                                         'bg-yellow-100 text-yellow-600': result.type === 'help'
                                     }">
                                    <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="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                                    </svg>
                                </div>
                            </div>
                            
                            <!-- Content -->
                            <div class="ml-3 flex-1">
                                <div class="flex items-center justify-between">
                                    <p class="text-sm font-semibold text-gray-900" x-text="result.title"></p>
                                    <span class="text-xs text-gray-500 uppercase" x-text="result.type"></span>
                                </div>
                                <p class="text-xs text-gray-600 mt-1 line-clamp-2" x-text="result.description"></p>
                            </div>
                        </div>
                    </a>
                </template>
            </div>
        </template>

        <!-- No Results -->
        <template x-if="results.length === 0 && query.length >= 2 && !loading">
            <div class="px-4 py-8 text-center">
                <svg class="w-12 h-12 text-gray-400 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                <p class="text-sm text-gray-600 mb-2">No results found for "<span x-text="query" class="font-semibold"></span>"</p>
                <p class="text-xs text-gray-500">Try different keywords or check our <a href="#" class="text-blue-600 hover:text-blue-700 underline">help center</a></p>
            </div>
        </template>

        <!-- Quick Links Footer -->
        <div class="border-t border-gray-200 bg-gray-50 px-4 py-3">
            <div class="flex items-center justify-between text-xs">
                <div class="flex items-center gap-4 text-gray-500">
                    <span class="flex items-center">
                        <kbd class="px-2 py-1 bg-white border border-gray-300 rounded text-xs">↑↓</kbd>
                        <span class="ml-1">Navigate</span>
                    </span>
                    <span class="flex items-center">
                        <kbd class="px-2 py-1 bg-white border border-gray-300 rounded text-xs">↵</kbd>
                        <span class="ml-1">Select</span>
                    </span>
                    <span class="flex items-center">
                        <kbd class="px-2 py-1 bg-white border border-gray-300 rounded text-xs">Esc</kbd>
                        <span class="ml-1">Close</span>
                    </span>
                </div>
            </div>
        </div>
    </div>
</div>