{{--
    Public Discussion Boards Landing Page
    ======================================
    Features:
    - 60-word pitch paragraph in hero
    - Inline responsive stat tab cards
    - Real-time Alpine.js search dropdown (2+ chars)
    - Real-time topic/sort filter (auto-submit on change)
    - Branded hero headers
    - Inward-styled divider
    - RBAC: @can/@auth guards on all action buttons
    Layout: Site Layout (public)
--}}
<x-site-layout
    title="{{ $seoMetadata['title'] ?? 'Community Discussion Boards' }}"
    meta-description="{{ $seoMetadata['description'] ?? '' }}"
>

{{-- ===== HERO ===== --}}
<div class="relative bg-gradient-to-br from-teal-700 via-green-700 to-emerald-800 overflow-hidden">
    <div class="absolute inset-0 pointer-events-none overflow-hidden">
        <div class="absolute -top-24 -right-24 w-96 h-96 bg-white opacity-5 rounded-full"></div>
        <div class="absolute -bottom-16 -left-16 w-72 h-72 bg-white opacity-5 rounded-full"></div>
        <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-teal-400 opacity-5 rounded-full blur-3xl"></div>
    </div>

    <div class="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">

        {{-- Title row --}}
        <div class="flex flex-col md:flex-row md:items-start md:justify-between mb-6">
            <div class="flex items-center mb-6 md:mb-0">
                <div class="w-16 h-16 bg-white bg-opacity-20 rounded-2xl flex items-center justify-center mr-5 shadow-lg flex-shrink-0">
                    <i class="fas fa-comments text-white text-3xl"></i>
                </div>
                <div>
                    <h1 class="text-3xl md:text-4xl font-extrabold text-white tracking-tight">
                        Community Discussions
                    </h1>
                    <p class="text-teal-100 mt-1 text-sm md:text-base">
                        Ask questions, share knowledge, and connect with the community
                    </p>
                </div>
            </div>
            @auth
                @can('create discussions')
                <a href="{{ route('knowledge-sharing.discussions.create') }}"
                   class="inline-flex items-center px-6 py-3 bg-white text-teal-700 font-semibold rounded-xl hover:bg-teal-50 transition shadow-lg text-sm">
                    <i class="fas fa-plus mr-2"></i>Start a Discussion
                </a>
                @endcan
            @else
                <div class="flex flex-col sm:flex-row gap-3">
                    <a href="{{ route('register.role.contributor') }}"
                       class="inline-flex items-center justify-center px-6 py-3 bg-white text-teal-700 font-bold rounded-xl hover:bg-teal-50 transition shadow-lg text-sm">
                        <i class="fas fa-user-plus mr-2"></i>Register to Post
                    </a>
                    <a href="{{ route('public.contributor.login') }}"
                       class="inline-flex items-center justify-center px-6 py-3 bg-transparent border-2 border-white text-white font-semibold rounded-xl hover:bg-white hover:bg-opacity-10 transition text-sm">
                        <i class="fas fa-sign-in-alt mr-2"></i>Sign In
                    </a>
                </div>
            @endauth
        </div>

        {{-- 60-word pitch paragraph --}}
        <div class="max-w-3xl mb-8">
            <p class="text-teal-100 text-sm md:text-base leading-relaxed">
                Join a vibrant community of health informatics professionals across South Sudan. Our discussion platform lets you ask questions, share expertise, and engage with peers on clinical practice, health policy, research, and training. Post your own questions, contribute answers, and learn from real-world experiences — because every voice strengthens our collective knowledge.
            </p>
        </div>

        {{-- Inline responsive stat tab cards --}}
        <div class="flex flex-wrap gap-2 mb-8">
            <div class="flex items-center gap-2 bg-white bg-opacity-15 backdrop-blur-sm border border-white border-opacity-20 rounded-xl px-4 py-2 text-white">
                <i class="fas fa-comments text-teal-200 text-sm"></i>
                <div>
                    <span class="text-lg font-extrabold leading-none">{{ number_format($statistics['total_discussions'] ?? 0) }}</span>
                    <span class="text-teal-200 text-xs ml-1">Discussions</span>
                </div>
            </div>
            <div class="flex items-center gap-2 bg-white bg-opacity-15 backdrop-blur-sm border border-white border-opacity-20 rounded-xl px-4 py-2 text-white">
                <i class="fas fa-layer-group text-emerald-200 text-sm"></i>
                <div>
                    <span class="text-lg font-extrabold leading-none">{{ number_format($statistics['total_topics'] ?? 0) }}</span>
                    <span class="text-emerald-200 text-xs ml-1">Topics</span>
                </div>
            </div>
            <div class="flex items-center gap-2 bg-white bg-opacity-15 backdrop-blur-sm border border-white border-opacity-20 rounded-xl px-4 py-2 text-white">
                <i class="fas fa-reply-all text-violet-200 text-sm"></i>
                <div>
                    <span class="text-lg font-extrabold leading-none">{{ number_format($statistics['total_replies'] ?? 0) }}</span>
                    <span class="text-violet-200 text-xs ml-1">Replies</span>
                </div>
            </div>
            <div class="flex items-center gap-2 bg-white bg-opacity-15 backdrop-blur-sm border border-white border-opacity-20 rounded-xl px-4 py-2 text-white">
                <i class="fas fa-users text-amber-200 text-sm"></i>
                <div>
                    <span class="text-lg font-extrabold leading-none">{{ number_format($statistics['total_contributors'] ?? 0) }}</span>
                    <span class="text-amber-200 text-xs ml-1">Contributors</span>
                </div>
            </div>
            <div class="flex items-center gap-2 bg-white bg-opacity-15 backdrop-blur-sm border border-white border-opacity-20 rounded-xl px-4 py-2 text-white">
                <i class="fas fa-arrow-trend-up text-cyan-200 text-sm"></i>
                <div>
                    <span class="text-lg font-extrabold leading-none">{{ number_format($statistics['recent_discussions'] ?? 0) }}</span>
                    <span class="text-cyan-200 text-xs ml-1">This Week</span>
                </div>
            </div>
        </div>

    </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-teal-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">Community Discussions</span>
        </nav>
    </div>
