@props(['machines' => collect(), 'allCategories' => collect(), 'allBrands' => collect()])

@php
    /*
     * allCategories and allBrands come from the full DB (passed by HomeController)
     * so the filter dropdowns always reflect every published machine, not just
     * the 6 shown on first load.
     */
    $categories = $allCategories->isNotEmpty()
        ? $allCategories
        : $machines->pluck('category')->filter()->unique()->sort()->values();

    $brands = $allBrands->isNotEmpty()
        ? $allBrands
        : $machines->pluck('brand')->filter()->unique()->sort()->values();

    $machineData = $machines->map(function ($machine) {
        $imageUrl = null;
        if ($machine->primary_image) {
            $imageUrl = asset('storage/' . $machine->primary_image);
        } elseif (!empty($machine->images) && is_array($machine->images)) {
            $imageUrl = asset('storage/' . $machine->images[0]);
        }
        return [
            'id'          => $machine->id,
            'name'        => $machine->name,
            'slug'        => $machine->slug,
            'brand'       => $machine->brand,
            'model'       => $machine->model,
            'category'    => $machine->category,
            'description' => $machine->description
                                ? \Illuminate\Support\Str::limit($machine->description, 100)
                                : null,
            'image'       => $imageUrl,
            'url'         => route('machines.show', $machine->slug),
        ];
    })->values()->toArray();

    $popularCategories = $categories->take(5)->values();
