@extends('layouts.site')

@section('title', 'Research & Innovation Centre')
@section('meta-description', 'Explore published research, clinical studies, and innovative projects from the SSHIA community.')

@php
    $catLabels = [
        'clinical' => 'Clinical Research',
        'tech'     => 'Technology & Innovation',
        'social'   => 'Social Sciences',
    ];
@endphp

@section('content')

{{-- ══════════════════════════════════════════════════════════════════════════
     HERO + SEARCH
══════════════════════════════════════════════════════════════════════════ --}}
<div class="bg-gradient-to-r from-emerald-700 to-teal-700 shadow-lg"
     x-data="{
         /* ── search state ── */
         query: '{{ addslashes($filters['q'] ?? '') }}',
         category: '{{ addslashes($filters['category'] ?? '') }}',
         searchResults: [],
         searchLoading: false,
         showModal: false,
         searchTimer: null,
         searchUrl: '{{ route('research.public.ajax.search') }}',

         /* ── debounced live search ── */
         onQueryInput() {
             clearTimeout(this.searchTimer);
             if (this.query.trim().length < 2) {
                 this.searchResults = [];
                 this.showModal = false;
                 return;
             }
             this.searchTimer = setTimeout(() => this.runSearch(), 300);
         },

         /* ── category auto-filter (no button click needed) ── */
         onCategoryChange() {
             /* If there is a search query, re-run live search with new category */
             if (this.query.trim().length >= 2) {
                 clearTimeout(this.searchTimer);
                 this.runSearch();
             } else {
                 /* Otherwise submit the page form immediately */
                 this.$nextTick(() => this.$refs.filterForm.submit());
             }
         },

         async runSearch() {
             this.searchLoading = true;
             this.showModal = true;
             try {
                 const params = new URLSearchParams({ q: this.query });
                 if (this.category) params.append('category', this.category);
                 const res  = await fetch(this.searchUrl + '?' + params.toString(), {
                     headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
                 });
                 const json = await res.json();
                 this.searchResults = json.data ?? [];
             } catch(e) {
                 this.searchResults = [];
             } finally {
                 this.searchLoading = false;
             }
         },

         closeModal() {
             this.showModal = false;
             this.searchResults = [];
         }
     }"
     @keydown.escape.window="closeModal()"