</div>

{{-- ===== MAIN CONTENT ===== --}}
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">

        {{-- Main Discussion List --}}
        <div class="lg:col-span-3">

            {{-- Search & Filter Bar with real-time Alpine.js --}}
            <div class="bg-theme-card rounded-2xl shadow-sm p-5 mb-6"
                 x-data="discussionSearch()"
                 @click.outside="showDropdown = false">

                {{-- Real-time search input --}}
                <div class="relative mb-4">
                    <i class="fas fa-search absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-sm z-10"></i>
                    <input
                        type="text"
                        x-model="query"
                        @input.debounce.300ms="search()"
                        @focus="query.length >= 2 && (showDropdown = true)"
                        @keydown.escape="showDropdown = false"
                        placeholder="Search discussions in real-time…"
                        class="w-full pl-11 pr-10 py-3 border border-gray-200 rounded-xl bg-theme-body text-theme-body focus:ring-2 focus:ring-teal-500 focus:border-transparent text-sm"
                    >
                    <div x-show="loading" class="absolute right-4 top-1/2 -translate-y-1/2">
                        <i class="fas fa-spinner fa-spin text-teal-500 text-sm"></i>
                    </div>

                    {{-- Real-time search dropdown --}}
                    <div
                        x-show="showDropdown"
                        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"
                        class="absolute z-50 w-full bg-white rounded-xl shadow-2xl border border-gray-100 mt-2 overflow-hidden"
                        style="display:none"
                    >
                        <template x-if="results.length > 0">
                            <div class="max-h-80 overflow-y-auto divide-y divide-gray-50">
                                <template x-for="result in results" :key="result.url">
                                    <a :href="result.url"
                                       class="flex items-start gap-3 px-4 py-3 hover:bg-teal-50 transition group">
                                        <div class="w-8 h-8 bg-teal-100 rounded-lg flex items-center justify-center flex-shrink-0 mt-0.5 group-hover:bg-teal-200 transition">
                                            <i class="fas fa-comments text-teal-600 text-xs"></i>
                                        </div>
                                        <div class="flex-1 min-w-0">
                                            <p class="text-sm font-semibold text-gray-800 truncate" x-text="result.title"></p>
                                            <div class="flex items-center gap-3 mt-0.5">
                                                <span class="text-xs text-teal-600 font-medium" x-text="result.topic"></span>
                                                <span class="text-xs text-gray-400">
                                                    <i class="fas fa-eye mr-1"></i><span x-text="result.view_count"></span>
                                                    &nbsp;·&nbsp;
                                                    <i class="fas fa-comment mr-1"></i><span x-text="result.reply_count"></span> replies
                                                </span>
                                            </div>
                                        </div>
                                        <i class="fas fa-arrow-right text-gray-300 group-hover:text-teal-500 transition text-xs mt-1 flex-shrink-0"></i>
                                    </a>
                                </template>
                            </div>
                        </template>
                        <template x-if="results.length === 0 && query.length >= 2 && !loading">
                            <div class="px-4 py-6 text-center">
                                <i class="fas fa-search text-gray-300 text-2xl mb-2 block"></i>
                                <p class="text-sm text-gray-500">No results for "<span x-text="query" class="font-medium text-gray-700"></span>"</p>
                            </div>
                        </template>
                    </div>
                </div>

                {{-- Real-time filter form (auto-submits on change) --}}
                <form method="GET" action="{{ route('public.discussions.index') }}" id="filterForm" class="flex flex-col sm:flex-row gap-3">
                    <select name="topic"
                            onchange="document.getElementById('filterForm').submit()"
                            class="flex-1 px-4 py-2.5 border border-gray-200 rounded-xl bg-theme-body text-theme-body text-sm focus:ring-2 focus:ring-teal-500">
                        <option value="">All Topics</option>
                        @foreach($topics as $topic)
                            <option value="{{ $topic->id }}" {{ request('topic') == $topic->id ? 'selected' : '' }}>
                                {{ $topic->name }}
                            </option>
                        @endforeach
                    </select>
                    <select name="sort"
                            onchange="document.getElementById('filterForm').submit()"
                            class="flex-1 px-4 py-2.5 border border-gray-200 rounded-xl bg-theme-body text-theme-body text-sm focus:ring-2 focus:ring-teal-500">
                        <option value="latest" {{ request('sort', 'latest') === 'latest' ? 'selected' : '' }}>Latest</option>
                        <option value="popular" {{ request('sort') === 'popular' ? 'selected' : '' }}>Most Popular</option>
                        <option value="active" {{ request('sort') === 'active' ? 'selected' : '' }}>Most Active</option>
                    </select>
                    <button type="submit"
                            class="px-5 py-2.5 bg-teal-600 text-white text-sm font-semibold rounded-xl hover:bg-teal-700 transition whitespace-nowrap">
                        <i class="fas fa-filter mr-1.5"></i>Filter
                    </button>
                </form>
            </div>

            {{-- Featured Discussions --}}
            @if($featuredDiscussions->isNotEmpty() && !request()->has('q'))
                <div class="mb-6">
                    <h2 class="text-base font-bold text-theme-heading mb-3 flex items-center">
                        <span class="w-6 h-6 bg-yellow-100 rounded-lg flex items-center justify-center mr-2">
                            <i class="fas fa-star text-yellow-500 text-xs"></i>
                        </span>
                        Featured Discussions
                    </h2>
                    <div class="grid gap-4">
                        @foreach($featuredDiscussions as $discussion)
                            @include('public.discussions.partials.discussion-card', ['discussion' => $discussion, 'featured' => true])
                        @endforeach
                    </div>
                </div>

                {{-- Inward-styled divider --}}
                <div class="relative my-6">
                    <div class="absolute inset-0 flex items-center">
                        <div class="w-full border-t-2 border-gray-200 shadow-inner" style="box-shadow: inset 0 2px 4px rgba(0,0,0,0.06);"></div>
                    </div>
                    <div class="relative flex justify-center">
                        <span class="bg-gray-50 px-4 py-1 text-xs font-semibold text-gray-400 uppercase tracking-widest rounded-full border border-gray-200 shadow-inner">
                            All Discussions
                        </span>
                    </div>
                </div>
            @endif

            {{-- Discussion List --}}
            <div class="space-y-4">
                @forelse($discussions as $discussion)
                    @include('public.discussions.partials.discussion-card', ['discussion' => $discussion])
                @empty
                    <div class="bg-theme-card rounded-2xl shadow-sm p-10 text-center">
                        <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-comments text-gray-300 text-2xl"></i>
                        </div>
                        <h3 class="text-lg font-semibold text-theme-heading mb-2">No discussions found</h3>
                        <p class="text-theme-body text-sm mb-5">
                            @if(request('q'))
                                No discussions match your search. Try different keywords.
                            @else
                                Be the first to start a discussion in this community!
                            @endif
                        </p>
                        @auth
                            @can('create discussions')
                            <a href="{{ route('knowledge-sharing.discussions.create') }}"
                               class="inline-flex items-center px-5 py-2.5 bg-teal-600 text-white text-sm font-semibold rounded-xl hover:bg-teal-700 transition">
                                <i class="fas fa-plus mr-2"></i>Start a Discussion
                            </a>
                            @endcan
                        @else
                            <a href="{{ route('register.role.contributor') }}"
                               class="inline-flex items-center px-5 py-2.5 bg-teal-600 text-white text-sm font-semibold rounded-xl hover:bg-teal-700 transition">
                                <i class="fas fa-user-plus mr-2"></i>Register to Post
                            </a>
                        @endauth
                    </div>
                @endforelse
            </div>

            @if($discussions->hasPages())
                <div class="mt-6">{{ $discussions->links() }}</div>
            @endif
        </div>

        {{-- Sidebar --}}
        <div class="lg:col-span-1 space-y-5">

            {{-- Guest CTA --}}
            @guest
                <div class="bg-gradient-to-br from-teal-600 to-emerald-700 rounded-2xl p-6 text-white shadow-lg">
                    <div class="text-center">
                        <div class="w-14 h-14 bg-white bg-opacity-20 rounded-2xl flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-user-plus text-2xl"></i>
                        </div>
                        <h3 class="text-base font-bold mb-2">Join the Community</h3>
                        <p class="text-teal-100 text-xs mb-4 leading-relaxed">
                            Create your contributor account and start sharing your knowledge today!
                        </p>
                        <a href="{{ route('register.role.contributor') }}"
                           class="block w-full py-2.5 bg-white text-teal-700 text-sm font-bold rounded-xl hover:bg-teal-50 transition mb-3">
                            Register to Post
                        </a>
                        <p class="text-xs text-teal-200">
                            Already have an account?
                            <a href="{{ route('public.contributor.login') }}" class="underline hover:text-white font-medium">Sign in</a>
                        </p>
                    </div>
                </div>
            @endguest

            {{-- Auth Quick Actions --}}
            @auth
                <div class="bg-theme-card rounded-2xl shadow-sm p-4">
                    <h3 class="text-sm font-bold text-theme-heading mb-3 flex items-center">
                        <i class="fas fa-bolt text-yellow-500 mr-2"></i>Quick Actions
                    </h3>
                    <div class="space-y-2">
                        @can('create discussions')
                        <a href="{{ route('knowledge-sharing.discussions.create') }}"
                           class="flex items-center p-3 rounded-xl bg-teal-50 text-teal-700 hover:bg-teal-100 transition text-sm font-medium">
                            <i class="fas fa-plus mr-3 text-teal-500"></i>Start a Discussion
                        </a>
                        @endcan
                        @if(auth()->user()->hasRole('Contributor') && !auth()->user()->hasAnyRole(['Super Manager', 'Manager']))
                            <a href="{{ route('contributor.dashboard') }}"
                               class="flex items-center p-3 rounded-xl hover:bg-theme-body transition text-theme-body text-sm">
                                <i class="fas fa-tachometer-alt mr-3 text-gray-400"></i>My Dashboard
                            </a>
                        @endif
                        @can('view discussions')
                        <a href="{{ route('knowledge-sharing.discussions.index') }}"
                           class="flex items-center p-3 rounded-xl hover:bg-theme-body transition text-theme-body text-sm">
                            <i class="fas fa-cog mr-3 text-gray-400"></i>Manage Discussions
                        </a>
                        @endcan
                    </div>
                </div>
            @endauth

            {{-- Browse Topics --}}
            <div class="bg-theme-card rounded-2xl shadow-sm p-4">
                <h3 class="text-sm font-bold text-theme-heading mb-3 flex items-center">
                    <i class="fas fa-layer-group text-teal-600 mr-2"></i>Browse Topics
                </h3>
                <ul class="space-y-1">
                    @foreach($topics as $topic)
                        <li>
                            <a href="{{ route('public.discussions.topic', $topic->slug) }}"
                               class="flex items-center justify-between px-3 py-2 rounded-xl hover:bg-teal-50 transition text-sm {{ request('topic') == $topic->id ? 'bg-teal-50 text-teal-700 font-medium' : 'text-theme-body' }}">
                                <span class="flex items-center">
                                    <i class="fas {{ $topic->icon ?? 'fa-folder' }} {{ $topic->color ? "text-{$topic->color}-500" : 'text-gray-400' }} mr-2 text-xs w-4"></i>
                                    {{ $topic->name }}
                                </span>
                                <span class="text-xs bg-gray-100 text-gray-500 px-2 py-0.5 rounded-full">
                                    {{ $topic->discussions_count ?? 0 }}
                                </span>
                            </a>
                        </li>
                    @endforeach
                </ul>
            </div>

            {{-- Popular Discussions --}}
            <div class="bg-theme-card rounded-2xl shadow-sm p-4">
                <h3 class="text-sm font-bold text-theme-heading mb-3 flex items-center">
                    <i class="fas fa-fire text-orange-500 mr-2"></i>Popular Discussions
                </h3>
                <ul class="space-y-3">
                    @foreach($popularDiscussions as $pop)
                        <li>
                            <a href="{{ route('public.discussions.show', $pop->slug) }}"
                               class="block p-2 rounded-xl hover:bg-theme-body transition">
                                <h4 class="text-xs font-semibold text-theme-heading line-clamp-2 mb-1">{{ $pop->title }}</h4>
                                <div class="flex items-center gap-3 text-xs text-gray-400">
                                    <span><i class="fas fa-eye mr-1"></i>{{ number_format($pop->view_count) }}</span>
                                    <span><i class="fas fa-comment mr-1"></i>{{ $pop->reply_count }}</span>
                                </div>
                            </a>
                        </li>
                    @endforeach
                </ul>
            </div>

            {{-- Recent Activity --}}
            <div class="bg-theme-card rounded-2xl shadow-sm p-4">
                <h3 class="text-sm font-bold text-theme-heading mb-3 flex items-center">
                    <i class="fas fa-clock text-blue-500 mr-2"></i>Recent Activity
                </h3>
                <div class="space-y-3">
                    @foreach(\App\Models\Discussion::with('user')->published()->latest()->limit(5)->get() as $recent)
                        <div class="flex items-start gap-2">
                            <img src="{{ $recent->user->avatar ?? 'https://ui-avatars.com/api/?name=' . urlencode($recent->user->name) . '&size=32' }}"
                                 alt="{{ $recent->user->name }}"
                                 class="w-7 h-7 rounded-full flex-shrink-0">
                            <div class="min-w-0">
                                <p class="text-xs text-theme-body leading-snug">
                                    <span class="font-semibold text-theme-heading">{{ $recent->user->name }}</span>
                                    started a discussion
                                </p>
                                <p class="text-xs text-gray-400 mt-0.5">{{ $recent->created_at->diffForHumans() }}</p>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>

        </div>
    </div>
</div>

@push('scripts')
<script>
function discussionSearch() {
    return {
        query: '{{ request('q', '') }}',
        results: [],
        showDropdown: false,
        loading: false,
        async search() {
            if (this.query.length < 2) {
                this.results = [];
                this.showDropdown = false;
                return;
            }
            this.loading = true;
            this.showDropdown = true;
            try {
                const res = await fetch(
                    `{{ route('public.discussions.ajax-search') }}?q=${encodeURIComponent(this.query)}`,
                    { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } }
                );
                const data = await res.json();
                this.results = data.results ?? [];
            } catch (e) {
                this.results = [];
            } finally {
                this.loading = false;
            }
        }
    };
}
</script>
@endpush

</x-site-layout>
