{{--
    Public Discussion Topic Page
    =============================
    Features:
    - Branded hero header with topic icon/color
    - Real-time search (Alpine.js, auto-submit on filter change)
    - RBAC guards on action buttons
    - Inward-styled divider
    - SEO structured data
    Layout: Site Layout (public)
--}}
<x-site-layout
    title="{{ $seoMetadata['title'] ?? $topic->name . ' - Discussions' }}"
    meta-description="{{ $seoMetadata['description'] ?? $topic->description }}"
>
    @if(isset($breadcrumbSchema))
        <script type="application/ld+json">{!! json_encode($breadcrumbSchema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) !!}</script>
    @endif

    {{-- ===== BRANDED HERO HEADER ===== --}}
    <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">
            <div class="absolute -top-20 -right-20 w-80 h-80 bg-white opacity-5 rounded-full"></div>
            <div class="absolute -bottom-16 -left-16 w-64 h-64 bg-white opacity-5 rounded-full"></div>
        </div>
        <div class="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">

            {{-- Breadcrumb inside hero --}}
            <nav class="flex items-center space-x-2 text-sm text-teal-300 mb-5" aria-label="Breadcrumb">
                <a href="{{ url('/') }}" class="hover:text-white transition flex items-center">
                    <i class="fas fa-home mr-1"></i>Home
                </a>
                <i class="fas fa-chevron-right text-teal-500 text-xs"></i>
                <a href="{{ route('public.discussions.index') }}" class="hover:text-white transition">Discussions</a>
                <i class="fas fa-chevron-right text-teal-500 text-xs"></i>
                <span class="text-white font-medium">{{ $topic->name }}</span>
            </nav>

            {{-- Topic header --}}
            <div class="flex items-start gap-5">
                <div class="flex-shrink-0 w-16 h-16 rounded-2xl bg-white bg-opacity-15 border border-white border-opacity-20 flex items-center justify-center shadow-lg">
                    <i class="fas {{ $topic->icon ?? 'fa-folder' }} text-white text-2xl"></i>
                </div>
                <div class="flex-1 min-w-0">
                    <h1 class="text-3xl md:text-4xl font-extrabold text-white tracking-tight">{{ $topic->name }}</h1>
                    @if($topic->description)
                        <p class="text-teal-100 mt-2 text-sm md:text-base leading-relaxed max-w-3xl">{{ $topic->description }}</p>
                    @endif

                    {{-- Inline stat tabs --}}
                    <div class="flex flex-wrap gap-2 mt-5">
                        <div class="flex items-center gap-2 bg-white bg-opacity-15 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>
                            <span class="text-lg font-extrabold leading-none">{{ number_format($topic->active_discussions_count ?? $discussions->total()) }}</span>
                            <span class="text-teal-200 text-xs">Discussions</span>
                        </div>
                        @auth
                            @can('create discussions')
                            <a href="{{ route('knowledge-sharing.discussions.create', ['topic_id' => $topic->id]) }}"
                               class="flex items-center gap-2 bg-white text-teal-700 rounded-xl px-4 py-2 text-sm font-semibold hover:bg-teal-50 transition shadow">
                                <i class="fas fa-plus text-sm"></i>Start Discussion
                            </a>
                            @endcan
                        @endauth
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Breadcrumb bar --}}
    <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>
                <a href="{{ route('public.discussions.index') }}" class="hover:text-teal-600 transition">Discussions</a>
                <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
                <span class="text-gray-900 font-medium">{{ $topic->name }}</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">

                {{-- Real-time search + filter bar --}}
                <div class="bg-theme-card rounded-2xl shadow-sm p-5 mb-6"
                     x-data="topicSearch()"
                     @click.outside="showDropdown = false">

                    {{-- Real-time search --}}
                    <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 in {{ $topic->name }}…"
                            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>

                        {{-- 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-72 overflow-y-auto divide-y divide-gray-50">
                                    <template x-for="r in results" :key="r.url">
                                        <a :href="r.url" class="flex items-start gap-3 px-4 py-3 hover:bg-teal-50 transition group">
                                            <div class="w-7 h-7 bg-teal-100 rounded-lg flex items-center justify-center flex-shrink-0 mt-0.5">
                                                <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="r.title"></p>
                                                <span class="text-xs text-gray-400">
                                                    <i class="fas fa-eye mr-1"></i><span x-text="r.view_count"></span>
                                                    &nbsp;·&nbsp;
                                                    <i class="fas fa-comment mr-1"></i><span x-text="r.reply_count"></span>
                                                </span>
                                            </div>
                                        </a>
                                    </template>
                                </div>
                            </template>
                            <template x-if="results.length === 0 && query.length >= 2 && !loading">
                                <div class="px-4 py-5 text-center text-sm text-gray-500">
                                    No results for "<span x-text="query" class="font-medium text-gray-700"></span>"
                                </div>
                            </template>
                        </div>
                    </div>

                    {{-- Sort filter (auto-submit) --}}
                    <form method="GET" id="topicFilterForm" class="flex gap-3">
                        <select name="sort"
                                onchange="document.getElementById('topicFilterForm').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">
                            <i class="fas fa-filter mr-1.5"></i>Filter
                        </button>
                    </form>
                </div>

                {{-- Inward divider --}}
                <div class="relative mb-5">
                    <div class="absolute inset-0 flex items-center">
                        <div class="w-full border-t-2 border-gray-200" 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">
                            {{ $discussions->total() }} Discussion{{ $discussions->total() !== 1 ? 's' : '' }}
                        </span>
                    </div>
                </div>

                {{-- 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">
                            <i class="fas fa-comments text-5xl text-gray-200 mb-4 block"></i>
                            <h3 class="text-base font-semibold text-theme-heading mb-2">No discussions in this topic</h3>
                            <p class="text-theme-body text-sm mb-5">
                                @if(request('q'))
                                    No discussions match your search.
                                @else
                                    Be the first to start a discussion in {{ $topic->name }}!
                                @endif
                            </p>
                            @auth
                                @can('create discussions')
                                <a href="{{ route('knowledge-sharing.discussions.create', ['topic_id' => $topic->id]) }}"
                                   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
                            @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">

                {{-- Other Topics --}}
                <div class="bg-theme-card rounded-2xl shadow-sm overflow-hidden">
                    <div class="bg-gradient-to-r from-teal-600 to-emerald-600 px-4 py-3">
                        <h3 class="text-sm font-bold text-white flex items-center gap-2">
                            <i class="fas fa-folder"></i>Other Topics
                        </h3>
                    </div>
                    <ul class="divide-y divide-gray-100">
                        @foreach($topics->where('id', '!=', $topic->id) as $otherTopic)
                            <li>
                                <a href="{{ route('public.discussions.topic', $otherTopic->slug) }}"
                                   class="flex items-center justify-between p-3 hover:bg-theme-body transition">
                                    <span class="flex items-center gap-2 text-sm text-theme-body">
                                        <i class="fas {{ $otherTopic->icon ?? 'fa-folder' }} {{ $otherTopic->color ? "text-{$otherTopic->color}-500" : 'text-gray-400' }} w-4 text-xs"></i>
                                        {{ $otherTopic->name }}
                                    </span>
                                    <span class="text-xs bg-gray-100 text-gray-500 px-2 py-0.5 rounded-full">
                                        {{ $otherTopic->active_discussions_count ?? 0 }}
                                    </span>
                                </a>
                            </li>
                        @endforeach
                    </ul>
                </div>

                {{-- Start Discussion CTA --}}
                @auth
                    @can('create discussions')
                    <div class="bg-gradient-to-br from-teal-600 to-emerald-700 rounded-2xl p-5 text-white text-center">
                        <i class="fas fa-plus-circle text-3xl mb-3 opacity-80"></i>
                        <h3 class="font-bold text-sm mb-2">Have something to share?</h3>
                        <p class="text-teal-100 text-xs mb-4">Start a discussion in this topic.</p>
                        <a href="{{ route('knowledge-sharing.discussions.create', ['topic_id' => $topic->id]) }}"
                           class="inline-flex items-center px-4 py-2 bg-white text-teal-700 text-sm font-semibold rounded-xl hover:bg-teal-50 transition">
                            <i class="fas fa-plus mr-2"></i>Start Discussion
                        </a>
                    </div>
                    @endcan
                @else
                    <div class="bg-theme-card rounded-2xl shadow-sm p-5 text-center">
                        <h3 class="font-semibold text-theme-heading text-sm mb-2">Join the Community</h3>
                        <p class="text-xs text-theme-body mb-4">Sign in to start discussions and reply.</p>
                        <a href="{{ route('register.role.contributor') }}"
                           class="inline-flex items-center px-4 py-2 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>Sign Up
                        </a>
                    </div>
                @endauth

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

    @push('scripts')
    <script>
    function topicSearch() {
        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)}&topic_id={{ $topic->id }}`,
                        { headers: { 'Accept': 'application/json' } }
                    );
                    const data = await res.json();
                    this.results = data.results ?? [];
                } catch(e) {
                    this.results = [];
                } finally {
                    this.loading = false;
                }
            }
        };
    }
    </script>
    @endpush

</x-site-layout>