>
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div class="flex flex-col md:flex-row items-start md:items-center justify-between mb-8 gap-4">
            <div class="flex items-center gap-4">
                <div class="w-14 h-14 rounded-2xl bg-white/20 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-microscope text-white text-2xl"></i>
                </div>
                <div>
                    <h1 class="text-3xl md:text-4xl font-bold text-white font-serif">
                        Research &amp; Innovation Centre
                    </h1>
                    <p class="text-emerald-100 mt-1">
                        Discover groundbreaking research from our academic community
                    </p>
                </div>
            </div>
            <a href="{{ route('research.public.submit') }}"
               class="inline-flex items-center gap-2 px-5 py-3 bg-white text-emerald-700 rounded-xl font-semibold text-sm hover:bg-emerald-50 transition shadow-sm flex-shrink-0">
                <i class="fas fa-upload"></i>
                Submit Your Research
            </a>
        </div>

        {{-- ── Search + Filter Bar ──────────────────────────────────────── --}}
        <form action="{{ route('research.public.index') }}" method="GET"
              x-ref="filterForm"
              class="bg-white/15 backdrop-blur-sm rounded-2xl p-5">
            <div class="flex flex-col md:flex-row gap-3">

                {{-- Search input with live modal --}}
                <div class="flex-1 relative">
                    <div class="relative">
                        <i class="fas fa-search absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                        <input type="text"
                               name="q"
                               x-model="query"
                               @input="onQueryInput()"
                               @focus="query.trim().length >= 2 && (showModal = true)"
                               placeholder="Search by title, abstract, or keywords…"
                               autocomplete="off"
                               class="w-full pl-11 pr-4 py-3 rounded-xl border-0 focus:ring-2 focus:ring-emerald-400 focus:outline-none text-sm shadow-sm">

                        {{-- Loading spinner --}}
                        <div x-show="searchLoading"
                             class="absolute right-3 top-1/2 -translate-y-1/2">
                            <svg class="animate-spin h-4 w-4 text-emerald-500" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
                            </svg>
                        </div>
                    </div>

                    {{-- ── Live Search Modal ──────────────────────────────── --}}
                    <div x-show="showModal && (searchResults.length > 0 || searchLoading)"
                         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 translate-y-0"
                         x-transition:leave-end="opacity-0 -translate-y-1"
                         @click.outside="closeModal()"
                         class="absolute top-full left-0 right-0 mt-2 bg-white rounded-2xl shadow-2xl border border-gray-100 z-50 overflow-hidden"
                         x-cloak>

                        {{-- Loading state --}}
                        <div x-show="searchLoading" class="p-4 text-center text-sm text-gray-500">
                            <i class="fas fa-spinner fa-spin mr-2 text-emerald-500"></i>
                            Searching publications…
                        </div>

                        {{-- Results --}}
                        <template x-if="!searchLoading && searchResults.length > 0">
                            <div>
                                <div class="px-4 py-2.5 bg-gray-50 border-b border-gray-100 flex items-center justify-between">
                                    <span class="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                                        <span x-text="searchResults.length"></span> result(s) found
                                    </span>
                                    <button type="button" @click="closeModal()"
                                            class="text-gray-400 hover:text-gray-600 transition">
                                        <i class="fas fa-times text-xs"></i>
                                    </button>
                                </div>
                                <div class="divide-y divide-gray-50 max-h-96 overflow-y-auto">
                                    <template x-for="result in searchResults" :key="result.id">
                                        <a :href="result.url"
                                           class="flex items-start gap-3 px-4 py-3 hover:bg-emerald-50 transition group">
                                            {{-- Thumbnail --}}
                                            <div class="w-12 h-12 rounded-lg overflow-hidden flex-shrink-0 bg-gray-100">
                                                <template x-if="result.cover_image">
                                                    <img :src="result.cover_image" :alt="result.title"
                                                         class="w-full h-full object-cover">
                                                </template>
                                                <template x-if="!result.cover_image">
                                                    <div class="w-full h-full flex items-center justify-center">
                                                        <i class="fas fa-file-alt text-gray-400 text-lg"></i>
                                                    </div>
                                                </template>
                                            </div>
                                            {{-- Info --}}
                                            <div class="flex-1 min-w-0">
                                                <p class="text-sm font-semibold text-gray-900 group-hover:text-emerald-700 transition truncate"
                                                   x-text="result.title"></p>
                                                <p class="text-xs text-gray-500 mt-0.5 line-clamp-2"
                                                   x-text="result.abstract"></p>
                                                <div class="flex items-center gap-2 mt-1">
                                                    <span class="text-xs font-medium text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded"
                                                          x-text="result.category_label"></span>
                                                    <span class="text-xs text-gray-400" x-text="result.author"></span>
                                                    <span class="text-xs text-gray-300">•</span>
                                                    <span class="text-xs text-gray-400" x-text="result.date"></span>
                                                </div>
                                            </div>
                                            <i class="fas fa-arrow-right text-gray-300 group-hover:text-emerald-500 transition text-xs flex-shrink-0 mt-1"></i>
                                        </a>
                                    </template>
                                </div>
                                {{-- View all results link --}}
                                <div class="px-4 py-3 bg-gray-50 border-t border-gray-100 text-center">
                                    <button type="submit"
                                            class="text-sm text-emerald-600 hover:text-emerald-700 font-semibold transition">
                                        View all results for "<span x-text="query"></span>"
                                        <i class="fas fa-arrow-right ml-1 text-xs"></i>
                                    </button>
                                </div>
                            </div>
                        </template>

                        {{-- No results --}}
                        <template x-if="!searchLoading && searchResults.length === 0 && query.trim().length >= 2">
                            <div class="p-6 text-center">
                                <i class="fas fa-search text-gray-300 text-3xl mb-2"></i>
                                <p class="text-sm text-gray-500">No publications found for "<span x-text="query" class="font-medium"></span>"</p>
                            </div>
                        </template>
                    </div>
                </div>

                {{-- Category filter — auto-submits on change --}}
                <div class="w-full md:w-56">
                    <select name="category"
                            x-model="category"
                            @change="onCategoryChange()"
                            class="w-full px-4 py-3 rounded-xl border-0 focus:ring-2 focus:ring-emerald-400 focus:outline-none text-sm shadow-sm bg-white">
                        <option value="">All Categories</option>
                        <option value="clinical" {{ ($filters['category'] ?? '') === 'clinical' ? 'selected' : '' }}>Clinical Research</option>
                        <option value="tech"     {{ ($filters['category'] ?? '') === 'tech'     ? 'selected' : '' }}>Technology &amp; Innovation</option>
                        <option value="social"   {{ ($filters['category'] ?? '') === 'social'   ? 'selected' : '' }}>Social Sciences</option>
                    </select>
                </div>

                {{-- Filter button (fallback / explicit submit) --}}
                <button type="submit"
                        class="px-6 py-3 bg-emerald-900 text-white rounded-xl hover:bg-emerald-950 transition font-semibold text-sm shadow-sm flex-shrink-0">
                    <i class="fas fa-filter mr-2"></i>Filter
                </button>

                {{-- Clear filters --}}
                @if(!empty($filters['q']) || !empty($filters['category']))
                <a href="{{ route('research.public.index') }}"
                   class="px-4 py-3 bg-white/20 text-white rounded-xl hover:bg-white/30 transition text-sm font-medium flex-shrink-0 flex items-center gap-1.5">
                    <i class="fas fa-times text-xs"></i> Clear
                </a>
                @endif
            </div>
        </form>
    </div>
