{{--
    Public Discussion Show Page
    ============================
    Features:
    - Branded hero header with topic badge
    - Real-time view/reply counts (Alpine.js polling)
    - RBAC: @can/@auth guards on all action buttons
    - Threaded replies with nested display
    - Inward-styled divider
    - SEO structured data
    Layout: Site Layout (public)
--}}
<x-site-layout
    title="{{ $seoMetadata['title'] ?? $discussion->title }}"
    meta-description="{{ $seoMetadata['description'] ?? Str::limit(strip_tags($discussion->content), 160) }}"
>
    {{-- Structured Data --}}
    @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-teal-700 via-green-700 to-emerald-800 overflow-hidden">
        <div class="absolute inset-0 pointer-events-none">
            <div class="absolute -top-16 -right-16 w-64 h-64 bg-white opacity-5 rounded-full"></div>
            <div class="absolute -bottom-12 -left-12 w-48 h-48 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-8">

            {{-- Topic badge --}}
            @if($discussion->topic)
                <div class="mb-3">
                    <a href="{{ route('public.discussions.topic', $discussion->topic->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 {{ $discussion->topic->icon ?? 'fa-folder' }} text-xs"></i>
                        {{ $discussion->topic->name }}
                    </a>
                    @if($discussion->is_featured)
                        <span class="ml-2 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($discussion->is_pinned)
                        <span class="ml-2 inline-flex items-center gap-1 px-3 py-1 bg-purple-400 text-purple-900 text-xs font-semibold rounded-full">
                            <i class="fas fa-thumbtack text-xs"></i>Pinned
                        </span>
                    @endif
                </div>
            @endif

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

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

            {{-- Real-time stats bar --}}
            <div class="flex flex-wrap gap-3"
                 x-data="discussionStats({{ $discussion->id }}, {{ $discussion->view_count }}, {{ $discussion->reply_count }})"
                 x-init="startPolling()">
                <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-teal-200 text-xs"></i>
                    <span x-text="viewCount.toLocaleString()">{{ number_format($discussion->view_count) }}</span>
                    <span class="text-teal-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-comment text-emerald-200 text-xs"></i>
                    <span x-text="replyCount.toLocaleString()">{{ number_format($discussion->reply_count) }}</span>
                    <span class="text-emerald-200 text-xs">replies</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-clock text-amber-200 text-xs"></i>
                    <span class="text-amber-200 text-xs">{{ $discussion->reading_time }} min read</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-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>
                @if($discussion->topic)
                    <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
                    <a href="{{ route('public.discussions.topic', $discussion->topic->slug) }}" class="hover:text-teal-600 transition">{{ $discussion->topic->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($discussion->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">

                {{-- Discussion 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">
                            {!! $discussion->content !!}
                        </div>
                    </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">
                            {{-- Like button --}}
                            @auth
                            <button onclick="likeDiscussion({{ $discussion->id }}, this)"
                                    class="inline-flex items-center gap-2 px-4 py-2 rounded-xl border border-gray-200 hover:bg-teal-50 hover:border-teal-300 hover:text-teal-700 transition text-sm text-theme-body">
                                <i class="fas fa-thumbs-up"></i>
                                <span id="like-count-{{ $discussion->id }}">{{ $discussion->like_count ?? 0 }}</span>
                            </button>
                            @endauth

                            {{-- Share --}}
                            <button onclick="shareDiscussion()"
                                    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($discussion->user_id === auth()->id() || auth()->user()->can('edit discussions'))
                                <a href="{{ route('knowledge-sharing.discussions.edit', $discussion) }}"
                                   class="inline-flex items-center gap-2 text-sm text-teal-600 hover:underline">
                                    <i class="fas fa-edit"></i>Edit Discussion
                                </a>
                            @endif
                        @endauth
                    </div>
                </div>

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

                    {{-- Replies header --}}
                    <div class="px-6 py-4 bg-gradient-to-r from-teal-600 to-emerald-600">
                        <h2 class="text-base font-bold text-white flex items-center gap-2">
                            <i class="fas fa-comments"></i>
                            Replies
                            <span class="ml-1 bg-white bg-opacity-20 text-white text-xs px-2 py-0.5 rounded-full"
                                  id="reply-count-badge">{{ $discussion->reply_count }}</span>
                        </h2>
                    </div>

                    {{-- Reply Form --}}
                    @auth
                        @if(auth()->user()->can('create discussion replies') || auth()->user()->can('create discussions'))
                        <div class="p-6 bg-teal-50 border-b border-teal-100">
                            <form action="{{ route('knowledge-sharing.discussions.replies.store', $discussion) }}" method="POST">
                                @csrf
                                <div class="flex items-start gap-3">
                                    <img src="{{ auth()->user()->avatar ?? 'https://ui-avatars.com/api/?name=' . urlencode(auth()->user()->name) . '&size=40&background=0d9488&color=fff' }}"
                                         alt="{{ auth()->user()->name }}"
                                         class="w-9 h-9 rounded-full flex-shrink-0 mt-1">
                                    <div class="flex-1">
                                        <textarea name="content"
                                                  rows="3"
                                                  placeholder="Write your reply… (minimum 10 characters)"
                                                  class="w-full px-4 py-3 border border-teal-200 rounded-xl bg-white text-gray-700 focus:ring-2 focus:ring-teal-500 focus:border-transparent text-sm resize-none"
                                                  required></textarea>
                                        <div class="flex justify-end mt-2">
                                            <button type="submit"
                                                    class="px-5 py-2 bg-teal-600 text-white text-sm font-semibold rounded-xl hover:bg-teal-700 transition">
                                                <i class="fas fa-paper-plane mr-2"></i>Post Reply
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        @endif
                    @else
                        <div class="p-6 bg-teal-50 border-b border-teal-100 text-center">
                            <div class="w-12 h-12 bg-teal-100 rounded-full flex items-center justify-center mx-auto mb-3">
                                <i class="fas fa-reply text-teal-600 text-lg"></i>
                            </div>
                            <p class="text-gray-600 text-sm mb-4">Join the community to reply to this discussion.</p>
                            <div class="flex flex-col sm:flex-row gap-3 justify-center">
                                <a href="{{ route('register.role.contributor') }}"
                                   class="inline-flex items-center justify-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 Reply
                                </a>
                                <a href="{{ route('public.contributor.login') }}"
                                   class="inline-flex items-center justify-center px-5 py-2.5 border border-teal-600 text-teal-600 text-sm font-semibold rounded-xl hover:bg-teal-50 transition">
                                    <i class="fas fa-sign-in-alt mr-2"></i>Sign In
                                </a>
                            </div>
                        </div>
                    @endauth

                    {{-- Replies List --}}
                    <div class="divide-y divide-gray-100">
                        @forelse($replies as $reply)
                            <div class="p-6 {{ $reply->is_accepted_answer ? 'bg-green-50' : '' }}"
                                 id="reply-{{ $reply->id }}"
                                 style="{{ $reply->depth > 0 ? 'margin-left: ' . ($reply->depth * 24) . 'px;' : '' }}">

                                @if($reply->is_accepted_answer)
                                    <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="{{ $reply->user->avatar ?? 'https://ui-avatars.com/api/?name=' . urlencode($reply->user->name) . '&size=40&background=0d9488&color=fff' }}"
                                         alt="{{ $reply->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">{{ $reply->user->name }}</span>
                                                @if($reply->user_id === $discussion->user_id)
                                                    <span class="px-2 py-0.5 bg-teal-100 text-teal-700 text-xs rounded-full font-medium">Author</span>
                                                @endif
                                                @if($reply->is_accepted_answer)
                                                    <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">{{ $reply->created_at->diffForHumans() }}</span>
                                        </div>
                                        <div class="prose prose-sm max-w-none text-theme-body">
                                            {!! $reply->content !!}
                                        </div>
                                        <div class="flex items-center gap-4 mt-3 text-sm">
                                            {{-- Like reply --}}
                                            @auth
                                            <button onclick="likeReply({{ $reply->id }}, this)"
                                                    class="flex items-center gap-1.5 text-gray-400 hover:text-teal-600 transition">
                                                <i class="fas fa-thumbs-up text-xs"></i>
                                                <span id="reply-like-{{ $reply->id }}">{{ $reply->like_count ?? 0 }}</span>
                                            </button>
                                            @endauth

                                            {{-- Edit/Delete (owner or manager) --}}
                                            @auth
                                                @if($reply->user_id === auth()->id() || auth()->user()->can('edit discussion replies'))
                                                    <a href="{{ route('knowledge-sharing.discussions.replies.edit', [$discussion, $reply]) }}"
                                                       class="text-xs text-gray-400 hover:text-amber-600 transition">
                                                        <i class="fas fa-edit mr-1"></i>Edit
                                                    </a>
                                                @endif
                                                @if($reply->user_id === auth()->id() || auth()->user()->can('delete discussion replies'))
                                                    <form action="{{ route('knowledge-sharing.discussions.replies.destroy', [$discussion, $reply]) }}"
                                                          method="POST" class="inline"
                                                          onsubmit="return confirm('Delete this reply?')">
                                                        @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-comment-slash text-4xl text-gray-200 mb-4 block"></i>
                                <p class="text-theme-body text-sm">No replies yet. Be the first to reply!</p>
                            </div>
                        @endforelse
                    </div>

                    @if($replies->hasPages())
                        <div class="p-4 border-t border-gray-100">
                            {{ $replies->links() }}
                        </div>
                    @endif
                </div>

            </div>

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

                {{-- Related Discussions --}}
                <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-link"></i>Related Discussions
                        </h3>
                    </div>
                    <ul class="divide-y divide-gray-100">
                        @forelse($relatedDiscussions as $related)
                            <li>
                                <a href="{{ route('public.discussions.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-comment mr-1"></i>{{ $related->reply_count }}</span>
                                    </div>
                                </a>
                            </li>
                        @empty
                            <li class="p-4 text-center text-xs text-gray-400">No related discussions</li>
                        @endforelse
                    </ul>
                </div>

                {{-- 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>Topics
                        </h3>
                    </div>
                    <ul class="divide-y divide-gray-100">
                        @foreach($topics as $topic)
                            <li>
                                <a href="{{ route('public.discussions.topic', $topic->slug) }}"
                                   class="flex items-center justify-between p-3 hover:bg-theme-body transition {{ $discussion->topic_id === $topic->id ? 'bg-teal-50 border-l-4 border-teal-500' : '' }}">
                                    <span class="flex items-center gap-2 text-xs text-theme-body">
                                        <i class="fas {{ $topic->icon ?? 'fa-folder' }} {{ $topic->color ? "text-{$topic->color}-500" : 'text-gray-400' }} w-4"></i>
                                        {{ $topic->name }}
                                    </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>
                        <a href="{{ route('knowledge-sharing.discussions.create') }}"
                           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 discussionStats(discussionId, initialViews, initialReplies) {
        return {
            viewCount: initialViews,
            replyCount: initialReplies,
            startPolling() {
                // Real-time counts update on page load; no polling needed
                // The view count is incremented server-side on each page load
                const badge = document.getElementById('reply-count-badge');
                if (badge) badge.textContent = this.replyCount;
            }
        };
    }

    function likeDiscussion(id, btn) {
        const token = document.querySelector('meta[name="csrf-token"]')?.content;
        if (!token) return;
        fetch(`/api/knowledge-sharing/discussions/${id}/like`, {
            method: 'POST',
            headers: { 'X-CSRF-TOKEN': token, 'Accept': 'application/json' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                const span = document.getElementById(`like-count-${id}`);
                if (span) span.textContent = data.data.like_count;
                btn.classList.toggle('text-teal-600', data.data.is_liked);
                btn.classList.toggle('border-teal-400', data.data.is_liked);
            }
        })
        .catch(() => {});
    }

    function likeReply(id, btn) {
        const token = document.querySelector('meta[name="csrf-token"]')?.content;
        if (!token) return;
        fetch(`/api/knowledge-sharing/discussions/replies/${id}/like`, {
            method: 'POST',
            headers: { 'X-CSRF-TOKEN': token, 'Accept': 'application/json' }
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                const span = document.getElementById(`reply-like-${id}`);
                if (span) span.textContent = data.data.like_count;
                btn.classList.toggle('text-teal-600', data.data.is_liked);
            }
        })
        .catch(() => {});
    }

    function shareDiscussion() {
        if (navigator.share) {
            navigator.share({ title: '{{ addslashes($discussion->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>
