{{-- 
    Digital Machine Showcase Listing
    E-commerce style listing with search and filtering
    
    Uses: <x-site-layout>
    Requirements: 6.1, 6.5
--}}
<x-site-layout 
    title="Digital Health Machines"
    meta-description="Discover medical equipment and health machines. Browse diagnostic devices, surgical equipment, and more."
>
    {{-- Hero Section --}}
    <section class="relative bg-gradient-to-br from-blue-600 via-blue-700 to-indigo-800">
        <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">
            <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-microscope mr-3"></i>Digital Health Machines
                </h1>
                <p class="text-base text-blue-100 max-w-3xl mx-auto">
                    Explore cutting-edge medical equipment and diagnostic devices for your healthcare facility.
                </p>
            </div>
            
            {{-- Search + Filters (unified form with Alpine real-time dropdown) --}}
            <div class="max-w-4xl mx-auto"
                 x-data="machineSearch('{{ route('api.machines.search') }}', '{{ route('machines.index') }}')"
                 @click.outside="showDropdown = false">

                <form id="machines-filter-form" action="{{ route('machines.index') }}" method="GET"
                      class="bg-white rounded-2xl shadow-2xl p-5">

                    {{-- Search Row --}}
                    <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="machine-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 machines, brands, categories..."
                                class="w-full pl-12 pr-10 py-4 text-lg border-2 border-gray-200 rounded-xl focus:border-blue-500 focus:ring-4 focus:ring-blue-100 transition"
                                autocomplete="off"
                            >

                            {{-- Spinner --}}
                            <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-blue-500"></i>
                            </div>

                            {{-- Dropdown Results --}}
                            <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-blue-50 border-b border-gray-50 last:border-0 transition">
                                        <div class="w-10 h-10 rounded-lg bg-gray-100 flex-shrink-0 overflow-hidden">
                                            <template x-if="result.primary_image_url">
                                                <img :src="result.primary_image_url" :alt="result.name" class="w-full h-full object-cover">
                                            </template>
                                            <template x-if="!result.primary_image_url">
                                                <div class="w-full h-full flex items-center justify-center">
                                                    <i class="fas fa-x-ray text-gray-400 text-sm"></i>
                                                </div>
                                            </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 gap-2">
                                                <span x-show="result.brand" x-text="result.brand"></span>
                                                <span x-show="result.brand && result.category" class="text-gray-300">•</span>
                                                <span x-show="result.category" x-text="result.category"></span>
                                            </div>
                                        </div>
                                        <i class="fas fa-arrow-right text-blue-400 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 machines 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-blue-600 to-blue-700 text-white font-semibold rounded-xl hover:from-blue-700 hover:to-blue-800 transition shadow-lg hover:shadow-xl whitespace-nowrap">
                            <i class="fas fa-search mr-2"></i>Search
                        </button>
                    </div>

                    {{-- Filter Row --}}
                    <div class="mt-4 flex flex-wrap gap-4 items-center">
                        {{-- Category Filter --}}
                        <div class="flex-1 min-w-[200px]">
                            <select name="category"
                                    id="category-filter"
                                    @change="$el.form.submit()"
                                    class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition cursor-pointer">
                                <option value="">All Categories</option>
                                @foreach($categories as $catName => $count)
                                    <option value="{{ $catName }}" {{ request('category') == $catName ? 'selected' : '' }}>
                                        {{ $catName }} ({{ $count }})
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        {{-- Brand Filter --}}
                        <div class="flex-1 min-w-[200px]">
                            <select name="brand"
                                    id="brand-filter"
                                    @change="$el.form.submit()"
                                    class="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-blue-500 transition cursor-pointer">
                                <option value="">All Brands</option>
                                @foreach($brands as $brandName => $count)
                                    <option value="{{ $brandName }}" {{ request('brand') == $brandName ? 'selected' : '' }}>
                                        {{ $brandName }} ({{ $count }})
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        {{-- Price Visible Toggle --}}
                        <label class="flex items-center gap-2 px-4 py-3 bg-gray-50 border-2 border-gray-200 rounded-lg cursor-pointer hover:border-blue-400 transition whitespace-nowrap">
                            <input type="checkbox" name="price_visible" value="1"
                                   {{ request('price_visible') ? 'checked' : '' }}
                                   @change="$el.form.submit()"
                                   class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500">
                            <span class="text-sm text-gray-700">Price Visible Only</span>
                        </label>

                        {{-- Clear Filters --}}
                        @if(request('category') || request('brand') || request('q') || request('price_visible'))
                            <a href="{{ route('machines.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-blue-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">Digital Health Machines</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">
                            {{ $machines->total() }} Health Machines Found
                        </h2>
                        
                        <div class="flex items-center gap-2">
                            <button class="p-2 rounded-lg bg-blue-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>
                    
                    {{-- Machines Grid --}}
                    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                        @forelse($machines as $machine)
                            <a href="{{ route('machines.show', $machine->slug) }}" 
                               class="group bg-white rounded-xl shadow-md hover:shadow-xl transition-all duration-300 overflow-hidden">
                                {{-- Image --}}
                                <div class="relative h-56 bg-gradient-to-br from-gray-100 to-gray-200">
                                    @if($machine->primary_image)
                                        <img src="{{ $machine->primary_image_url }}" 
                                             alt="{{ $machine->name }}"
                                             class="w-full h-full object-cover group-hover:scale-105 transition duration-300">
                                    @else
                                        <div class="w-full h-full flex items-center justify-center">
                                            <i class="fas fa-x-ray text-6xl text-gray-300"></i>
                                        </div>
                                    @endif
                                    
                                    @if($machine->category)
                                        <span class="absolute top-3 left-3 px-3 py-1 bg-blue-600 text-white text-xs font-semibold rounded-full">
                                            {{ $machine->category }}
                                        </span>
                                    @endif
                                    
                                    @if($machine->price_publishable && ($machine->price_ssp || $machine->price_usd))
                                        <span class="absolute bottom-3 right-3 px-3 py-1 bg-green-600 text-white text-sm font-bold rounded-full">
                                            {{ $machine->formatted_price }}
                                        </span>
                                    @endif
                                </div>
                                
                                {{-- Content --}}
                                <div class="p-5">
                                    <h3 class="text-lg font-bold text-gray-800 group-hover:text-blue-600 transition mb-1 line-clamp-1">
                                        {{ $machine->name }}
                                    </h3>
                                    
                                    <div class="flex items-center text-gray-500 text-sm mb-2">
                                        @if($machine->brand)
                                            <span class="mr-2">
                                                <i class="fas fa-tag mr-1 text-blue-500"></i>{{ $machine->brand }}
                                            </span>
                                        @endif
                                        @if($machine->model)
                                            <span>
                                                <i class="fas fa-barcode mr-1 text-blue-500"></i>{{ $machine->model }}
                                            </span>
                                        @endif
                                    </div>
                                    
                                    <p class="text-gray-600 text-sm line-clamp-2 mb-3">
                                        {{ Str::limit($machine->description, 100) }}
                                    </p>
                                    
                                    <div class="flex flex-wrap gap-1">
                                        @foreach(array_slice($machine->functionalities ?? [], 0, 3) as $func)
                                            <span class="px-2 py-1 bg-blue-50 text-blue-700 text-xs rounded-full">
                                                {{ $func }}
                                            </span>
                                        @endforeach
                                        @if(count($machine->functionalities ?? []) > 3)
                                            <span class="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full">
                                                +{{ count($machine->functionalities) - 3 }} more
                                            </span>
                                        @endif
                                    </div>
                                    
                                    @if(!$machine->price_publishable)
                                        <div class="mt-3 text-gray-500 text-sm font-medium">
                                            <i class="fas fa-eye-slash mr-1"></i>Contact for Price
                                        </div>
                                    @endif
                                </div>
                                
                                <div class="px-5 py-3 bg-gray-50 border-t border-gray-100">
                                    <span class="text-blue-600 font-medium text-sm group-hover:text-blue-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-x-ray text-6xl text-gray-300 mb-4"></i>
                                <h3 class="text-xl font-semibold text-gray-700 mb-2">No machines found</h3>
                                <p class="text-gray-500 mb-4">Try adjusting your search or filters</p>
                                <a href="{{ route('machines.index') }}" class="text-blue-600 hover:text-blue-700 font-medium">
                                    Clear all filters
                                </a>
                            </div>
                        @endforelse
                    </div>
                    
                    {{-- Pagination — preserves all active query params --}}
                    {{ $machines->appends(request()->query())->links() }}
                </div>
                
                {{-- Sidebar --}}
                <aside class="lg:w-80 mt-8 lg:mt-0">
                    {{-- Featured Machines --}}
                    @if($featured->count() > 0)
                        <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                            <h3 class="text-lg font-bold text-gray-800 mb-4">
                                <i class="fas fa-star text-yellow-500 mr-2"></i>Featured Equipment
                            </h3>
                            <div class="space-y-4">
                                @foreach($featured as $featuredMachine)
                                    <a href="{{ route('machines.show', $featuredMachine->slug) }}" 
                                       class="flex items-center gap-3 group">
                                        <div class="w-16 h-16 rounded-lg bg-gray-100 flex-shrink-0 overflow-hidden">
                                            @if($featuredMachine->primary_image)
                                                <img src="{{ $featuredMachine->primary_image_url }}" class="w-full h-full object-cover">
                                            @else
                                                <div class="w-full h-full flex items-center justify-center">
                                                    <i class="fas fa-x-ray text-gray-400"></i>
                                                </div>
                                            @endif
                                        </div>
                                        <div class="flex-1 min-w-0">
                                            <h4 class="text-sm font-semibold text-gray-800 group-hover:text-blue-600 truncate">
                                                {{ $featuredMachine->name }}
                                            </h4>
                                            <p class="text-xs text-gray-500">{{ $featuredMachine->brand }}</p>
                                            @if($featuredMachine->price_publishable)
                                                <p class="text-sm font-bold text-green-600">{{ $featuredMachine->formatted_price }}</p>
                                            @endif
                                        </div>
                                    </a>
                                @endforeach
                            </div>
                        </div>
                    @endif
                    
                    {{-- Categories --}}
                    <div class="bg-white rounded-xl shadow-md p-6 mb-6">
                        <h3 class="text-lg font-bold text-gray-800 mb-4">
                            <i class="fas fa-layer-group text-blue-500 mr-2"></i>Categories
                        </h3>
                        <div class="space-y-2">
                            @foreach($categories as $catName => $count)
                                <a href="{{ route('machines.index', array_merge(request()->query(), ['category' => $catName])) }}" 
                                   class="flex items-center justify-between p-2 rounded-lg hover:bg-blue-50 transition {{ request('category') == $catName ? 'bg-blue-50 text-blue-700 font-medium' : '' }}">
                                    <span class="text-gray-700">{{ $catName }}</span>
                                    <span class="text-gray-400 text-sm">{{ $count }}</span>
                                </a>
                            @endforeach
                        </div>
                    </div>
                    
                    {{-- Register CTA --}}
                    <div class="bg-gradient-to-br from-blue-600 to-blue-700 rounded-xl p-6 text-white">
                        <h3 class="text-xl font-bold mb-2">
                            <i class="fas fa-plus-circle mr-2"></i>List Your Equipment
                        </h3>
                        <p class="text-blue-100 text-sm mb-4">
                            Showcase your medical equipment to healthcare facilities across South Sudan.
                        </p>
                        @auth
                            <a href="{{ route('dashboard.machines.create') }}" 
                               class="inline-block px-6 py-3 bg-white text-blue-700 font-semibold rounded-lg hover:bg-blue-50 transition">
                                Add Machine
                            </a>
                        @else
                            <a href="{{ route('login') }}" 
                               class="inline-block px-6 py-3 bg-white text-blue-700 font-semibold rounded-lg hover:bg-blue-50 transition">
                                Login to Add
                            </a>
                        @endauth
                    </div>
                </aside>
            </div>
        </div>
    </section>

    @push('scripts')
    <script>
        /**
         * machineSearch — Alpine.js component for the hero search bar.
         *
         * 1. Real-time AJAX dropdown as the user types (≥2 chars).
         * 2. Clicking a result navigates directly to that machine.
         * 3. Enter / Search button submits the full paginated form.
         * 4. Initialises query from the server-rendered input value.
         */
        function machineSearch(endpoint, formAction) {
            return {
                query: document.getElementById('machine-search-input')
                    ? document.getElementById('machine-search-input').getAttribute('value') || ''
                    : '',
                results: [],
                showDropdown: false,
                loading: false,
                _abortController: null,

                async search() {
                    const q = this.query.trim();

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

                    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();
                        this.results = Array.isArray(data.results) ? data.results : [];
                    } catch (e) {
                        if (e.name !== 'AbortError') this.results = [];
                    } finally {
                        this.loading = false;
                    }
                },

                submitSearch() {
                    this.showDropdown = false;
                    document.getElementById('machines-filter-form').submit();
                },
            };
        }
    </script>
    @endpush
</x-site-layout>
