{{-- 
    Health Institution Directory Listing
    Public page with globy.com-style search and filtering
    
    Uses: <x-site-layout>
    Requirements: 5.1, 5.3
--}}
<x-site-layout 
    title="Health Institution Directory"
    meta-description="Find healthcare institutions in South Sudan. Browse hospitals, clinics, and medical facilities near you."
>
    {{-- Hero Section with Search Overlay --}}
    <section class="relative bg-gradient-to-br from-green-600 via-green-700 to-emerald-800">
        {{-- Background Pattern --}}
        <div class="absolute inset-0 opacity-10">
            <div class="absolute inset-0" style="background-image: url('data:image/svg+xml,%3Csvg width=&quot;60&quot; height=&quot;60&quot; viewBox=&quot;0 0 60 60&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;%3E%3Cg fill=&quot;none&quot; fill-rule=&quot;evenodd&quot;%3E%3Cg fill=&quot;%23ffffff&quot; fill-opacity=&quot;0.4&quot;%3E%3Cpath d=&quot;M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z&quot;/%3E%3C/g%3E%3C/g%3E%3C/svg%3E');"></div>
        </div>
        
        <div class="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10 lg:py-14">
            {{-- Title --}}
            <div class="text-center mb-7">
                <h1 class="text-3xl md:text-4xl font-bold text-white mb-2 tracking-tight">
                    <i class="fas fa-hospital mr-3"></i>Health Institution Directory
                </h1>
                <p class="text-base text-green-100 max-w-3xl mx-auto">
                    Discover healthcare facilities across South Sudan. Find hospitals, clinics, and medical centers near you.
                </p>
            </div>
            
            {{-- Search Form --}}
            <div class="max-w-4xl mx-auto"
                 x-data="institutionSearch('{{ route('api.institutions.search') }}', '{{ route('institutions.index') }}')"
                 @click.outside="showDropdown = false">
                <form id="institutions-filter-form" action="{{ route('institutions.index') }}" method="GET" class="bg-white rounded-2xl shadow-2xl p-5">
                    {{-- Main Search with AJAX Dropdown --}}
                    <div class="flex flex-col lg:flex-row gap-4">
                        <div class="flex-1 relative">
                            <i class="fas fa-search absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 z-10"></i>
                            <input
                                type="text"
                                name="q"
                                id="institution-search-input"
                                x-model="query"
                                @input.debounce.300ms="search()"
                                @focus="if (query.length >= 2) showDropdown = true"
                                @keydown.escape="showDropdown = false"
                                @keydown.enter.prevent="submitSearch()"
                                placeholder="Search institutions, services, locations..."
                                class="w-full pl-12 pr-4 py-4 text-lg border-2 border-gray-200 rounded-xl focus:border-green-500 focus:ring-4 focus:ring-green-100 transition"
                                autocomplete="off"
                            >

                            {{-- Loading indicator inside input --}}
                            <div x-show="loading" class="absolute right-4 top-1/2 transform -translate-y-1/2 z-10">
                                <i class="fas fa-spinner fa-spin text-green-500"></i>
                            </div>

                            {{-- Results Dropdown --}}
                            <div x-show="showDropdown && results.length > 0"
                                 x-transition:enter="transition ease-out duration-150"
                                 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-100"
                                 x-transition:leave-start="opacity-100"
                                 x-transition:leave-end="opacity-0"
                                 class="absolute z-50 w-full bg-white shadow-2xl rounded-xl mt-1 max-h-80 overflow-y-auto border border-gray-100">
                                <template x-for="result in results" :key="result.slug">
                                    <a :href="result.url"
                                       class="flex items-center gap-3 px-4 py-3 hover:bg-green-50 border-b border-gray-50 last:border-0 transition">
                                        <div class="w-9 h-9 rounded-lg bg-green-100 flex-shrink-0 flex items-center justify-center overflow-hidden">
                                            <template x-if="result.logo_url">
                                                <img :src="result.logo_url" class="w-full h-full object-contain p-1" :alt="result.name">
                                            </template>
                                            <template x-if="!result.logo_url">
                                                <i class="fas fa-hospital text-green-500 text-sm"></i>
                                            </template>
                                        </div>
                                        <div class="flex-1 min-w-0">
                                            <div class="font-semibold text-gray-800 text-sm truncate" x-text="result.name"></div>
                                            <div class="text-xs text-gray-500 flex items-center gap-1">
                                                <i class="fas fa-map-marker-alt text-green-400"></i>
                                                <span x-text="result.city"></span>
                                            </div>
                                        </div>
                                        <i class="fas fa-arrow-right text-gray-300 text-xs flex-shrink-0"></i>
                                    </a>
                                </template>
                            </div>

                            {{-- No Results --}}
                            <div x-show="showDropdown && results.length === 0 && query.length >= 2 && !loading"
                                 x-transition
                                 class="absolute z-50 w-full bg-white shadow-2xl rounded-xl mt-1 p-4 text-center text-gray-500 border border-gray-100">
                                <i class="fas fa-search-minus text-gray-300 text-2xl mb-2 block"></i>
                                No institutions found for "<span x-text="query" class="font-medium text-gray-700"></span>"
                            </div>
                        </div>

                        <button type="submit" class="px-8 py-4 bg-gradient-to-r from-green-600 to-green-700 text-white font-semibold rounded-xl hover:from-green-700 hover:to-green-800 transition shadow-lg hover:shadow-xl whitespace-nowrap">
                            <i class="fas fa-search mr-2"></i>Search
                        </button>
                    </div>
                    
                    {{-- Filters Row --}}
                    <div class="mt-4 flex flex-wrap gap-4 items-center">
                        {{-- City Filter --}}
                        <div class="flex-1 min-w-[200px]">
                            <select name="city"
                                    id="city-filter"
                                    @change="$el.form.submit()"
                                    class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-green-500 transition cursor-pointer">
                                <option value="">All Cities</option>
                                @foreach($cities as $cityName => $count)
                                    <option value="{{ $cityName }}" {{ request('city') == $cityName ? 'selected' : '' }}>
                                        {{ $cityName }} ({{ $count }})
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        
                        {{-- Service Filter --}}
                        <div class="flex-1 min-w-[200px]">
                            <select name="services"
                                    id="services-filter"
                                    @change="$el.form.submit()"
                                    class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-green-500 transition cursor-pointer">
                                <option value="">All Services</option>
                                @foreach($services as $serviceName => $count)
                                    <option value="{{ $serviceName }}" {{ request('services') == $serviceName ? 'selected' : '' }}>
                                        {{ $serviceName }} ({{ $count }})
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        
                        {{-- Clear Filters --}}
                        @if(request('city') || request('services') || request('q'))
                            <a href="{{ route('institutions.index') }}"
                               class="flex items-center gap-1 px-4 py-3 text-red-600 hover:text-red-700 font-medium whitespace-nowrap transition">
                                <i class="fas fa-times"></i>Clear Filters
                            </a>
                        @endif
                    </div>
                </form>
            </div>
        </div>
    </section>
    
    {{-- Breadcrumb --}}
    <div class="bg-gray-50 border-b border-gray-200">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3">
            <nav class="flex items-center space-x-2 text-sm text-gray-600" aria-label="Breadcrumb">
                <a href="{{ url('/') }}" class="hover:text-green-600 transition flex items-center">
                    <i class="fas fa-home mr-1"></i>Home
                </a>
                <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
                <span class="text-gray-900 font-medium">Health Institution Directory</span>
            </nav>
        </div>
    </div>

    {{-- Main Content --}}
    <section class="py-12 bg-gray-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="lg:flex lg:gap-8">
                {{-- Main Grid --}}
                <div class="lg:flex-1">
                    {{-- Results Header --}}
                    <div class="flex items-center justify-between mb-6">
                        <h2 class="text-2xl font-bold text-gray-800">
                            {{ $institutions->total() }} Health Institutions Found
                        </h2>
                        
                        {{-- View Toggle --}}
                        <div class="flex items-center gap-2">
                            <span class="text-sm text-gray-500">View:</span>
                            <button class="p-2 rounded-lg bg-green-600 text-white">
                                <i class="fas fa-th-large"></i>
                            </button>
                            <button class="p-2 rounded-lg bg-gray-200 text-gray-600 hover:bg-gray-300 transition">
                                <i class="fas fa-list"></i>
                            </button>
                        </div>
                    </div>
                    
                    {{-- Institutions Grid --}}
                    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                        @forelse($institutions as $institution)
                            <a href="{{ route('institutions.show', $institution->slug) }}" 
                               class="group bg-white rounded-xl shadow-md hover:shadow-xl transition-all duration-300 overflow-hidden">
                                {{-- Image --}}
                                <div class="relative h-48 bg-gradient-to-br from-green-100 to-green-200">
                                    @if($institution->logo)
                                        <img src="{{ $institution->logo_url }}" 
                                             alt="{{ $institution->name }}"
                                             class="w-full h-full object-contain p-4">
                                    @else
                                        <div class="w-full h-full flex items-center justify-center">
                                            <i class="fas fa-hospital text-6xl text-green-300"></i>
                                        </div>
                                    @endif
                                    
                                    {{-- Status Badge --}}
                                    <span class="absolute top-3 right-3 px-2 py-1 bg-green-600 text-white text-xs font-semibold rounded-full">
                                        Verified
                                    </span>
                                </div>
                                
                                {{-- Content --}}
                                <div class="p-5">
                                    <h3 class="text-lg font-bold text-gray-800 group-hover:text-green-600 transition mb-1">
                                        {{ Str::limit($institution->name, 40) }}
                                    </h3>
                                    
                                    <div class="flex items-center text-gray-500 text-sm mb-3">
                                        <i class="fas fa-map-marker-alt mr-1 text-green-500"></i>
                                        {{ $institution->city }}, {{ $institution->country }}
                                    </div>
                                    
                                    <p class="text-gray-600 text-sm line-clamp-2 mb-3">
                                        {{ Str::limit($institution->description, 100) }}
                                    </p>
                                    
                                    {{-- Services Tags --}}
                                    <div class="flex flex-wrap gap-1">
                                        @foreach(array_slice($institution->services ?? [], 0, 3) as $service)
                                            <span class="px-2 py-1 bg-green-50 text-green-700 text-xs rounded-full">
                                                {{ $service }}
                                            </span>
                                        @endforeach
                                        @if(count($institution->services ?? []) > 3)
                                            <span class="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full">
                                                +{{ count($institution->services) - 3 }} more
                                            </span>
                                        @endif
                                    </div>
                                </div>
                                
                                {{-- View More --}}
                                <div class="px-5 py-3 bg-gray-50 border-t border-gray-100">
                                    <span class="text-green-600 font-medium text-sm group-hover:text-green-700">
                                        View Details <i class="fas fa-arrow-right ml-1 transition group-hover:translate-x-1"></i>
                                    </span>
                                </div>
                            </a>
                        @empty
                            <div class="col-span-full text-center py-16">
                                <i class="fas fa-hospital text-6xl text-gray-300 mb-4"></i>
                                <h3 class="text-xl font-semibold text-gray-700 mb-2">No institutions found</h3>
                                <p class="text-gray-500 mb-4">Try adjusting your search or filters</p>
                                <a href="{{ route('institutions.index') }}" class="text-green-600 hover:text-green-700 font-medium">
                                    Clear all filters
                                </a>
                            </div>
                        @endforelse
                    </div>
                    
                    {{-- Pagination --}}
                    {{ $institutions->appends(request()->query())->links() }}
                </div>
                
                {{-- Sidebar --}}
                <aside class="lg:w-80 mt-8 lg:mt-0">
                    {{-- Register CTA --}}
                    <div class="bg-gradient-to-br from-green-600 to-green-700 rounded-xl p-6 text-white mb-6">
                        <h3 class="text-xl font-bold mb-2">
                            <i class="fas fa-plus-circle mr-2"></i>List Your Institution
                        </h3>
                        <p class="text-green-100 text-sm mb-4">
                            Register your healthcare facility and reach patients across South Sudan.
                        </p>
                        <a href="{{ route('institutions.register') }}" 
                           class="inline-block px-6 py-3 bg-white text-green-700 font-semibold rounded-lg hover:bg-green-50 transition">
                            Register Now
                        </a>
                    </div>
                    
                    {{-- Featured Institutions --}}
                    @if($featured->count() > 0)
                        <div class="bg-white rounded-xl shadow-md p-6">
                            <h3 class="text-lg font-bold text-gray-800 mb-4">
                                <i class="fas fa-star text-yellow-500 mr-2"></i>Featured Institutions
                            </h3>
                            <div class="space-y-4">
                                @foreach($featured as $featuredInst)
                                    <a href="{{ route('institutions.show', $featuredInst->slug) }}" 
                                       class="flex items-center gap-3 group">
                                        <div class="w-12 h-12 rounded-lg bg-green-100 flex-shrink-0 flex items-center justify-center">
                                            @if($featuredInst->logo)
                                                <img src="{{ $featuredInst->logo_url }}" class="w-8 h-8 object-contain">
                                            @else
                                                <i class="fas fa-hospital text-green-500"></i>
                                            @endif
                                        </div>
                                        <div class="flex-1 min-w-0">
                                            <h4 class="text-sm font-semibold text-gray-800 group-hover:text-green-600 truncate">
                                                {{ $featuredInst->name }}
                                            </h4>
                                            <p class="text-xs text-gray-500">{{ $featuredInst->city }}</p>
                                        </div>
                                    </a>
                                @endforeach
                            </div>
                        </div>
                    @endif
                </aside>
            </div>
        </div>
    </section>

    @push('scripts')
    <script>
        /**
         * institutionSearch — Alpine.js component for the hero search bar.
         *
         * Responsibilities:
         *  1. Real-time AJAX dropdown as the user types (≥2 chars).
         *  2. Clicking a dropdown result navigates directly to that institution.
         *  3. Pressing Enter or clicking "Search" submits the form for a full
         *     paginated results page (respects city/services filters too).
         *  4. Initialises `query` from the server-rendered value so the input
         *     is pre-filled when the page loads with an existing ?q= param.
         *
         * @param {string} endpoint  URL for the AJAX search API
         * @param {string} formAction  URL for the full-page search form
         */
        function institutionSearch(endpoint, formAction) {
            return {
                // Seed from the hidden input so Alpine picks up the server value
                query: document.getElementById('institution-search-input')
                    ? document.getElementById('institution-search-input').getAttribute('value') || ''
                    : '',
                results: [],
                showDropdown: false,
                loading: false,
                _abortController: null,

                /**
                 * Fetch real-time suggestions from the API.
                 * Aborts any in-flight request before starting a new one.
                 */
                async search() {
                    const q = this.query.trim();

                    if (q.length < 2) {
                        this.results = [];
                        this.showDropdown = false;
                        return;
                    }

                    // Abort previous request if still pending
                    if (this._abortController) {
                        this._abortController.abort();
                    }
                    this._abortController = new AbortController();

                    this.loading = true;
                    this.showDropdown = true;

                    try {
                        const res = await fetch(
                            `${endpoint}?q=${encodeURIComponent(q)}`,
                            { signal: this._abortController.signal }
                        );

                        if (!res.ok) throw new Error(`HTTP ${res.status}`);

                        const data = await res.json();
                        // API returns { results: [...] }
                        this.results = Array.isArray(data.results) ? data.results : [];
                    } catch (e) {
                        if (e.name !== 'AbortError') {
                            // Network / parse error — silently clear results
                            this.results = [];
                        }
                    } finally {
                        this.loading = false;
                    }
                },

                /**
                 * Submit the form for a full paginated search.
                 * Hides the dropdown first so it doesn't flash on the new page.
                 */
                submitSearch() {
                    this.showDropdown = false;
                    document.getElementById('institutions-filter-form').submit();
                },
            };
        }
    </script>
    @endpush
</x-site-layout>
