<x-app-layout>

<x-module-hero
    title="{{ Str::limit($thread->title, 55) }}"
    description="{{ $thread->category_label }} · {{ $thread->replies_count }} {{ Str::plural('reply', $thread->replies_count) }} · {{ $thread->views_count }} views"
    icon="fa-comments">

    <x-slot name="backButton">
        <a href="{{ route('partners.forum.index') }}"
           class="inline-flex items-center gap-1 text-sm text-[#475569] hover:text-[#1e293b] transition-colors">
            <i class="fas fa-arrow-left text-xs"></i> Back to Forum
        </a>
    </x-slot>

    <x-slot name="tabs">
        @can('view partners')
        <a href="{{ route('partners.index') }}"
           class="module-hero-tab {{ request()->routeIs('partners.index') && !request()->routeIs('partners.forum.*') ? '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-handshake text-sm"></i> Partners
        </a>
        @endcan
        @can('view forum')
        <a href="{{ route('partners.forum.index') }}"
           class="module-hero-tab {{ request()->routeIs('partners.forum.index') ? '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> Forum
        </a>
        @endcan
        @can('create forum threads')
        <a href="{{ route('partners.forum.create') }}"
           class="module-hero-tab {{ request()->routeIs('partners.forum.create') ? '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-plus text-sm"></i> New Thread
        </a>
        @endcan
    </x-slot>

    @can('moderate forum')
    <x-slot name="actions">
        <button onclick="togglePin()"
                class="inline-flex items-center gap-2 px-3 py-1.5 bg-[#1e293b] hover:bg-[#334155] text-white text-xs font-medium rounded-lg transition-colors">
            <i class="fas fa-thumbtack"></i> {{ $thread->is_pinned ? 'Unpin' : 'Pin' }}
        </button>
        <button onclick="toggleLock()"
                class="inline-flex items-center gap-2 px-3 py-1.5 bg-[#475569] hover:bg-[#334155] text-white text-xs font-medium rounded-lg transition-colors">
            <i class="fas fa-{{ $thread->is_locked ? 'unlock' : 'lock' }}"></i> {{ $thread->is_locked ? 'Unlock' : 'Lock' }}
        </button>
    </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

    <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">

        {{-- Main Column --}}
        <div class="lg:col-span-3 space-y-5">

            {{-- Original Thread Post --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                {{-- Thread Header Bar --}}
                <div class="px-6 py-3 flex items-center justify-between"
                     style="background: linear-gradient(90deg, #1a4731 0%, #276749 40%, #c53030 100%);">
                    <div class="flex items-center gap-3 flex-wrap">
                        <span class="px-2.5 py-0.5 bg-white/20 text-white rounded-full text-xs font-medium">
                            {{ $thread->category_label }}
                        </span>
                        @if($thread->is_pinned)
                            <span class="text-yellow-300 text-xs flex items-center gap-1">
                                <i class="fas fa-thumbtack"></i> Pinned
                            </span>
                        @endif
                        @if($thread->is_locked)
                            <span class="text-red-300 text-xs flex items-center gap-1">
                                <i class="fas fa-lock"></i> Locked
                            </span>
                        @endif
                        @if($thread->is_featured)
                            <span class="text-yellow-300 text-xs flex items-center gap-1">
                                <i class="fas fa-star"></i> Featured
                            </span>
                        @endif
                    </div>
                    <div class="flex items-center gap-3 text-white/70 text-xs">
                        <span><i class="fas fa-eye mr-1"></i>{{ $thread->views_count }}</span>
                        <span><i class="fas fa-comments mr-1"></i>{{ $thread->replies_count }}</span>
                    </div>
                </div>

                <div class="p-6">
                    <h1 class="text-xl font-bold text-gray-900 mb-3 leading-snug">{{ $thread->title }}</h1>

                    @if(!empty($thread->tags) && count($thread->tags) > 0)
                        <div class="flex flex-wrap gap-1.5 mb-4">
                            @foreach($thread->tags as $tag)
                                <span class="px-2 py-0.5 bg-indigo-100 text-indigo-700 text-xs rounded-full">#{{ $tag }}</span>
                            @endforeach
                        </div>
                    @endif

                    {{-- Author Info --}}
                    <div class="flex items-center gap-3 mb-5 pb-5 border-b border-gray-100">
                        <div class="w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center flex-shrink-0">
                            <span class="text-indigo-600 font-bold text-sm">{{ Str::substr($thread->user->name, 0, 1) }}</span>
                        </div>
                        <div>
                            <p class="font-semibold text-gray-900 text-sm">{{ $thread->user->name }}</p>
                            <p class="text-xs text-gray-500">
                                @if($thread->partner)
                                    <span class="text-indigo-600">{{ $thread->partner->organization_name }}</span> ·
                                @else
                                    {{ $thread->user->roles->first()?->name ?? 'Member' }} ·
                                @endif
                                {{ $thread->created_at->format('M d, Y \a\t H:i') }}
                            </p>
                        </div>
                        @if($thread->isAuthor(auth()->id()) || auth()->user()->can('moderate forum'))
                            <div class="ml-auto flex items-center gap-2">
                                @can('moderate forum')
                                <form action="{{ route('partners.forum.destroy', $thread) }}" method="POST"
                                      onsubmit="return confirm('Delete this thread? This cannot be undone.')">
                                    @csrf @method('DELETE')
                                    <button type="submit"
                                            class="text-xs text-red-500 hover:text-red-700 px-2 py-1 rounded hover:bg-red-50 transition">
                                        <i class="fas fa-trash mr-1"></i>Delete
                                    </button>
                                </form>
                                @endcan
                            </div>
                        @endif
                    </div>

                    {{-- Thread Content (rendered HTML from Quill) --}}
                    <div class="prose prose-sm max-w-none text-gray-800 leading-relaxed forum-content">
                        {!! $thread->content !!}
                    </div>

                    {{-- Thread Attachments --}}
                    @if($thread->attachments->count() > 0)
                        <div class="mt-6 pt-5 border-t border-gray-100">
                            <p class="text-xs font-semibold text-gray-600 mb-3 flex items-center gap-2">
                                <i class="fas fa-paperclip text-gray-400"></i>
                                Attachments ({{ $thread->attachments->count() }})
                            </p>
                            @include('forum._attachments', ['attachments' => $thread->attachments])
                        </div>
                    @endif
                </div>
            </div>

            {{-- Replies Section --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-100 bg-gray-50 flex items-center justify-between">
                    <h2 class="font-semibold text-gray-900 text-sm flex items-center gap-2">
                        <i class="fas fa-comments text-indigo-600"></i>
                        {{ $thread->replies_count }} {{ Str::plural('Reply', $thread->replies_count) }}
                    </h2>
                </div>

                @if($thread->replies->count() > 0)
                    <div class="divide-y divide-gray-100">
                        @foreach($thread->replies as $index => $reply)
                            <div class="{{ $index % 2 === 0 ? 'bg-white' : 'bg-gray-50/50' }} {{ $reply->is_best_answer ? 'border-l-4 border-green-500 bg-green-50/30' : '' }} p-6"
                                 id="reply-{{ $reply->id }}">

                                @if($reply->is_best_answer)
                                    <div class="flex items-center gap-2 text-green-700 mb-3 text-xs font-semibold bg-green-100 rounded-lg px-3 py-1.5 w-fit">
                                        <i class="fas fa-check-circle"></i> Best Answer
                                    </div>
                                @endif

                                <div class="flex gap-4">
                                    <div class="flex-shrink-0">
                                        <div class="w-9 h-9 bg-indigo-100 rounded-full flex items-center justify-center">
                                            <span class="text-indigo-600 font-bold text-xs">{{ Str::substr($reply->user->name, 0, 1) }}</span>
                                        </div>
                                    </div>
                                    <div class="flex-1 min-w-0">
                                        <div class="flex items-start justify-between mb-2 gap-2">
                                            <div>
                                                <span class="font-semibold text-gray-900 text-sm">{{ $reply->user->name }}</span>
                                                <span class="text-xs text-gray-400 ml-2">{{ $reply->created_at->diffForHumans() }}</span>
                                                @if($reply->is_edited)
                                                    <span class="text-xs text-gray-400 ml-1">(edited)</span>
                                                @endif
                                            </div>
                                            <div class="flex items-center gap-2 flex-shrink-0">
                                                <button onclick="markHelpful({{ $reply->id }}, this)"
                                                        class="flex items-center gap-1 text-xs text-gray-500 hover:text-green-600 transition px-2 py-1 rounded hover:bg-green-50">
                                                    <i class="far fa-thumbs-up"></i>
                                                    <span class="helpful-count">{{ $reply->helpful_count }}</span>
                                                </button>
                                                <div class="relative" x-data="{ open: false }">
                                                    <button @click="open = !open"
                                                            class="p-1.5 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded transition">
                                                        <i class="fas fa-ellipsis-v text-xs"></i>
                                                    </button>
                                                    <div x-show="open" @click.away="open = false" x-transition
                                                         class="absolute right-0 mt-1 w-48 bg-white rounded-xl shadow-xl border border-gray-200 z-20 py-1.5"
                                                         style="display:none;">
                                                        @if($reply->isAuthor(auth()->id()) || auth()->user()->can('moderate forum'))
                                                            <a href="{{ route('partners.forum.replies.edit', $reply) }}"
                                                               class="flex items-center gap-2 px-4 py-2 text-xs text-gray-700 hover:bg-gray-50">
                                                                <i class="fas fa-edit w-3 text-center"></i> Edit Reply
                                                            </a>
                                                            <form action="{{ route('partners.forum.replies.destroy', $reply) }}" method="POST"
                                                                  onsubmit="return confirm('Delete this reply?')">
                                                                @csrf @method('DELETE')
                                                                <button type="submit"
                                                                        class="w-full flex items-center gap-2 px-4 py-2 text-xs text-red-600 hover:bg-red-50">
                                                                    <i class="fas fa-trash w-3 text-center"></i> Delete Reply
                                                                </button>
                                                            </form>
                                                        @endif
                                                        @if(($thread->isAuthor(auth()->id()) || auth()->user()->can('moderate forum')) && !$reply->is_best_answer)
                                                            <div class="border-t border-gray-100 my-1"></div>
                                                            <button onclick="markBestAnswer({{ $reply->id }})"
                                                                    class="w-full flex items-center gap-2 px-4 py-2 text-xs text-green-600 hover:bg-green-50">
                                                                <i class="fas fa-check-circle w-3 text-center"></i> Mark Best Answer
                                                            </button>
                                                        @endif
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        {{-- Reply Content (rendered HTML) --}}
                                        <div class="prose prose-sm max-w-none text-gray-800 text-sm leading-relaxed forum-content">
                                            {!! $reply->content !!}
                                        </div>

                                        {{-- Reply Attachments --}}
                                        @if($reply->attachments->count() > 0)
                                            <div class="mt-4 pt-3 border-t border-gray-100">
                                                @include('forum._attachments', ['attachments' => $reply->attachments])
                                            </div>
                                        @endif

                                        {{-- Nested Replies --}}
                                        @if($reply->replies->count() > 0)
                                            <div class="mt-4 pl-4 border-l-2 border-indigo-100 space-y-3">
                                                @foreach($reply->replies as $nested)
                                                    <div class="bg-gray-50 rounded-xl p-4 border border-gray-100">
                                                        <div class="flex items-center gap-2 mb-2">
                                                            <div class="w-6 h-6 bg-gray-200 rounded-full flex items-center justify-center flex-shrink-0">
                                                                <span class="text-gray-600 font-bold text-xs">{{ Str::substr($nested->user->name, 0, 1) }}</span>
                                                            </div>
                                                            <span class="font-medium text-gray-900 text-xs">{{ $nested->user->name }}</span>
                                                            <span class="text-xs text-gray-400">{{ $nested->created_at->diffForHumans() }}</span>
                                                        </div>
                                                        <div class="prose prose-xs max-w-none text-gray-700 text-xs forum-content">
                                                            {!! $nested->content !!}
                                                        </div>
                                                        @if($nested->attachments->count() > 0)
                                                            <div class="mt-2">
                                                                @include('forum._attachments', ['attachments' => $nested->attachments, 'compact' => true])
                                                            </div>
                                                        @endif
                                                    </div>
                                                @endforeach
                                            </div>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                @else
                    <div class="p-10 text-center text-gray-500">
                        <i class="fas fa-comment-slash text-4xl text-gray-300 mb-3 block"></i>
                        <p class="text-sm font-medium text-gray-600">No replies yet.</p>
                        <p class="text-xs text-gray-400 mt-1">Be the first to respond!</p>
                    </div>
                @endif
            </div>

            {{-- Reply Form --}}
            @if(!$thread->is_locked)
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="px-6 py-4 border-b border-gray-100 bg-gray-50">
                        <h3 class="font-semibold text-gray-900 text-sm flex items-center gap-2">
                            <i class="fas fa-reply text-indigo-600"></i> Post a Reply
                        </h3>
                    </div>
                    <div class="p-6">
                        <form action="{{ route('partners.forum.reply', $thread) }}" method="POST"
                              enctype="multipart/form-data" id="reply-form">
                            @csrf

                            {{-- Quill Reply Editor --}}
                            <div class="mb-4">
                                <div id="reply-toolbar" class="border border-gray-300 rounded-t-lg bg-gray-50">
                                    <span class="ql-formats">
                                        <button class="ql-bold"></button>
                                        <button class="ql-italic"></button>
                                        <button class="ql-underline"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-blockquote"></button>
                                        <button class="ql-list" value="ordered"></button>
                                        <button class="ql-list" value="bullet"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-link"></button>
                                        <button class="ql-image"></button>
                                    </span>
                                    <span class="ql-formats">
                                        <button class="ql-clean"></button>
                                    </span>
                                </div>
                                <div id="reply-editor"
                                     class="border border-t-0 border-gray-300 rounded-b-lg bg-white"
                                     style="min-height: 140px; font-size: 0.875rem;"></div>
                                <input type="hidden" name="content" id="reply-content-input">
                                @error('content')
                                    <p class="mt-1 text-xs text-red-600">{{ $message }}</p>
                                @enderror
                            </div>

                            {{-- Reply Attachments --}}
                            <div class="mb-4">
                                <label class="block text-xs font-medium text-gray-700 mb-2">
                                    <i class="fas fa-paperclip text-gray-400 mr-1"></i>
                                    Attach Files <span class="text-gray-400 font-normal">(optional, max 5)</span>
                                </label>
                                <div id="reply-drop-zone"
                                     class="border-2 border-dashed border-gray-200 rounded-lg p-4 text-center cursor-pointer hover:border-indigo-400 hover:bg-indigo-50/20 transition-all"
                                     onclick="document.getElementById('reply-file-input').click()">
                                    <i class="fas fa-cloud-upload-alt text-gray-400 text-xl mb-1 block"></i>
                                    <p class="text-xs text-gray-500">Click or drop files here</p>
                                    <p class="text-xs text-gray-400">Images, PDF, Word, Excel · Max 10 MB each</p>
                                </div>
                                <input type="file" id="reply-file-input" name="attachments[]"
                                       multiple accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.doc,.docx,.xls,.xlsx"
                                       class="hidden">
                                <div id="reply-file-preview" class="mt-3 space-y-2"></div>
                            </div>

                            <div class="flex items-center justify-between">
                                <a href="{{ route('partners.forum.index') }}"
                                   class="inline-flex items-center gap-2 text-sm text-gray-500 hover:text-gray-700 transition">
                                    <i class="fas fa-arrow-left text-xs"></i> Back to Forum
                                </a>
                                <button type="submit"
                                        class="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition text-sm font-semibold shadow-sm">
                                    <i class="fas fa-paper-plane"></i> Post Reply
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            @else
                <div class="bg-gray-100 rounded-xl p-6 text-center border border-gray-200">
                    <i class="fas fa-lock text-2xl text-gray-400 mb-2 block"></i>
                    <p class="text-gray-600 text-sm font-medium">This thread is locked for new replies.</p>
                    <a href="{{ route('partners.forum.index') }}"
                       class="inline-flex items-center gap-2 mt-3 text-sm text-indigo-600 hover:text-indigo-800 transition">
                        <i class="fas fa-arrow-left text-xs"></i> Back to Forum
                    </a>
                </div>
            @endif

        </div>{{-- end main column --}}

        {{-- Sidebar --}}
        <div class="space-y-5">

            {{-- Thread Info --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <h4 class="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
                    <i class="fas fa-info-circle text-indigo-600"></i> Thread Info
                </h4>
                <ul class="space-y-2 text-xs">
                    <li class="flex justify-between">
                        <span class="text-gray-500">Category</span>
                        <span class="font-medium text-gray-800">{{ $thread->category_label }}</span>
                    </li>
                    <li class="flex justify-between">
                        <span class="text-gray-500">Visibility</span>
                        <span class="font-medium text-gray-800 capitalize">{{ str_replace('_', ' ', $thread->visibility) }}</span>
                    </li>
                    <li class="flex justify-between">
                        <span class="text-gray-500">Posted</span>
                        <span class="font-medium text-gray-800">{{ $thread->created_at->format('M d, Y') }}</span>
                    </li>
                    <li class="flex justify-between">
                        <span class="text-gray-500">Views</span>
                        <span class="font-medium text-gray-800">{{ number_format($thread->views_count) }}</span>
                    </li>
                    <li class="flex justify-between">
                        <span class="text-gray-500">Replies</span>
                        <span class="font-medium text-gray-800">{{ $thread->replies_count }}</span>
                    </li>
                    @if($thread->last_reply_at)
                        <li class="flex justify-between">
                            <span class="text-gray-500">Last Reply</span>
                            <span class="font-medium text-gray-800">{{ $thread->last_reply_at->diffForHumans() }}</span>
                        </li>
                    @endif
                </ul>
            </div>

            {{-- Author Card --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <h4 class="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
                    <i class="fas fa-user text-indigo-600"></i> Posted By
                </h4>
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center flex-shrink-0">
                        <span class="text-indigo-600 font-bold text-sm">{{ Str::substr($thread->user->name, 0, 1) }}</span>
                    </div>
                    <div>
                        <p class="font-semibold text-gray-900 text-sm">{{ $thread->user->name }}</p>
                        @if($thread->partner)
                            <p class="text-xs text-indigo-600">{{ $thread->partner->organization_name }}</p>
                        @else
                            <p class="text-xs text-gray-500">{{ $thread->user->roles->first()?->name ?? 'Member' }}</p>
                        @endif
                    </div>
                </div>
            </div>

            {{-- Moderator Actions --}}
            @can('moderate forum')
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
                <h4 class="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
                    <i class="fas fa-shield-alt text-indigo-600"></i> Moderation
                </h4>
                <div class="space-y-2">
                    <button onclick="togglePin()"
                            class="w-full flex items-center gap-2 px-3 py-2 text-xs rounded-lg transition
                                {{ $thread->is_pinned ? 'bg-yellow-50 text-yellow-700 hover:bg-yellow-100' : 'bg-gray-50 text-gray-700 hover:bg-gray-100' }}">
                        <i class="fas fa-thumbtack w-4 text-center"></i>
                        {{ $thread->is_pinned ? 'Unpin Thread' : 'Pin to Top' }}
                    </button>
                    <button onclick="toggleLock()"
                            class="w-full flex items-center gap-2 px-3 py-2 text-xs rounded-lg transition
                                {{ $thread->is_locked ? 'bg-green-50 text-green-700 hover:bg-green-100' : 'bg-red-50 text-red-700 hover:bg-red-100' }}">
                        <i class="fas fa-{{ $thread->is_locked ? 'unlock' : 'lock' }} w-4 text-center"></i>
                        {{ $thread->is_locked ? 'Unlock Thread' : 'Lock Thread' }}
                    </button>
                    <form action="{{ route('partners.forum.destroy', $thread) }}" method="POST"
                          onsubmit="return confirm('Delete this entire thread? This cannot be undone.')">
                        @csrf @method('DELETE')
                        <button type="submit"
                                class="w-full flex items-center gap-2 px-3 py-2 text-xs bg-red-50 text-red-700 hover:bg-red-100 rounded-lg transition">
                            <i class="fas fa-trash w-4 text-center"></i> Delete Thread
                        </button>
                    </form>
                </div>
            </div>
            @endcan

        </div>{{-- end sidebar --}}
    </div>
</div>

{{-- Quill CSS --}}
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.snow.css" rel="stylesheet">
<style>
    /* Ensure Quill-rendered content displays cleanly */
    .forum-content p { margin-bottom: 0.75rem; }
    .forum-content p:last-child { margin-bottom: 0; }
    .forum-content h1,.forum-content h2,.forum-content h3 { font-weight: 700; margin: 1rem 0 0.5rem; }
    .forum-content ul,.forum-content ol { padding-left: 1.5rem; margin-bottom: 0.75rem; }
    .forum-content li { margin-bottom: 0.25rem; }
    .forum-content blockquote { border-left: 4px solid #6366f1; padding-left: 1rem; color: #6b7280; margin: 0.75rem 0; font-style: italic; }
    .forum-content pre { background: #f3f4f6; padding: 0.75rem 1rem; border-radius: 0.5rem; overflow-x: auto; font-size: 0.8rem; }
    .forum-content a { color: #6366f1; text-decoration: underline; }
    .forum-content img { max-width: 100%; border-radius: 0.5rem; margin: 0.5rem 0; }
</style>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.js"></script>
<script>
const CSRF = document.querySelector('meta[name="csrf-token"]').content;

// ── Reply Quill Editor ────────────────────────────────────────────────────────
@if(!$thread->is_locked)
const replyQuill = new Quill('#reply-editor', {
    theme: 'snow',
    modules: {
        toolbar: '#reply-toolbar',
        clipboard: { matchVisual: false },
    },
    placeholder: 'Write your reply here...',
});

document.getElementById('reply-form').addEventListener('submit', function (e) {
    const content = replyQuill.root.innerHTML.trim();
    const text    = replyQuill.getText().trim();
    if (text.length < 5) {
        e.preventDefault();
        replyQuill.root.style.borderColor = '#ef4444';
        replyQuill.root.focus();
        if (window.showToast) window.showToast('Reply must be at least 5 characters.', 'error');
        return;
    }
    document.getElementById('reply-content-input').value = content;
});

// Reply file attachments
const replyFileInput   = document.getElementById('reply-file-input');
const replyFilePreview = document.getElementById('reply-file-preview');
const replyDropZone    = document.getElementById('reply-drop-zone');
let replyFiles = [];

function getFileIcon(name) {
    const ext = name.split('.').pop().toLowerCase();
    if (['jpg','jpeg','png','gif','webp'].includes(ext)) return '<i class="fas fa-image text-blue-500"></i>';
    if (ext === 'pdf') return '<i class="fas fa-file-pdf text-red-500"></i>';
    if (['doc','docx'].includes(ext)) return '<i class="fas fa-file-word text-blue-700"></i>';
    if (['xls','xlsx'].includes(ext)) return '<i class="fas fa-file-excel text-green-600"></i>';
    return '<i class="fas fa-file text-gray-500"></i>';
}
function formatBytes(b) {
    if (b < 1024) return b + ' B';
    if (b < 1048576) return (b/1024).toFixed(1) + ' KB';
    return (b/1048576).toFixed(1) + ' MB';
}
function renderReplyPreviews() {
    replyFilePreview.innerHTML = '';
    replyFiles.forEach((file, idx) => {
        const div = document.createElement('div');
        div.className = 'flex items-center gap-3 p-2.5 bg-gray-50 rounded-lg border border-gray-200';
        div.innerHTML = `
            <div class="text-lg flex-shrink-0">${getFileIcon(file.name)}</div>
            ${file.type.startsWith('image/') ? `<img src="${URL.createObjectURL(file)}" class="w-8 h-8 rounded object-cover flex-shrink-0">` : ''}
            <div class="flex-1 min-w-0">
                <p class="text-xs font-medium text-gray-800 truncate">${file.name}</p>
                <p class="text-xs text-gray-400">${formatBytes(file.size)}</p>
            </div>
            <button type="button" onclick="removeReplyFile(${idx})" class="text-gray-400 hover:text-red-500 transition p-1">
                <i class="fas fa-times text-xs"></i>
            </button>`;
        replyFilePreview.appendChild(div);
    });
    const dt = new DataTransfer();
    replyFiles.forEach(f => dt.items.add(f));
    replyFileInput.files = dt.files;
}
function removeReplyFile(idx) { replyFiles.splice(idx, 1); renderReplyPreviews(); }

replyFileInput.addEventListener('change', function () {
    replyFiles = [...replyFiles, ...Array.from(this.files)].slice(0, 5);
    renderReplyPreviews();
});
replyDropZone.addEventListener('dragover', e => { e.preventDefault(); replyDropZone.classList.add('border-indigo-400','bg-indigo-50'); });
replyDropZone.addEventListener('dragleave', () => replyDropZone.classList.remove('border-indigo-400','bg-indigo-50'));
replyDropZone.addEventListener('drop', e => {
    e.preventDefault();
    replyDropZone.classList.remove('border-indigo-400','bg-indigo-50');
    replyFiles = [...replyFiles, ...Array.from(e.dataTransfer.files)].slice(0, 5);
    renderReplyPreviews();
});
@endif

// ── Moderation Actions ────────────────────────────────────────────────────────
function togglePin() {
    fetch('{{ route('api.partners.forum.toggle-pin', $thread) }}', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF }
    }).then(r => r.json()).then(d => {
        if (d.success) { if (window.showToast) window.showToast(d.message, 'success'); setTimeout(() => location.reload(), 700); }
    });
}
function toggleLock() {
    fetch('{{ route('api.partners.forum.toggle-lock', $thread) }}', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF }
    }).then(r => r.json()).then(d => {
        if (d.success) { if (window.showToast) window.showToast(d.message, 'success'); setTimeout(() => location.reload(), 700); }
    });
}
function markHelpful(replyId, btn) {
    fetch(`/api/partners/forum/replies/${replyId}/helpful`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF }
    }).then(r => r.json()).then(d => {
        if (d.success) btn.querySelector('.helpful-count').textContent = d.helpful_count;
    });
}
function markBestAnswer(replyId) {
    if (!confirm('Mark this reply as the best answer?')) return;
    fetch(`/api/partners/forum/replies/${replyId}/best-answer`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF }
    }).then(r => r.json()).then(d => {
        if (d.success) { if (window.showToast) window.showToast(d.message, 'success'); setTimeout(() => location.reload(), 700); }
    });
}
</script>
@endpush

</x-app-layout>
