@props(['institutions' => collect(), 'allCities' => collect()])

@php
    /*
     * Build the initial dataset from the pre-loaded collection.
     * allCities comes from the full DB (passed by HomeController) so the
     * filter dropdown always reflects every published institution, not just
     * the 12 shown on first load.
     */
    $cities = $allCities->isNotEmpty()
        ? $allCities
        : $institutions->pluck('city')->filter()->unique()->sort()->values();

    $institutionData = $institutions->map(function ($inst) {
        return [
            'id'          => $inst->id,
            'name'        => $inst->name,
            'slug'        => $inst->slug,
            'email'       => $inst->email,
            'website_url' => $inst->website_url,
            'description' => $inst->description
                ? \Illuminate\Support\Str::words($inst->description, 12, '...')
                : null,
            'logo'        => $inst->logo ? asset('storage/' . $inst->logo) : null,
            'city'        => $inst->city,
            'country'     => $inst->country,
            'url'         => route('institutions.show', $inst->slug),
        ];
    })->values()->toArray();

    $popularCities = $cities->take(5)->values();
@endphp

<section id="institutions" class="relative">

    <div
        x-data="{
            query: '',
            cityFilter: '',
            results: @js($institutionData),
            defaultResults: @js($institutionData),
            loading: false,
            error: null,
            page: 1,
            perPage: 6,
            searchUrl: '{{ route('api.institutions.filter') }}',

            get totalPages() { return Math.max(1, Math.ceil(this.results.length / this.perPage)); },
            get paginatedResults() {
                const start = (this.page - 1) * this.perPage;
                return this.results.slice(start, start + this.perPage);
            },
            get hasActiveFilters() { return this.query.trim() !== '' || this.cityFilter !== ''; },

            async search() {
                /*
                 * Always hit the API when any filter is active — including
                 * city-only (no query text). This sources results from the
                 * entire database, bypassing the 12-item pre-loaded default.
                 */
                if (!this.hasActiveFilters) {
                    this.results = this.defaultResults;
                    this.error   = null;
                    this.page    = 1;
                    return;
                }

                this.loading = true;
                this.error   = null;

                try {
                    const params = new URLSearchParams();
                    if (this.query.trim()) params.set('q', this.query.trim());
                    if (this.cityFilter)   params.set('city', this.cityFilter);

                    const res = await fetch(this.searchUrl + '?' + params.toString(), {
                        headers: {
                            'Accept': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    });

                    if (!res.ok) throw new Error('HTTP ' + res.status);

                    const data = await res.json();
                    /* api.institutions.filter → search() returns { institutions: [...] } */
                    const raw  = data.institutions ?? data.data ?? data;

                    this.results = Array.isArray(raw) ? raw.map(inst => ({
                        id:          inst.id,
                        name:        inst.name,
                        slug:        inst.slug,
                        email:       inst.email       ?? null,
                        website_url: inst.website_url ?? null,
                        description: inst.description ?? null,
                        logo:        inst.logo_url    ?? null,
                        city:        inst.city        ?? null,
                        country:     inst.country     ?? null,
                        url:         inst.url         ?? ('/institutions/' + inst.slug),
                    })) : [];

                    this.page = 1;

                } catch (e) {
                    this.error   = 'Search failed. Please try again.';
                    this.results = this.defaultResults;
                } finally {
                    this.loading = false;
                }
            },

            doSearch() {
                this.page = 1;
                this.search();
            },

            clearAll() {
                this.query      = '';
                this.cityFilter = '';
                this.results    = this.defaultResults;
                this.error      = null;
                this.page       = 1;
            },

            prevPage() { if (this.page > 1) this.page--; },
            nextPage() { if (this.page < this.totalPages) this.page++; },
            goToPage(n) { this.page = n; }
        }"
    >

    {{-- ══════════════════════════════════════════════════════════════
         COMPACT HERO — navy blue background, green/red accents
         Requirements: 12.1, 12.2, 12.3, 12.4, 12.5, 12.6
    ══════════════════════════════════════════════════════════════ --}}
    <div class="relative w-full overflow-hidden" style="background-color: #0f172a;">

        {{-- Subtle dot/grid overlay --}}
        <div class="pointer-events-none absolute inset-0 overflow-hidden opacity-10" aria-hidden="true">
            <svg class="absolute inset-0 w-full h-full" xmlns="http://www.w3.org/2000/svg">
                <defs>
                    <pattern id="inst-dots" x="0" y="0" width="24" height="24" patternUnits="userSpaceOnUse">
                        <circle cx="2" cy="2" r="1.5" fill="white"/>
                    </pattern>
                </defs>
                <rect width="100%" height="100%" fill="url(#inst-dots)"/>
            </svg>
        </div>

        <div class="relative z-10 w-full px-4 sm:px-6 lg:px-8 pt-12 pb-20">
            <div class="max-w-3xl mx-auto text-center">

                {{-- Headline — Requirements: 12.2 --}}
                <h2 class="text-3xl sm:text-4xl font-extrabold text-white leading-tight mb-2">
                    Find a
                    <span class="text-green-400">Health Institution</span>
                    Near You
                </h2>
                <p class="text-white/70 text-sm sm:text-base mb-1">
                    Browse registered healthcare facilities across South Sudan
                </p>
                <span class="inline-flex items-center gap-1 text-xs font-bold text-red-400 bg-red-400/10 border border-red-400/30 rounded-full px-3 py-1 mb-6">
                    <i class="fa-solid fa-circle-dot text-[8px]"></i> Live Directory
                </span>

                {{-- Tab-style type switcher --}}
                <div class="inline-flex items-center gap-2 bg-white/15 backdrop-blur-sm border border-white/25 rounded-full px-2 py-1.5 mb-5">
                    <button type="button"
                            class="flex items-center gap-1.5 text-xs font-semibold text-white bg-white/20 border border-white/30 rounded-full px-4 py-1.5 focus:outline-none">
                        <i class="fa-solid fa-hospital text-emerald-300 text-[11px]"></i> Institutions
                    </button>
                    @if($cities->isNotEmpty())
                    <div class="relative">
                        <select x-model="cityFilter" x-on:change="doSearch()"
                                class="flex items-center gap-1.5 text-xs font-semibold text-white/80 bg-transparent border-0 rounded-full px-4 py-1.5 focus:outline-none appearance-none cursor-pointer pr-6"
                                aria-label="Filter by city">
                            <option value="" class="text-gray-900 bg-white">All Cities</option>
                            @foreach($cities as $city)
                                <option value="{{ $city }}" class="text-gray-900 bg-white">{{ $city }}</option>
                            @endforeach
                        </select>
                        <span class="pointer-events-none absolute inset-y-0 right-1.5 flex items-center text-white/50 text-[9px]">
                            <i class="fa-solid fa-chevron-down"></i>
                        </span>
                    </div>
                    @endif
                </div>

                {{-- Search bar — realtime on every keystroke (debounced 400ms) --}}
                <div class="flex items-center bg-white rounded-2xl shadow-lg overflow-hidden max-w-5xl mx-auto mb-4"
                     role="search" aria-label="Search health institutions">
                    <input
                        type="search"
                        x-model="query"
                        x-on:input.debounce.400ms="doSearch()"
                        x-on:keydown.enter.prevent="doSearch()"
                        placeholder="Search by name, city, or service..."
                        class="flex-1 px-5 py-4 text-gray-700 text-sm placeholder-gray-400 bg-transparent border-0 focus:outline-none focus:ring-0"
                        aria-label="Search institutions"
                        autocomplete="off"
                    >
                    <button
                        type="button"
                        x-on:click="doSearch()"
                        class="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-bold px-6 py-4 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-1 shrink-0"
                        aria-label="Search"
                    >
                        <span x-show="!loading"><i class="fa-solid fa-magnifying-glass"></i> Search</span>
                        <span x-show="loading" x-cloak><i class="fa-solid fa-spinner fa-spin"></i> Searching</span>
                    </button>
                </div>

                {{-- Popular city quick-links --}}
                @if($popularCities->isNotEmpty())
                <div class="flex flex-wrap items-center justify-center gap-2 text-xs">
                    <span class="text-white/60 font-medium">Popular:</span>
                    @foreach($popularCities as $city)
                    <button type="button"
                            x-on:click="cityFilter = '{{ $city }}'; doSearch()"
                            class="bg-white/15 hover:bg-white/25 border border-white/25 text-white font-semibold px-3 py-1 rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-white/50">
                        {{ $city }}
                    </button>
                    @endforeach
                </div>
                @endif

                {{-- Error alert --}}
                <div x-show="error" x-cloak
                     class="mt-4 inline-flex items-center gap-2 bg-red-500/20 border border-red-400/40 rounded-xl px-4 py-2.5 text-red-200 text-sm"
                     role="alert">
                    <i class="fa-solid fa-triangle-exclamation shrink-0" aria-hidden="true"></i>
                    <span x-text="error"></span>
                </div>

            </div>
        </div>
    </div>{{-- /hero --}}

    {{-- ══════════════════════════════════════════════════════════════
         RESULTS — overlaps hero with negative margin + rounded top
    ══════════════════════════════════════════════════════════════ --}}
    <div class="relative z-10 -mt-6 bg-gray-50 dark:bg-gray-900 rounded-t-3xl px-4 sm:px-6 lg:px-8 pt-8 pb-12">
        <div class="max-w-screen-xl mx-auto">

            {{-- Active filter chips + result count row --}}
            <div class="flex flex-wrap items-center justify-between gap-3 mb-6">
                <div class="flex flex-wrap items-center gap-2">
                    <template x-if="cityFilter">
                        <span class="inline-flex items-center gap-1.5 bg-teal-100 dark:bg-teal-900/30 border border-teal-300 dark:border-teal-700 text-teal-700 dark:text-teal-300 text-xs font-semibold px-3 py-1 rounded-full">
                            <i class="fa-solid fa-location-dot text-[9px]" aria-hidden="true"></i>
                            <span x-text="cityFilter"></span>
                            <button type="button" x-on:click="cityFilter=''; doSearch()" class="ml-1 hover:text-teal-900 dark:hover:text-white focus:outline-none" aria-label="Remove city filter">
                                <i class="fa-solid fa-xmark text-[9px]"></i>
                            </button>
                        </span>
                    </template>
                    <template x-if="query.trim() !== ''">
                        <span class="inline-flex items-center gap-1.5 bg-blue-100 dark:bg-blue-900/30 border border-blue-300 dark:border-blue-700 text-blue-700 dark:text-blue-300 text-xs font-semibold px-3 py-1 rounded-full">
                            <i class="fa-solid fa-magnifying-glass text-[9px]" aria-hidden="true"></i>
                            <span x-text="'&quot;' + query.trim() + '&quot;'"></span>
                            <button type="button" x-on:click="query=''; doSearch()" class="ml-1 hover:text-blue-900 dark:hover:text-white focus:outline-none" aria-label="Remove search query">
                                <i class="fa-solid fa-xmark text-[9px]"></i>
                            </button>
                        </span>
                    </template>
                    <template x-if="hasActiveFilters">
                        <button type="button" x-on:click="clearAll()"
                                class="text-xs text-gray-400 hover:text-red-500 dark:hover:text-red-400 underline focus:outline-none transition-colors">
                            Clear all
                        </button>
                    </template>
                </div>
                <p class="text-sm text-gray-500 dark:text-gray-400" x-show="results.length > 0">
                    <span class="font-semibold text-gray-700 dark:text-gray-200" x-text="results.length"></span>
                    <span x-text="results.length !== 1 ? ' institutions' : ' institution'"></span> found
                </p>
            </div>

            {{-- Loading skeleton --}}
            <div x-show="loading" x-cloak
                 class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 mb-6"
                 aria-busy="true" aria-label="Loading results">
                <template x-for="n in 6" :key="'skel-' + n">
                    <div class="bg-white dark:bg-gray-800 rounded-2xl overflow-hidden shadow-sm border border-gray-100 dark:border-gray-700 animate-pulse">
                        <div class="flex items-start gap-4 p-5 pb-3">
                            <div class="shrink-0 w-12 h-12 rounded-xl bg-gray-200 dark:bg-gray-700"></div>
                            <div class="flex-1 space-y-2">
                                <div class="h-4 bg-gray-200 dark:bg-gray-700 rounded w-3/4"></div>
                                <div class="h-3 bg-gray-200 dark:bg-gray-700 rounded w-1/2"></div>
                            </div>
                        </div>
                        <div class="mx-5 border-t border-gray-100 dark:border-gray-700"></div>
                        <div class="px-5 py-3 space-y-2">
                            <div class="h-3 bg-gray-200 dark:bg-gray-700 rounded"></div>
                            <div class="h-3 bg-gray-200 dark:bg-gray-700 rounded w-5/6"></div>
                        </div>
                    </div>
                </template>
            </div>

            {{-- Empty state --}}
            <div x-show="results.length === 0 && !loading" x-cloak
                 class="flex flex-col items-center justify-center py-16 text-center" role="status">
                <div class="w-16 h-16 rounded-2xl bg-teal-50 dark:bg-teal-900/20 flex items-center justify-center mb-4 border border-teal-100 dark:border-teal-800">
                    <i class="fa-solid fa-hospital-slash text-teal-300 text-2xl" aria-hidden="true"></i>
                </div>
                <h3 class="text-lg font-bold text-gray-800 dark:text-white mb-1">No institutions found</h3>
                <p class="text-sm text-gray-500 dark:text-gray-400 max-w-xs mb-4">Try adjusting your search or clearing the filters.</p>
                <button type="button" x-on:click="clearAll()"
                        class="text-sm font-semibold text-teal-600 hover:text-teal-700 dark:text-teal-400 hover:underline focus:outline-none">
                    Clear all filters
                </button>
            </div>

            {{-- 3-column card grid --}}
            <div x-show="results.length > 0 && !loading"
                 class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5"
                 role="list" aria-label="Institution results">
                <template x-for="institution in paginatedResults" :key="institution.id">
                    <article
                        class="bg-white dark:bg-gray-800 rounded-2xl overflow-hidden shadow-sm border border-gray-100 dark:border-gray-700 flex flex-col hover:shadow-md transition-shadow duration-200 focus-within:ring-2 focus-within:ring-teal-500"
                        role="listitem"
                    >
                        <div class="flex items-start gap-4 p-5 pb-3">
                            <div class="shrink-0 w-12 h-12 rounded-xl overflow-hidden bg-teal-50 dark:bg-teal-900/20 flex items-center justify-center border border-gray-100 dark:border-gray-700">
                                <template x-if="institution.logo">
                                    <img :src="institution.logo" :alt="institution.name + ' logo'"
                                         class="w-full h-full object-cover" loading="lazy">
                                </template>
                                <template x-if="!institution.logo">
                                    <i class="fa-solid fa-hospital text-teal-400 text-xl" aria-hidden="true"></i>
                                </template>
                            </div>
                            <div class="flex-1 min-w-0">
                                <h3 class="font-bold text-gray-900 dark:text-white text-sm leading-snug line-clamp-2"
                                    x-text="institution.name"></h3>
                                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1 flex items-center gap-1" x-show="institution.city">
                                    <i class="fa-solid fa-location-dot text-teal-500 shrink-0 text-[10px]" aria-hidden="true"></i>
                                    <span x-text="institution.city"></span>
                                    <template x-if="institution.country">
                                        <span x-text="', ' + institution.country" class="truncate"></span>
                                    </template>
                                </p>
                            </div>
                        </div>

                        <div class="mx-5 border-t border-gray-100 dark:border-gray-700"></div>

                        <div class="px-5 py-3 flex-1">
                            <p class="text-sm text-gray-500 dark:text-gray-400 line-clamp-3"
                               x-show="institution.description" x-text="institution.description"></p>
                            <p class="text-sm text-gray-400 dark:text-gray-500 italic"
                               x-show="!institution.description">No description available.</p>
                        </div>

                        <div class="px-5 pb-3 flex flex-wrap gap-x-4 gap-y-1 text-xs text-gray-400 dark:text-gray-500">
                            <span x-show="institution.email" class="flex items-center gap-1 min-w-0">
                                <i class="fa-solid fa-envelope text-teal-400 shrink-0" aria-hidden="true"></i>
                                <span class="truncate" x-text="institution.email"></span>
                            </span>
                        </div>

                        <div class="px-5 py-4 bg-gray-50 dark:bg-gray-700/40 border-t border-gray-100 dark:border-gray-700 mt-auto">
                            <a :href="institution.url"
                               class="inline-flex items-center gap-1.5 text-sm font-semibold text-teal-600 dark:text-teal-400 hover:text-teal-700 dark:hover:text-teal-300 transition-colors focus:outline-none focus:ring-2 focus:ring-teal-500 rounded"
                               :aria-label="'View details for ' + institution.name">
                                View Details
                                <i class="fa-solid fa-arrow-right text-xs" aria-hidden="true"></i>
                            </a>
                        </div>
                    </article>
                </template>
            </div>

            {{-- Pagination --}}
            <div x-show="results.length > 0 && !loading && totalPages > 1" x-cloak
                 class="mt-8 flex items-center justify-center gap-2 flex-wrap"
                 role="navigation" aria-label="Pagination">
                <button type="button" x-on:click="prevPage()" :disabled="page === 1"
                        class="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium border transition-all focus:outline-none focus:ring-2 focus:ring-teal-400"
                        :class="page === 1
                            ? 'border-gray-200 dark:border-gray-700 text-gray-300 dark:text-gray-600 cursor-not-allowed'
                            : 'border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-200 hover:bg-teal-50 dark:hover:bg-teal-900/20 hover:border-teal-400'"
                        aria-label="Previous page">
                    <i class="fa-solid fa-chevron-left text-xs" aria-hidden="true"></i> Prev
                </button>

                <template x-for="n in totalPages" :key="n">
                    <button type="button" x-on:click="goToPage(n)"
                            class="w-9 h-9 rounded-lg text-sm font-semibold border transition-all focus:outline-none focus:ring-2 focus:ring-teal-400"
                            :class="page === n
                                ? 'bg-teal-600 border-teal-600 text-white shadow-sm'
                                : 'border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-200 hover:bg-teal-50 dark:hover:bg-teal-900/20 hover:border-teal-400'"
                            :aria-label="'Go to page ' + n"
                            :aria-current="page === n ? 'page' : null"
                            x-text="n"></button>
                </template>

                <button type="button" x-on:click="nextPage()" :disabled="page === totalPages"
                        class="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium border transition-all focus:outline-none focus:ring-2 focus:ring-teal-400"
                        :class="page === totalPages
                            ? 'border-gray-200 dark:border-gray-700 text-gray-300 dark:text-gray-600 cursor-not-allowed'
                            : 'border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-200 hover:bg-teal-50 dark:hover:bg-teal-900/20 hover:border-teal-400'"
                        aria-label="Next page">
                    Next <i class="fa-solid fa-chevron-right text-xs" aria-hidden="true"></i>
                </button>
            </div>

            {{-- Browse all link --}}
            <div class="mt-8 text-center" x-show="results.length > 0 && !loading">
                <a href="{{ route('institutions.index') }}"
                   class="inline-flex items-center gap-2 text-sm font-semibold text-teal-600 dark:text-teal-400 hover:text-teal-700 dark:hover:text-teal-300 border border-teal-200 dark:border-teal-800 hover:border-teal-400 px-5 py-2.5 rounded-xl transition-all focus:outline-none focus:ring-2 focus:ring-teal-400">
                    Browse Full Directory
                    <i class="fa-solid fa-arrow-right text-xs" aria-hidden="true"></i>
                </a>
            </div>

        </div>
    </div>

    </div>{{-- /x-data --}}

</section>