@endphp

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

    <div
        x-data="{
            query: '',
            categoryFilter: '',
            brandFilter: '',
            results: @js($machineData),
            defaultResults: @js($machineData),
            loading: false,
            error: null,
            searchUrl: '{{ route('api.machines.filter') }}',

            get hasActiveFilters() {
                return this.query.trim() !== '' || this.categoryFilter !== '' || this.brandFilter !== '';
            },

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

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

                try {
                    const params = new URLSearchParams();
                    if (this.query.trim())    params.set('q',        this.query.trim());
                    if (this.categoryFilter)  params.set('category', this.categoryFilter);
                    if (this.brandFilter)     params.set('brand',    this.brandFilter);

                    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.machines.filter → search() returns { machines: [...] } */
                    const raw  = data.machines ?? data.data ?? data;

                    this.results = Array.isArray(raw) ? raw.map(m => ({
                        id:          m.id,
                        name:        m.name,
                        slug:        m.slug,
                        brand:       m.brand       ?? null,
                        model:       m.model       ?? null,
                        category:    m.category    ?? null,
                        description: m.description ?? null,
                        image:       m.primary_image_url ?? m.image ?? null,
                        url:         m.url ?? ('/machines/' + m.slug),
                    })) : [];

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

            doSearch() {
                this.search();
            },

            clearAll() {
                this.query          = '';
                this.categoryFilter = '';
                this.brandFilter    = '';
                this.results        = this.defaultResults;
                this.error          = null;
            },

            heroCard()   { return this.results[0] ?? null; },
            stackCards() { return this.results.slice(1, 3); },
            bottomRow()  { return this.results.slice(3, 6); }
        }"
    >

    {{-- ══════════════════════════════════════════════════════════════
         COMPACT HERO — navy blue background, green/red accents
         Requirements: 11.1, 11.2, 11.3, 11.4, 11.5, 11.6, 11.7
    ══════════════════════════════════════════════════════════════ --}}
    <div class="relative w-full overflow-hidden" style="background-color: #0f172a;">

        {{-- Subtle dot 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="mach-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(#mach-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: 11.2 --}}
                <h2 class="text-3xl sm:text-4xl font-extrabold text-white leading-tight mb-2">
                    Discover
                    <span class="text-green-400">Digital Health</span>
                    Equipment
                </h2>
                <p class="text-white/70 text-sm sm:text-base mb-1">
                    Cutting-edge medical machines available 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-microchip text-cyan-300 text-[11px]"></i> Equipment
                    </button>
                    @if($categories->isNotEmpty())
                    <div class="relative">
                        <select x-model="categoryFilter" x-on:change="doSearch()"
                                class="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 category">
                            <option value="" class="text-gray-900 bg-white">All Categories</option>
                            @foreach($categories as $cat)
                                <option value="{{ $cat }}" class="text-gray-900 bg-white">{{ $cat }}</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
                    @if($brands->isNotEmpty())
                    <div class="relative">
                        <select x-model="brandFilter" x-on:change="doSearch()"
                                class="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 brand">
                            <option value="" class="text-gray-900 bg-white">All Brands</option>
                            @foreach($brands as $brand)
                                <option value="{{ $brand }}" class="text-gray-900 bg-white">{{ $brand }}</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 digital health machines">
                    <input
                        type="search"
                        x-model="query"
                        x-on:input.debounce.400ms="doSearch()"
                        x-on:keydown.enter.prevent="doSearch()"
                        placeholder="Search by name, brand, or model..."
                        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 machines"
                        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 category quick-links --}}
                @if($popularCategories->isNotEmpty())
                <div class="flex flex-wrap items-center justify-center gap-2 text-xs">
                    <span class="text-white/60 font-medium">Popular:</span>
                    @foreach($popularCategories as $cat)
                    <button type="button"
                            x-on:click="categoryFilter = '{{ $cat }}'; 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">
                        {{ $cat }}
                    </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 --}}
            <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="categoryFilter">
                        <span class="inline-flex items-center gap-1.5 bg-cyan-100 dark:bg-cyan-900/30 border border-cyan-300 dark:border-cyan-700 text-cyan-700 dark:text-cyan-300 text-xs font-semibold px-3 py-1 rounded-full">
                            <i class="fa-solid fa-tag text-[9px]" aria-hidden="true"></i>
                            <span x-text="categoryFilter"></span>
                            <button type="button" x-on:click="categoryFilter=''; doSearch()" class="ml-1 hover:text-cyan-900 dark:hover:text-white focus:outline-none" aria-label="Remove category filter">
                                <i class="fa-solid fa-xmark text-[9px]"></i>
                            </button>
                        </span>
                    </template>
                    <template x-if="brandFilter">
                        <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-building text-[9px]" aria-hidden="true"></i>
                            <span x-text="brandFilter"></span>
                            <button type="button" x-on:click="brandFilter=''; doSearch()" class="ml-1 hover:text-blue-900 dark:hover:text-white focus:outline-none" aria-label="Remove brand 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-indigo-100 dark:bg-indigo-900/30 border border-indigo-300 dark:border-indigo-700 text-indigo-700 dark:text-indigo-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-indigo-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 ? ' machines' : ' machine'"></span> found
                </p>
            </div>

            {{-- Loading skeleton --}}
            <div x-show="loading" x-cloak aria-busy="true" aria-label="Loading results">
                <div class="grid grid-cols-1 lg:grid-cols-3 overflow-hidden rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700 animate-pulse">
                    <div class="lg:col-span-2 bg-gray-300 dark:bg-gray-700 min-h-[300px]"></div>
                    <div class="flex flex-col border-l border-gray-200 dark:border-gray-700">
                        <div class="flex-1 bg-gray-200 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 min-h-[150px]"></div>
                        <div class="flex-1 bg-gray-200 dark:bg-gray-800 min-h-[150px]"></div>
                    </div>
                </div>
            </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-cyan-50 dark:bg-cyan-900/20 flex items-center justify-center mb-4 border border-cyan-100 dark:border-cyan-800">
                    <i class="fa-solid fa-computer text-cyan-300 text-2xl" aria-hidden="true"></i>
                </div>
                <h3 class="text-lg font-bold text-gray-800 dark:text-white mb-1">No machines 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-cyan-600 hover:text-cyan-700 dark:text-cyan-400 hover:underline focus:outline-none">
                    Clear all filters
                </button>
            </div>

            {{-- Row 1: wide hero card (2/3) + 2 stacked (1/3) --}}
            <div x-show="results.length > 0 && !loading"
                 class="grid grid-cols-1 lg:grid-cols-3 overflow-hidden rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700"
                 role="list" aria-label="Featured machines">
                <template x-if="heroCard()">
                    <article class="lg:col-span-2 relative group overflow-hidden bg-gray-900 min-h-[300px] flex flex-col" role="listitem">
                        <template x-if="heroCard().image">
                            <img :src="heroCard().image" :alt="heroCard().name"
                                 class="absolute inset-0 w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" loading="lazy">
                        </template>
                        <template x-if="!heroCard().image">
                            <div class="absolute inset-0 flex items-center justify-center"
                                 style="background: linear-gradient(135deg, #1e3a5f, #0e7490);">
                                <i class="fa-solid fa-computer text-white/10 text-9xl" aria-hidden="true"></i>
                            </div>
                        </template>
                        <div class="absolute inset-0 bg-gradient-to-t from-black/85 via-black/20 to-transparent"></div>
                        <div class="relative z-10 mt-auto p-6 sm:p-8">
                            <div class="flex flex-wrap gap-2 mb-3">
                                <span x-show="heroCard().category" x-text="heroCard().category"
                                      class="text-xs font-bold uppercase tracking-wider bg-cyan-500/80 text-white px-2.5 py-1 rounded-full"></span>
                                <span x-show="heroCard().brand" x-text="heroCard().brand"
                                      class="text-xs font-medium bg-white/20 text-white px-2.5 py-1 rounded-full"></span>
                            </div>
                            <h3 class="text-xl sm:text-2xl font-black text-white leading-snug mb-2 line-clamp-2" x-text="heroCard().name"></h3>
                            <p class="text-white/65 text-sm line-clamp-2 mb-4" x-show="heroCard().description" x-text="heroCard().description"></p>
                            <a :href="heroCard().url"
                               class="inline-flex items-center gap-2 text-sm font-bold text-white border border-white/40 hover:bg-white hover:text-gray-900 px-4 py-2 rounded-lg transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-white/50"
                               :aria-label="'View details for ' + heroCard().name">
                                View Details
                                <i class="fa-solid fa-arrow-right text-xs" aria-hidden="true"></i>
                            </a>
                        </div>
                    </article>
                </template>

                <div class="flex flex-col border-l border-gray-700">
                    <template x-for="(machine, idx) in stackCards()" :key="'stack-' + machine.id">
                        <article class="relative group overflow-hidden bg-gray-800 flex-1 min-h-[150px] flex flex-col"
                                 :class="idx === 0 ? 'border-b border-gray-700' : ''" role="listitem">
                            <template x-if="machine.image">
                                <img :src="machine.image" :alt="machine.name"
                                     class="absolute inset-0 w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" loading="lazy">
                            </template>
                            <template x-if="!machine.image">
                                <div class="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-slate-700 to-slate-900">
                                    <i class="fa-solid fa-computer text-white/10 text-5xl" aria-hidden="true"></i>
                                </div>
                            </template>
                            <div class="absolute inset-0 bg-gradient-to-t from-black/75 via-black/10 to-transparent"></div>
                            <div class="relative z-10 mt-auto p-4 sm:p-5">
                                <span x-show="machine.category" x-text="machine.category"
                                      class="text-[10px] font-bold uppercase tracking-wider bg-blue-500/70 text-white px-2 py-0.5 rounded-full mb-2 inline-block"></span>
                                <h3 class="text-sm font-bold text-white leading-snug line-clamp-2 mb-2" x-text="machine.name"></h3>
                                <a :href="machine.url"
                                   class="inline-flex items-center gap-1.5 text-xs font-bold text-white/80 hover:text-white transition-colors focus:outline-none"
                                   :aria-label="'View details for ' + machine.name">
                                    Read More <i class="fa-solid fa-chevron-right text-[9px]" aria-hidden="true"></i>
                                </a>
                            </div>
                        </article>
                    </template>
                </div>
            </div>

            {{-- Row 2: 3 equal cards --}}
            <div x-show="results.length > 3 && !loading"
                 class="grid grid-cols-1 sm:grid-cols-3 overflow-hidden rounded-b-2xl border-x border-b border-gray-200 dark:border-gray-700 shadow-lg -mt-px"
                 role="list" aria-label="More machines">
                <template x-for="(machine, idx) in bottomRow()" :key="'bottom-' + machine.id">
                    <article class="relative group overflow-hidden bg-gray-800 flex flex-col"
                             :class="idx < 2 ? 'border-r border-gray-700' : ''" role="listitem">
                        <div class="relative overflow-hidden h-40">
                            <template x-if="machine.image">
                                <img :src="machine.image" :alt="machine.name"
                                     class="absolute inset-0 w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" loading="lazy">
                            </template>
                            <template x-if="!machine.image">
                                <div class="absolute inset-0 flex items-center justify-center"
                                     :class="idx === 0 ? 'bg-gradient-to-br from-blue-900 to-blue-700' : idx === 1 ? 'bg-gradient-to-br from-teal-900 to-teal-700' : 'bg-gradient-to-br from-cyan-900 to-cyan-700'">
                                    <i class="fa-solid fa-computer text-white/20 text-5xl" aria-hidden="true"></i>
                                </div>
                            </template>
                            <div class="absolute inset-0 bg-gradient-to-b from-transparent to-black/30"></div>
                        </div>
                        <div class="relative z-10 p-4"
                             :class="idx === 0 ? 'bg-blue-700' : idx === 1 ? 'bg-teal-600' : 'bg-cyan-600'">
                            <h3 class="text-sm font-bold text-white leading-snug line-clamp-2 mb-1" x-text="machine.name"></h3>
                            <p class="text-white/70 text-xs line-clamp-1 mb-3"
                               x-show="machine.brand || machine.category"
                               x-text="[machine.brand, machine.category].filter(Boolean).join(' · ')"></p>
                            <a :href="machine.url"
                               class="inline-flex items-center gap-1.5 text-xs font-bold text-white/90 hover:text-white transition-colors focus:outline-none"
                               :aria-label="'View details for ' + machine.name">
                                View Details <i class="fa-solid fa-arrow-right text-[10px]" aria-hidden="true"></i>
                            </a>
                        </div>
                    </article>
                </template>
            </div>

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

        </div>
    </div>

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

</section>
