{{--
    Public Knowledge Base Question Show Page
    ==========================================
    Features:
    - Branded hero header with category badge & difficulty
    - Real-time view/answer counts (Alpine.js)
    - RBAC: @can/@auth guards on all action buttons
    - Accepted answer highlighting
    - Helpful vote AJAX
    - Inward-styled divider
    - SEO structured data
    Layout: Site Layout (public)
--}}
<x-site-layout
    title="{{ $seoMetadata['title'] ?? $question->title }}"
    meta-description="{{ $seoMetadata['description'] ?? Str::limit(strip_tags($question->content), 160) }}"
>
    @if(isset($schemaData))
        <script type="application/ld+json">{!! json_encode($schemaData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) !!}</script>
    @endif
    @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-slate-800 via-blue-900 to-indigo-900 overflow-hidden">
        <div class="absolute inset-0 pointer-events-none">
            <div class="absolute -top-16 -right-16 w-64 h-64 bg-blue-500 opacity-10 rounded-full blur-3xl"></div>
            <div class="absolute -bottom-12 -left-12 w-48 h-48 bg-indigo-500 opacity-10 rounded-full blur-3xl"></div>
        </div>
        <div class="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

            {{-- Category + difficulty badges --}}
            <div class="mb-3 flex flex-wrap gap-2">
                @if($question->category)
                    <a href="{{ route('public.knowledge-base.category', $question->category->slug) }}"
                       class="inline-flex items-center gap-1.5 px-3 py-1 bg-white bg-opacity-20 text-white text-xs font-semibold rounded-full hover:bg-opacity-30 transition">
                        <i class="fas {{ $question->category->icon ?? 'fa-folder' }} text-xs"></i>
                        {{ $question->category->name }}
                    </a>
                @endif
                @if($question->difficulty)
                    @php
                        $diffColors = ['beginner' => 'bg-green-400 text-green-900', 'intermediate' => 'bg-yellow-400 text-yellow-900', 'advanced' => 'bg-red-400 text-red-900'];
                    @endphp
                    <span class="inline-flex items-center gap-1 px-3 py-1 {{ $diffColors[$question->difficulty] ?? 'bg-gray-400 text-gray-900' }} text-xs font-semibold rounded-full">
                        <i class="fas fa-signal text-xs"></i>{{ ucfirst($question->difficulty) }}
                    </span>
                @endif
                @if($question->is_featured)
                    <span class="inline-flex items-center gap-1 px-3 py-1 bg-yellow-400 text-yellow-900 text-xs font-semibold rounded-full">
                        <i class="fas fa-star text-xs"></i>Featured
                    </span>
                @endif
                @if($question->has_accepted_answer)
                    <span class="inline-flex items-center gap-1 px-3 py-1 bg-green-400 text-green-900 text-xs font-semibold rounded-full">
                        <i class="fas fa-check-circle text-xs"></i>Answered
                    </span>
                @endif
            </div>

            {{-- Title --}}
            <h1 class="text-2xl md:text-3xl font-extrabold text-white mb-4 leading-tight">{{ $question->title }}</h1>

            {{-- Meta row --}}
            <div class="flex flex-wrap items-center gap-3 text-blue-200 text-sm mb-4">
                <div class="flex items-center gap-2">
                    <img src="{{ $question->user->avatar ?? 'https://ui-avatars.com/api/?name=' . urlencode($question->user->name) . '&size=32&background=1e40af&color=fff' }}"
                         alt="{{ $question->user->name }}"
                         class="w-7 h-7 rounded-full border-2 border-white border-opacity-30">
                    <span class="font-medium text-white">{{ $question->user->name }}</span>
                </div>
                <span class="text-blue-400">·</span>
                <span>{{ $question->created_at->format('M d, Y') }}</span>
                <span class="text-blue-400">·</span>
                <span>{{ $question->reading_time }} min read</span>
            </div>

            {{-- Real-time stats bar --}}
            <div class="flex flex-wrap gap-3"
                 x-data="{ viewCount: {{ $question->view_count }}, answerCount: {{ $answers->count() }} }">
                <span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-white bg-opacity-15 text-white text-sm font-medium">
                    <i class="fas fa-eye text-blue-200 text-xs"></i>
                    <span x-text="viewCount.toLocaleString()">{{ number_format($question->view_count) }}</span>
                    <span class="text-blue-200 text-xs">views</span>
                </span>
                <span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-white bg-opacity-15 text-white text-sm font-medium">
                    <i class="fas fa-lightbulb text-emerald-200 text-xs"></i>
                    <span x-text="answerCount">{{ $answers->count() }}</span>
                    <span class="text-emerald-200 text-xs">answers</span>
                </span>
                <span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-white bg-opacity-15 text-white text-sm font-medium">
                    <i class="fas fa-thumbs-up text-orange-200 text-xs"></i>
                    <span id="helpful-count">{{ $question->helpful_count ?? 0 }}</span>
                    <span class="text-orange-200 text-xs">helpful</span>
                </span>
            </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-blue-600 transition flex items-center">
                    <i class="fas fa-home mr-1"></i>Home
                </a>
                <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
                <a href="{{ route('public.knowledge-base.index') }}" class="hover:text-blue-600 transition">Knowledge Base</a>
                @if($question->category)
                    <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
                    <a href="{{ route('public.knowledge-base.category', $question->category->slug) }}" class="hover:text-blue-600 transition">{{ $question->category->name }}</a>
                @endif
                <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
                <span class="text-gray-900 font-medium truncate max-w-xs">{{ Str::limit($question->title, 50) }}</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 Content --}}
            <div class="lg:col-span-3">

                {{-- Question Content --}}
                <div class="bg-theme-card rounded-2xl shadow-sm overflow-hidden mb-6">
                    <div class="p-6">
                        <div class="prose max-w-none text-theme-body">
                            {!! $question->content !!}
                        </div>

                        {{-- Tags --}}
                        @if($question->tags)
                            @php $tags = is_array($question->tags) ? $question->tags : explode(',', $question->tags); @endphp
                            <div class="flex flex-wrap gap-2 mt-6 pt-5 border-t border-gray-100">
                                @foreach($tags as $tag)
                                    <a href="{{ route('public.knowledge-base.tag', trim($tag)) }}"
                                       class="px-3 py-1 bg-blue-50 text-blue-700 rounded-full text-xs font-medium hover:bg-blue-100 transition">
                                        <i class="fas fa-tag mr-1 text-xs"></i>{{ trim($tag) }}
                                    </a>
                                @endforeach
                            </div>
                        @endif
                    </div>

                    {{-- Inward divider --}}
                    <div class="relative mx-6">
                        <div class="border-t-2 border-gray-200" style="box-shadow: inset 0 2px 4px rgba(0,0,0,0.06);"></div>
                    </div>

                    {{-- Actions --}}
                    <div class="px-6 py-4 flex flex-wrap items-center justify-between gap-3">
                        <div class="flex items-center gap-3">
                            {{-- Helpful --}}
                            <button onclick="markHelpful({{ $question->id }}, this)"
                                    class="inline-flex items-center gap-2 px-4 py-2 rounded-xl border border-gray-200 hover:bg-blue-50 hover:border-blue-300 hover:text-blue-700 transition text-sm text-theme-body">
                                <i class="fas fa-thumbs-up"></i>
                                Helpful (<span id="helpful-btn-count">{{ $question->helpful_count ?? 0 }}</span>)
                            </button>

                            {{-- Bookmark --}}
                            @auth
                            <button onclick="bookmarkQuestion({{ $question->id }}, this)"
                                    class="inline-flex items-center gap-2 px-4 py-2 rounded-xl border border-gray-200 hover:bg-theme-body transition text-sm text-theme-body">
                                <i class="fas fa-bookmark"></i>Save
                            </button>
                            @endauth

                            {{-- Share --}}
                            <button onclick="shareQuestion()"
                                    class="inline-flex items-center gap-2 px-4 py-2 rounded-xl border border-gray-200 hover:bg-theme-body transition text-sm text-theme-body">
                                <i class="fas fa-share-alt"></i>Share
                            </button>
                        </div>

                        {{-- Edit (owner or manager) --}}
                        @auth
                            @if($question->user_id === auth()->id() || auth()->user()->can('edit knowledge base questions'))
                                <a href="{{ route('knowledge-sharing.knowledge-base.edit', $question) }}"
                                   class="inline-flex items-center gap-2 text-sm text-blue-600 hover:underline">
                                    <i class="fas fa-edit"></i>Edit Question
                                </a>
                            @endif
                        @endauth
                    </div>
                </div>

                {{-- Answers Section --}}
                <div class="bg-theme-card rounded-2xl shadow-sm overflow-hidden mb-6">

                    {{-- Answers header --}}
                    <div class="px-6 py-4 bg-gradient-to-r from-blue-600 to-indigo-600">
                        <h2 class="text-base font-bold text-white flex items-center gap-2">
                            <i class="fas fa-lightbulb"></i>
                            Answers
                            <span class="ml-1 bg-white bg-opacity-20 text-white text-xs px-2 py-0.5 rounded-full">{{ $answers->count() }}</span>
                        </h2>
                    </div>

                    {{-- Answers List --}}
                    <div class="divide-y divide-gray-100">
                        @forelse($answers as $answer)
                            <div class="p-6 {{ $answer->is_accepted ? 'bg-green-50' : '' }}" id="answer-{{ $answer->id }}">
                                @if($answer->is_accepted)
                                    <div class="flex items-center gap-2 text-green-600 mb-3 text-xs font-semibold">
                                        <i class="fas fa-check-circle"></i>Accepted Answer
                                    </div>
                                @endif

                                <div class="flex items-start gap-3">
                                    <img src="{{ $answer->user->avatar ?? 'https://ui-avatars.com/api/?name=' . urlencode($answer->user->name) . '&size=40&background=1e40af&color=fff' }}"
                                         alt="{{ $answer->user->name }}"
                                         class="w-9 h-9 rounded-full flex-shrink-0">
                                    <div class="flex-1 min-w-0">
                                        <div class="flex items-center justify-between mb-2 flex-wrap gap-2">
                                            <div class="flex items-center gap-2">
                                                <span class="font-semibold text-theme-heading text-sm">{{ $answer->user->name }}</span>
                                                @if($answer->user_id === $question->user_id)
                                                    <span class="px-2 py-0.5 bg-blue-100 text-blue-700 text-xs rounded-full font-medium">Author</span>
                                                @endif
                                                @if($answer->is_accepted)
                                                    <span class="px-2 py-0.5 bg-green-100 text-green-700 text-xs rounded-full font-medium">
                                                        <i class="fas fa-check mr-1"></i>Accepted
                                                    </span>
                                                @endif
                                            </div>
                                            <span class="text-xs text-gray-400">{{ $answer->created_at->diffForHumans() }}</span>
                                        </div>
                                        <div class="prose prose-sm max-w-none text-theme-body">
                                            {!! $answer->content !!}
                                        </div>
                                        <div class="flex items-center gap-4 mt-3 text-sm">
                                            {{-- Helpful vote --}}
                                            <button onclick="voteAnswer({{ $answer->id }}, this)"
                                                    class="flex items-center gap-1.5 text-gray-400 hover:text-blue-600 transition">
                                                <i class="fas fa-thumbs-up text-xs"></i>
                                                <span id="answer-helpful-{{ $answer->id }}">{{ $answer->helpful_count ?? 0 }}</span>
                                            </button>

                                            {{-- Accept answer (question owner or manager) --}}
                                            @auth
                                                @if($question->user_id === auth()->id() || auth()->user()->can('accept knowledge base answers'))
                                                    @if(!$answer->is_accepted)
                                                        <form action="{{ route('knowledge-sharing.knowledge-base.answers.accept', [$question, $answer]) }}"
                                                              method="POST" class="inline">
                                                            @csrf
                                                            <button type="submit" class="text-xs text-gray-400 hover:text-green-600 transition">
                                                                <i class="fas fa-check-circle mr-1"></i>Accept
                                                            </button>
                                                        </form>
                                                    @endif
                                                @endif

                                                {{-- Edit/Delete (owner or manager) --}}
                                                @if($answer->user_id === auth()->id() || auth()->user()->can('edit knowledge base answers'))
                                                    <a href="{{ route('knowledge-sharing.knowledge-base.answers.edit', [$question, $answer]) }}"
                                                       class="text-xs text-gray-400 hover:text-amber-600 transition">
                                                        <i class="fas fa-edit mr-1"></i>Edit
                                                    </a>
                                                @endif
                                                @if($answer->user_id === auth()->id() || auth()->user()->can('delete knowledge base answers'))
                                                    <form action="{{ route('knowledge-sharing.knowledge-base.answers.destroy', [$question, $answer]) }}"
                                                          method="POST" class="inline"
                                                          onsubmit="return confirm('Delete this answer?')">
                                                        @csrf
                                                        @method('DELETE')
                                                        <button type="submit" class="text-xs text-gray-400 hover:text-red-600 transition">
                                                            <i class="fas fa-trash mr-1"></i>Delete
                                                        </button>
                                                    </form>
                                                @endif
                                            @endauth
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @empty
                            <div class="p-10 text-center">
                                <i class="fas fa-lightbulb text-5xl text-gray-200 mb-4 block"></i>
                                <h3 class="text-base font-semibold text-theme-heading mb-2">No answers yet</h3>
                                <p class="text-theme-body text-sm mb-4">Be the first to provide an answer!</p>
                                @auth
                                    @can('answer knowledge base questions')
                                    <button onclick="document.getElementById('answerForm').scrollIntoView({behavior:'smooth'})"
                                            class="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-xl hover:bg-blue-700 transition text-sm font-semibold">
                                        <i class="fas fa-edit mr-2"></i>Write an Answer
                                    </button>
                                    @endcan
                                @endauth
                            </div>
                        @endforelse
                    </div>
                </div>

                {{-- Answer Form --}}
                @auth
                    @can('answer knowledge base questions')
                    <div id="answerForm" class="bg-theme-card rounded-2xl shadow-sm overflow-hidden">
                        <div class="px-6 py-4 bg-gradient-to-r from-blue-600 to-indigo-600">
                            <h3 class="text-base font-bold text-white flex items-center gap-2">
                                <i class="fas fa-edit"></i>Your Answer
                            </h3>
                        </div>
                        <div class="p-6">
                            <form action="{{ route('knowledge-sharing.knowledge-base.answers.store', $question) }}" method="POST">
                                @csrf
                                <textarea name="content"
                                          rows="7"
                                          placeholder="Write a detailed, helpful answer. Include examples or step-by-step instructions where applicable. Minimum 20 characters."
                                          class="w-full px-4 py-3 border border-gray-200 rounded-xl bg-theme-body text-theme-body focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm resize-y"
                                          required></textarea>
                                <div class="flex justify-end mt-4">
                                    <button type="submit"
                                            class="px-6 py-2.5 bg-blue-600 text-white text-sm font-semibold rounded-xl hover:bg-blue-700 transition shadow-sm">
                                        <i class="fas fa-paper-plane mr-2"></i>Post Your Answer
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    @else
                        <div class="bg-theme-card rounded-2xl shadow-sm p-6 text-center">
                            <p class="text-theme-body text-sm mb-3">
                                You need the <strong>Contributor</strong> role to post answers.
                            </p>
                        </div>
                    @endcan
                @else
                    <div class="bg-theme-card rounded-2xl shadow-sm p-6 text-center">
                        <p class="text-theme-body text-sm mb-4">
                            <a href="{{ route('public.contributor.login') }}" class="text-blue-600 hover:underline font-medium">Sign in</a>
                            or
                            <a href="{{ route('register.role.contributor') }}" class="text-blue-600 hover:underline font-medium">register</a>
                            to post an answer.
                        </p>
                        <a href="{{ route('register.role.contributor') }}"
                           class="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-xl hover:bg-blue-700 transition text-sm font-semibold">
                            <i class="fas fa-user-plus mr-2"></i>Join Community
                        </a>
                    </div>
                @endauth

            </div>

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

                {{-- Related Questions --}}
                <div class="bg-theme-card rounded-2xl shadow-sm overflow-hidden">
                    <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-4 py-3">
                        <h3 class="text-sm font-bold text-white flex items-center gap-2">
                            <i class="fas fa-link"></i>Related Questions
                        </h3>
                    </div>
                    <ul class="divide-y divide-gray-100">
                        @forelse($relatedQuestions as $related)
                            <li>
                                <a href="{{ route('public.knowledge-base.show', $related->slug) }}"
                                   class="block p-3 hover:bg-theme-body transition">
                                    <h4 class="text-xs font-semibold text-theme-heading line-clamp-2 mb-1">{{ $related->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($related->view_count) }}</span>
                                        <span><i class="fas fa-lightbulb mr-1"></i>{{ $related->answer_count }}</span>
                                    </div>
                                </a>
                            </li>
                        @empty
                            <li class="p-4 text-center text-xs text-gray-400">No related questions</li>
                        @endforelse
                    </ul>
                </div>

                {{-- Categories --}}
                <div class="bg-theme-card rounded-2xl shadow-sm overflow-hidden">
                    <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-4 py-3">
                        <h3 class="text-sm font-bold text-white flex items-center gap-2">
                            <i class="fas fa-folder"></i>Categories
                        </h3>
                    </div>
                    <ul class="divide-y divide-gray-100">
                        @foreach($categories as $cat)
                            <li>
                                <a href="{{ route('public.knowledge-base.category', $cat->slug) }}"
                                   class="flex items-center justify-between p-3 hover:bg-theme-body transition {{ $question->category_id === $cat->id ? 'bg-blue-50 border-l-4 border-blue-500' : '' }}">
                                    <span class="flex items-center gap-2 text-xs text-theme-body">
                                        <i class="fas {{ $cat->icon ?? 'fa-folder' }} {{ $cat->color ? "text-{$cat->color}-500" : 'text-gray-400' }} w-4"></i>
                                        {{ $cat->name }}
                                    </span>
                                </a>
                            </li>
                        @endforeach
                    </ul>
                </div>

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

    @push('scripts')
    <script>
    function markHelpful(questionId, btn) {
        const token = document.querySelector('meta[name="csrf-token"]')?.content;
        if (!token) { return; }
        fetch(`/api/knowledge-sharing/knowledge-base/${questionId}/helpful`, {
            method: 'POST',
            headers: { 'X-CSRF-TOKEN': token, 'Accept': 'application/json' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                const c1 = document.getElementById('helpful-count');
                const c2 = document.getElementById('helpful-btn-count');
                if (c1) c1.textContent = data.data.helpful_count;
                if (c2) c2.textContent = data.data.helpful_count;
                btn.classList.toggle('text-blue-600', data.data.is_helpful);
                btn.classList.toggle('border-blue-400', data.data.is_helpful);
            }
        })
        .catch(() => {});
    }

    function voteAnswer(answerId, btn) {
        const token = document.querySelector('meta[name="csrf-token"]')?.content;
        if (!token) { return; }
        fetch(`/api/knowledge-sharing/knowledge-base/answers/${answerId}/helpful`, {
            method: 'POST',
            headers: { 'X-CSRF-TOKEN': token, 'Accept': 'application/json' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                const span = document.getElementById(`answer-helpful-${answerId}`);
                if (span) span.textContent = data.data.helpful_count;
                btn.classList.toggle('text-blue-600', data.data.is_helpful);
            }
        })
        .catch(() => {});
    }

    function bookmarkQuestion(questionId, btn) {
        const token = document.querySelector('meta[name="csrf-token"]')?.content;
        if (!token) { return; }
        fetch(`/api/knowledge-sharing/knowledge-base/${questionId}/bookmark`, {
            method: 'POST',
            headers: { 'X-CSRF-TOKEN': token, 'Accept': 'application/json' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                btn.classList.toggle('text-blue-600', data.data.is_bookmarked);
                btn.classList.toggle('border-blue-400', data.data.is_bookmarked);
                const icon = btn.querySelector('i');
                if (icon) {
                    icon.className = data.data.is_bookmarked
                        ? 'fas fa-bookmark text-blue-600'
                        : 'fas fa-bookmark';
                }
            }
        })
        .catch(() => {});
    }

    function shareQuestion() {
        if (navigator.share) {
            navigator.share({ title: '{{ addslashes($question->title) }}', url: window.location.href });
        } else {
            navigator.clipboard.writeText(window.location.href)
                .then(() => {
                    const btn = event.currentTarget;
                    const orig = btn.innerHTML;
                    btn.innerHTML = '<i class="fas fa-check mr-2"></i>Copied!';
                    setTimeout(() => btn.innerHTML = orig, 2000);
                })
                .catch(() => alert('Link: ' + window.location.href));
        }
    }
    </script>
    @endpush

</x-site-layout>
