<x-app-layout>

    <x-module-hero
        title="Discussions"
        description="Manage community discussions"
        icon="fa-comments">

        <x-slot name="tabs">
            @can('view discussion topics')
            <a href="{{ route('knowledge-sharing.discussions.topics.index') }}"
               class="module-hero-tab {{ request()->routeIs('knowledge-sharing.discussions.topics.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-lightbulb text-sm"></i> Discussion Topics
            </a>
            @endcan
            @can('view discussions')
            <a href="{{ route('knowledge-sharing.discussions.index') }}"
               class="module-hero-tab {{ request()->routeIs('knowledge-sharing.discussions.index') || (request()->routeIs('knowledge-sharing.discussions.*') && !request()->routeIs('knowledge-sharing.discussions.topics.*') && !request()->routeIs('knowledge-sharing.discussions.replies.*')) ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-comments text-sm"></i> Discussions
            </a>
            @endcan
            @if(Route::has('knowledge-sharing.discussions.replies.index'))
            @can('view discussion replies')
            <a href="{{ route('knowledge-sharing.discussions.replies.index') }}"
               class="module-hero-tab {{ request()->routeIs('knowledge-sharing.discussions.replies.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-reply-all text-sm"></i> All Replies
            </a>
            @endcan
            @endif
            @can('manage knowledge base categories')
            <a href="{{ route('knowledge-sharing.knowledge-base.categories.index') }}"
               class="module-hero-tab {{ request()->routeIs('knowledge-sharing.knowledge-base.categories.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-book-open text-sm"></i> KB Categories
            </a>
            @endcan
            @can('view knowledge base questions')
            <a href="{{ route('knowledge-sharing.knowledge-base.index') }}"
               class="module-hero-tab {{ request()->routeIs('knowledge-sharing.knowledge-base.index') || (request()->routeIs('knowledge-sharing.knowledge-base.*') && !request()->routeIs('knowledge-sharing.knowledge-base.categories.*')) ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-circle-question text-sm"></i> Knowledge Base Q&amp;A
            </a>
            @endcan
            @hasRole('Contributor')
            <a href="{{ route('contributor.dashboard') }}"
               class="module-hero-tab {{ request()->routeIs('contributor.dashboard') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }} inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-pen-nib text-sm"></i> Contributor Dashboard
            </a>
            @endhasRole
        </x-slot>

        @can('create discussions')
        <x-slot name="actions">
            <a href="{{ route('knowledge-sharing.discussions.create') }}"
               class="inline-flex items-center gap-2 px-4 py-2 bg-white text-[#1e293b] text-sm font-semibold rounded-lg hover:bg-green-50 transition-colors">
                <i class="fas fa-plus"></i> New Discussion
            </a>
        </x-slot>
        @endcan

    </x-module-hero>

    <div class="p-6">

        @if(session('success'))
            <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center gap-2">
                <i class="fas fa-check-circle"></i> {{ session('success') }}
            </div>
        @endif
        @if(session('error'))
            <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg flex items-center gap-2">
                <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
            </div>
        @endif

        {{-- Statistics Cards (Phase 12.1) --}}
        @if(isset($statistics))
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-4 flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-teal-100 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-comments text-teal-600"></i>
                </div>
                <div>
                    <p class="text-2xl font-bold text-gray-800">{{ number_format($statistics['total_discussions'] ?? 0) }}</p>
                    <p class="text-xs text-gray-500">Total Discussions</p>
                </div>
            </div>
            <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-4 flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-green-100 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-check-circle text-green-600"></i>
                </div>
                <div>
                    <p class="text-2xl font-bold text-gray-800">{{ number_format($statistics['published_discussions'] ?? 0) }}</p>
                    <p class="text-xs text-gray-500">Published</p>
                </div>
            </div>
            <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-4 flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-purple-100 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-reply-all text-purple-600"></i>
                </div>
                <div>
                    <p class="text-2xl font-bold text-gray-800">{{ number_format($statistics['total_replies'] ?? 0) }}</p>
                    <p class="text-xs text-gray-500">Total Replies</p>
                </div>
            </div>
            <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-4 flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-amber-100 flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-arrow-trend-up text-amber-600"></i>
                </div>
                <div>
                    <p class="text-2xl font-bold text-gray-800">{{ number_format($statistics['recent_discussions'] ?? 0) }}</p>
                    <p class="text-xs text-gray-500">This Week</p>
                </div>
            </div>
        </div>
        @endif

        <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">

            {{-- Filter Form --}}
            <div class="p-4 bg-gray-50 border-b border-gray-200">
                <form method="GET" class="flex flex-col sm:flex-row flex-wrap gap-3">
                    <div class="flex-1 min-w-48 relative">
                        <input type="text" name="search" value="{{ request('search') }}"
                               placeholder="Search discussions…"
                               class="w-full pl-9 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-transparent">
                        <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                    </div>
                    <select name="topic_id" class="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                        <option value="">All Topics</option>
                        @foreach($topics as $topic)
                            <option value="{{ $topic->id }}" {{ request('topic_id') == $topic->id ? 'selected' : '' }}>{{ $topic->name }}</option>
                        @endforeach
                    </select>
                    <select name="status" class="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500">
                        <option value="">All Status</option>
                        <option value="published" {{ request('status') === 'published' ? 'selected' : '' }}>Published</option>
                        <option value="draft" {{ request('status') === 'draft' ? 'selected' : '' }}>Draft</option>
                        <option value="pending_review" {{ request('status') === 'pending_review' ? 'selected' : '' }}>Pending Review</option>
                        <option value="archived" {{ request('status') === 'archived' ? 'selected' : '' }}>Archived</option>
                    </select>
                    <label class="inline-flex items-center gap-2 px-3 py-2 border border-gray-300 rounded-lg bg-white text-sm cursor-pointer">
                        <input type="checkbox" name="inactive" value="1" {{ request('inactive') ? 'checked' : '' }} class="rounded">
                        Include Inactive
                    </label>
                    <button type="submit" class="px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700 transition-colors">
                        <i class="fas fa-filter mr-1"></i> Filter
                    </button>
                </form>
            </div>

            {{-- Bulk Actions Form --}}
            @can('delete discussions')
            <form id="bulkForm" method="POST" action="{{ route('knowledge-sharing.discussions.bulk-delete') }}">
                @csrf
            @endcan

            <div class="overflow-x-auto">
                <table class="w-full table-zebra">
                    <thead>
                        <tr>
                            @can('delete discussions')
                            <th class="th-col-1 px-4 py-3 w-10 text-center">
                                <input type="checkbox" class="rounded border-gray-300" onclick="toggleAll(this)">
                            </th>
                            @endcan
                            <th class="th-col-1 px-4 py-3 text-left">Title</th>
                            <th class="th-col-2 px-4 py-3 text-left">Topic</th>
                            <th class="th-col-3 px-4 py-3 text-left">Author</th>
                            <th class="th-col-4 px-4 py-3 text-center">Status</th>
                            <th class="th-col-5 px-4 py-3 text-center">Stats</th>
                            <th class="th-col-6 px-4 py-3 text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($discussions as $discussion)
                            <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0 {{ $discussion->is_active ? '' : 'opacity-60' }}">
                                @can('delete discussions')
                                <td class="px-4 py-3 text-center">
                                    <input type="checkbox" name="discussion_ids[]" value="{{ $discussion->id }}" class="rounded border-gray-300">
                                </td>
                                @endcan
                                <td class="px-4 py-3">
                                    <div class="flex items-center gap-2">
                                        @if($discussion->is_featured)
                                            <i class="fas fa-star text-yellow-500 text-xs" title="Featured"></i>
                                        @endif
                                        @if($discussion->is_pinned)
                                            <i class="fas fa-thumbtack text-purple-500 text-xs" title="Pinned"></i>
                                        @endif
                                        <div>
                                            <a href="{{ route('knowledge-sharing.discussions.show', $discussion) }}"
                                               class="font-medium text-gray-900 hover:text-green-600 transition-colors">
                                                {{ \Illuminate\Support\Str::limit($discussion->title, 50) }}
                                            </a>
                                            <p class="text-xs text-gray-400 mt-0.5">{{ $discussion->created_at->diffForHumans() }}</p>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 py-3">
                                    @if($discussion->topic)
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                            {{ $discussion->topic->name }}
                                        </span>
                                    @else
                                        <span class="text-gray-400 text-xs">No topic</span>
                                    @endif
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex items-center gap-2">
                                        <div class="w-6 h-6 rounded-full bg-gray-200 flex items-center justify-center text-xs font-semibold text-gray-600 flex-shrink-0">
                                            {{ strtoupper(substr($discussion->user->name, 0, 1)) }}
                                        </div>
                                        <span class="text-sm text-gray-700">{{ $discussion->user->name }}</span>
                                    </div>
                                </td>
                                <td class="px-4 py-3 text-center">
                                    @php
                                        $sc = ['published'=>'bg-green-100 text-green-800','draft'=>'bg-gray-100 text-gray-700','pending_review'=>'bg-yellow-100 text-yellow-800','archived'=>'bg-red-100 text-red-800'];
                                    @endphp
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $sc[$discussion->status] ?? 'bg-gray-100 text-gray-700' }}">
                                        {{ ucfirst(str_replace('_', ' ', $discussion->status)) }}
                                    </span>
                                </td>
                                <td class="px-4 py-3 text-center">
                                    <div class="flex items-center justify-center gap-3 text-xs text-gray-500">
                                        <span title="Views"><i class="fas fa-eye mr-1"></i>{{ number_format($discussion->view_count) }}</span>
                                        <span title="Replies"><i class="fas fa-comment mr-1"></i>{{ $discussion->active_replies_count ?? 0 }}</span>
                                    </div>
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex items-center justify-center gap-1">
                                        <a href="{{ route('knowledge-sharing.discussions.show', $discussion) }}" class="btn-action-view">
                                            <i class="fas fa-eye"></i> View
                                        </a>
                                        @can('edit discussions')
                                        <a href="{{ route('knowledge-sharing.discussions.edit', $discussion) }}" class="btn-action-edit">
                                            <i class="fas fa-edit"></i> Edit
                                        </a>
                                        @endcan
                                        @can('feature discussions')
                                        <form action="{{ route('knowledge-sharing.discussions.toggle-featured', $discussion) }}" method="POST" class="inline">
                                            @csrf
                                            <button type="submit"
                                                    class="{{ $discussion->is_featured ? 'btn-action-reject' : 'btn-action-approve' }}"
                                                    title="{{ $discussion->is_featured ? 'Unfeature' : 'Feature' }}">
                                                <i class="fas fa-star"></i>
                                            </button>
                                        </form>
                                        @endcan
                                        @can('delete discussions')
                                        <form action="{{ route('knowledge-sharing.discussions.destroy', $discussion) }}" method="POST" class="inline"
                                              onsubmit="return confirm('Delete this discussion?')">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="btn-action-delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </form>
                                        @endcan
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                                <td colspan="7" class="px-4 py-12 text-center">
                                    <i class="fas fa-comments text-4xl text-gray-300 mb-3 block"></i>
                                    <p class="text-gray-500 mb-4">No discussions found.</p>
                                    @can('create discussions')
                                    <a href="{{ route('knowledge-sharing.discussions.create') }}"
                                       class="inline-flex items-center gap-2 px-4 py-2 bg-green-600 text-white text-sm rounded-lg hover:bg-green-700">
                                        <i class="fas fa-plus"></i> Create Discussion
                                    </a>
                                    @endcan
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            @can('delete discussions')
            </form>
            @endcan

            @if($discussions->hasPages())
                <div class="px-4 py-3 border-t border-gray-200">
                    {{ $discussions->links() }}
                </div>
            @endif

        </div>

        {{-- Bulk delete bar --}}
        @can('delete discussions')
        <div id="bulkBar" class="hidden fixed bottom-4 left-1/2 -translate-x-1/2 bg-gray-900 text-white px-6 py-3 rounded-xl shadow-xl flex items-center gap-4 z-50">
            <span id="bulkCount" class="text-sm">0 selected</span>
            <button onclick="document.getElementById('bulkForm').submit()"
                    class="px-4 py-1.5 bg-red-600 hover:bg-red-700 text-white text-sm rounded-lg transition-colors">
                <i class="fas fa-trash mr-1"></i> Delete Selected
            </button>
            <button onclick="clearSelection()" class="text-gray-400 hover:text-white text-sm">Cancel</button>
        </div>
        @endcan

    </div>

    @push('scripts')
    <script>
        function toggleAll(checkbox) {
            document.querySelectorAll('input[name="discussion_ids[]"]').forEach(cb => cb.checked = checkbox.checked);
            updateBulkBar();
        }
        function updateBulkBar() {
            const checked = document.querySelectorAll('input[name="discussion_ids[]"]:checked').length;
            const bar = document.getElementById('bulkBar');
            if (bar) {
                bar.classList.toggle('hidden', checked === 0);
                document.getElementById('bulkCount').textContent = checked + ' selected';
            }
        }
        function clearSelection() {
            document.querySelectorAll('input[name="discussion_ids[]"]').forEach(cb => cb.checked = false);
            document.querySelector('input[onclick="toggleAll(this)"]').checked = false;
            updateBulkBar();
        }
        document.querySelectorAll('input[name="discussion_ids[]"]').forEach(cb => {
            cb.addEventListener('change', updateBulkBar);
        });
    </script>
    @endpush

</x-app-layout>