</div>

{{-- ── 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-emerald-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">Research &amp; Innovation Centre</span>
            @if(!empty($filters['category']))
            <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
            <span class="text-gray-700 capitalize">
                {{ $catLabels[$filters['category']] ?? $filters['category'] }}
            </span>
            @endif
        </nav>
    </div>
</div>

{{-- ══════════════════════════════════════════════════════════════════════════
     ACTIVE FILTERS BADGE
══════════════════════════════════════════════════════════════════════════ --}}
@if(!empty($filters['q']) || !empty($filters['category']))
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-6">
    <div class="flex flex-wrap items-center gap-2">
        <span class="text-sm text-gray-500 font-medium">Active filters:</span>
        @if(!empty($filters['q']))
        <span class="inline-flex items-center gap-1.5 px-3 py-1 bg-emerald-100 text-emerald-800 text-xs font-semibold rounded-full">
            <i class="fas fa-search text-xs"></i>
            "{{ $filters['q'] }}"
            <a href="{{ route('research.public.index', array_filter(['category' => $filters['category'] ?? ''])) }}"
               class="ml-1 text-emerald-600 hover:text-emerald-800">
                <i class="fas fa-times"></i>
            </a>
        </span>
        @endif
        @if(!empty($filters['category']))
        <span class="inline-flex items-center gap-1.5 px-3 py-1 bg-blue-100 text-blue-800 text-xs font-semibold rounded-full">
            <i class="fas fa-tag text-xs"></i>
            {{ $catLabels[$filters['category']] ?? $filters['category'] }}
            <a href="{{ route('research.public.index', array_filter(['q' => $filters['q'] ?? ''])) }}"
               class="ml-1 text-blue-600 hover:text-blue-800">
                <i class="fas fa-times"></i>
            </a>
        </span>
        @endif
        <a href="{{ route('research.public.index') }}"
           class="text-xs text-gray-500 hover:text-red-600 transition font-medium">
            Clear all
        </a>
    </div>
</div>
@endif

{{-- ══════════════════════════════════════════════════════════════════════════
     FEATURED PUBLICATIONS
══════════════════════════════════════════════════════════════════════════ --}}
@if($featured->count() > 0 && empty($filters['q']) && empty($filters['category']))
<section class="py-12 bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between mb-8">
            <div>
                <h2 class="text-2xl font-bold text-gray-900 font-serif flex items-center gap-2">
                    <i class="fas fa-star text-yellow-500"></i>
                    Featured Research
                </h2>
                <p class="text-gray-500 mt-1 text-sm">Highlighted publications selected by our editorial team</p>
            </div>
            <a href="{{ route('research.public.featured') }}"
               class="text-emerald-600 hover:text-emerald-700 font-semibold text-sm flex items-center gap-1.5 transition">
                View all featured <i class="fas fa-arrow-right text-xs"></i>
            </a>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            @foreach($featured as $pub)
            <article class="bg-white rounded-2xl shadow-sm overflow-hidden hover:shadow-lg hover:-translate-y-0.5 transition-all duration-200 border border-gray-100">
                @if($pub->cover_image)
                <div class="h-48 overflow-hidden">
                    <img src="{{ Storage::url($pub->cover_image) }}"
                         alt="{{ $pub->title }}"
                         class="w-full h-full object-cover">
                </div>
                @else
                <div class="h-48 bg-gradient-to-br from-emerald-400 to-teal-500 flex items-center justify-center">
                    <i class="fas fa-book-open text-white text-5xl opacity-40"></i>
                </div>
                @endif

                <div class="p-6">
                    <div class="flex items-center gap-2 mb-3">
                        <span class="px-2 py-0.5 bg-emerald-100 text-emerald-700 text-xs font-semibold rounded-full uppercase">
                            {{ $pub->category_label }}
                        </span>
                        <span class="px-2 py-0.5 bg-yellow-100 text-yellow-700 text-xs font-semibold rounded-full">
                            <i class="fas fa-star mr-0.5"></i>Featured
                        </span>
                    </div>
                    <h3 class="text-base font-bold text-gray-900 font-serif mb-2 line-clamp-2 leading-snug">
                        <a href="{{ route('research.public.show', $pub) }}"
                           class="hover:text-emerald-600 transition">
                            {{ $pub->title }}
                        </a>
                    </h3>
                    <p class="text-gray-500 text-sm mb-4 line-clamp-2">
                        {{ Str::limit($pub->abstract, 120) }}
                    </p>
                    <div class="flex items-center justify-between text-xs text-gray-400">
                        <span class="flex items-center gap-1.5">
                            <i class="fas fa-user"></i>
                            {{ $pub->user->name ?? 'Unknown' }}
                        </span>
                        <span>{{ $pub->approved_at?->format('M d, Y') ?? 'N/A' }}</span>
                    </div>
                </div>
            </article>
            @endforeach
        </div>
    </div>
</section>
@endif

{{-- ══════════════════════════════════════════════════════════════════════════
     ALL PUBLICATIONS
══════════════════════════════════════════════════════════════════════════ --}}
<section class="py-12">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">

        {{-- Section header --}}
        <div class="flex items-center justify-between mb-8">
            <div>
                <h2 class="text-2xl font-bold text-gray-900 font-serif">
                    @if(!empty($filters['q']) || !empty($filters['category']))
                        Search Results
                    @else
                        All Publications
                    @endif
                </h2>
                <p class="text-gray-500 mt-1 text-sm">
                    {{ $publications->total() }} publication{{ $publications->total() !== 1 ? 's' : '' }} found
                </p>
            </div>
        </div>

        @if($publications->count() > 0)
        <div class="space-y-6">
            @foreach($publications as $pub)
            <article class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-md hover:-translate-y-0.5 transition-all duration-200">
                <div class="flex flex-col md:flex-row">

                    {{-- Cover --}}
                    <div class="w-full md:w-56 h-48 md:h-auto flex-shrink-0">
                        @if($pub->cover_image)
                        <img src="{{ Storage::url($pub->cover_image) }}"
                             alt="{{ $pub->title }}"
                             class="w-full h-full object-cover">
                        @else
                        <div class="w-full h-full bg-gradient-to-br from-gray-100 to-gray-200 flex items-center justify-center min-h-[160px]">
                            <i class="fas fa-file-alt text-gray-300 text-5xl"></i>
                        </div>
                        @endif
                    </div>

                    {{-- Content --}}
                    <div class="flex-1 p-6">
                        <div class="flex flex-wrap items-center gap-2 mb-3">
                            <span class="px-2 py-0.5 bg-emerald-100 text-emerald-700 text-xs font-semibold rounded-full uppercase">
                                {{ $pub->category_label }}
                            </span>
                            <span class="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs font-semibold rounded-full">
                                {{ $pub->author_badge }}
                            </span>
                            @if($pub->is_featured)
                            <span class="px-2 py-0.5 bg-yellow-100 text-yellow-700 text-xs font-semibold rounded-full">
                                <i class="fas fa-star mr-0.5"></i>Featured
                            </span>
                            @endif
                        </div>

                        <h3 class="text-xl font-bold text-gray-900 font-serif mb-2 leading-snug">
                            <a href="{{ route('research.public.show', $pub) }}"
                               class="hover:text-emerald-600 transition">
                                {{ $pub->title }}
                            </a>
                        </h3>

                        <p class="text-gray-600 text-sm mb-4 line-clamp-2 leading-relaxed">
                            {{ Str::limit($pub->abstract, 220) }}
                        </p>

                        <div class="flex flex-wrap items-center justify-between gap-4">
                            <div class="flex flex-wrap items-center gap-4 text-xs text-gray-400">
                                <span class="flex items-center gap-1.5">
                                    <i class="fas fa-user"></i>
                                    {{ $pub->user->name ?? 'Unknown' }}
                                </span>
                                <span class="flex items-center gap-1.5">
                                    <i class="fas fa-calendar-alt"></i>
                                    {{ $pub->approved_at?->format('M d, Y') ?? 'N/A' }}
                                </span>
                                @if($pub->files->where('is_public', true)->count() > 0)
                                <span class="flex items-center gap-1.5 text-emerald-600 font-medium">
                                    <i class="fas fa-download"></i>
                                    {{ $pub->files->where('is_public', true)->count() }} file(s) available
                                </span>
                                @else
                                <span class="flex items-center gap-1.5 text-amber-500">
                                    <i class="fas fa-clock"></i>
                                    Full paper pending
                                </span>
                                @endif
                            </div>

                            <a href="{{ route('research.public.show', $pub) }}"
                               class="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white text-sm font-semibold rounded-xl hover:bg-emerald-700 transition shadow-sm">
                                Read More <i class="fas fa-arrow-right text-xs"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </article>
            @endforeach
        </div>

        {{-- Pagination --}}
        <div class="mt-10">
            {{ $publications->withQueryString()->links() }}
        </div>

        @else
        {{-- Empty state --}}
        <div class="text-center py-20 bg-white rounded-2xl border border-gray-100 shadow-sm">
            <div class="w-20 h-20 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-5">
                <i class="fas fa-search text-gray-400 text-3xl"></i>
            </div>
            <h3 class="text-xl font-bold text-gray-700 mb-2">No publications found</h3>
            <p class="text-gray-500 text-sm mb-6 max-w-sm mx-auto">
                @if(!empty($filters['q']) || !empty($filters['category']))
                    Try adjusting your search terms or removing filters.
                @else
                    Be the first to submit a research publication to our centre!
                @endif
            </p>
            <div class="flex flex-wrap items-center justify-center gap-3">
                @if(!empty($filters['q']) || !empty($filters['category']))
                <a href="{{ route('research.public.index') }}"
                   class="inline-flex items-center gap-2 px-5 py-2.5 bg-gray-100 text-gray-700 rounded-xl font-semibold text-sm hover:bg-gray-200 transition">
                    <i class="fas fa-times"></i> Clear Filters
                </a>
                @endif
                <a href="{{ route('research.public.submit') }}"
                   class="inline-flex items-center gap-2 px-5 py-2.5 bg-emerald-600 text-white rounded-xl font-semibold text-sm hover:bg-emerald-700 transition shadow-sm">
                    <i class="fas fa-upload"></i> Submit Research
                </a>
            </div>
        </div>
        @endif

    </div>
</section>

{{-- ══════════════════════════════════════════════════════════════════════════
     CALL TO ACTION
══════════════════════════════════════════════════════════════════════════ --}}
<section class="py-16 bg-gradient-to-r from-emerald-700 to-teal-700">
    <div class="max-w-4xl mx-auto px-4 text-center">
        <h2 class="text-3xl font-bold text-white font-serif mb-4">
            Share Your Research
        </h2>
        <p class="text-emerald-100 text-lg mb-8 max-w-2xl mx-auto">
            Join our community of researchers and contribute to the advancement of health informatics.
            Submit your research papers, clinical studies, or innovative projects for peer review.
        </p>
        <div class="flex flex-wrap items-center justify-center gap-4">
            <a href="{{ route('research.public.submit') }}"
               class="inline-flex items-center gap-2 px-7 py-3.5 bg-white text-emerald-700 rounded-xl font-bold hover:bg-gray-100 transition shadow-md">
                <i class="fas fa-upload"></i>
                Submit Your Research
            </a>
            @guest
            <a href="{{ route('register.role.contributor') }}"
               class="inline-flex items-center gap-2 px-7 py-3.5 bg-emerald-900/50 text-white rounded-xl font-semibold hover:bg-emerald-900/70 transition border border-white/20">
                <i class="fas fa-user-plus"></i>
                Become a Contributor
            </a>
            @endguest
        </div>
    </div>
</section>

@endsection
