<x-app-layout>

<x-module-hero
    title="Edit Reply"
    description="Update your reply in: {{ Str::limit($thread->title, 50) }}"
    icon="fa-edit">

    <x-slot name="backButton">
        <a href="{{ route('partners.forum.show', $thread) }}"
           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 Thread
        </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>

</x-module-hero>

<div class="p-6">
    @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-3 gap-6">

        {{-- Main Edit Form --}}
        <div class="lg:col-span-2 space-y-5">

            {{-- Thread Context --}}
            <div class="bg-indigo-50 rounded-xl border border-indigo-200 p-4">
                <p class="text-xs text-indigo-600 font-medium mb-1">Editing reply in thread:</p>
                <h3 class="font-semibold text-indigo-900 text-sm">{{ $thread->title }}</h3>
                <p class="text-xs text-indigo-600 mt-1">
                    by {{ $thread->user->name }} · {{ $thread->created_at->diffForHumans() }}
                </p>
            </div>

            @if($reply->is_edited)
                <div class="bg-yellow-50 border border-yellow-200 rounded-xl p-3 flex items-center gap-2 text-yellow-700 text-xs">
                    <i class="fas fa-info-circle"></i>
                    Previously edited · Last edit: {{ $reply->edited_at->format('M d, Y H:i') }}
                </div>
            @endif

            {{-- Edit Form --}}
            <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-edit text-indigo-600"></i> Reply Content
                    </h3>
                </div>
                <div class="p-6">
                    <form action="{{ route('partners.forum.replies.update', $reply) }}" method="POST"
                          enctype="multipart/form-data" id="edit-reply-form">
                        @csrf
                        @method('PUT')

                        {{-- Quill Editor --}}
                        <div class="mb-5">
                            <div id="edit-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>
                                    <button class="ql-strike"></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="edit-reply-editor"
                                 class="border border-t-0 border-gray-300 rounded-b-lg bg-white"
                                 style="min-height: 200px; font-size: 0.875rem;"></div>
                            <input type="hidden" name="content" id="edit-reply-content-input">
                            @error('content')
                                <p class="mt-1 text-xs text-red-600">{{ $message }}</p>
                            @enderror
                            <p class="mt-1.5 text-xs text-gray-400">Minimum 5 characters.</p>
                        </div>

                        {{-- Existing Attachments --}}
                        @if($reply->attachments->count() > 0)
                            <div class="mb-5">
                                <p class="text-xs font-semibold text-gray-700 mb-2 flex items-center gap-2">
                                    <i class="fas fa-paperclip text-gray-400"></i>
                                    Current Attachments
                                </p>
                                <div class="space-y-2">
                                    @foreach($reply->attachments as $att)
                                        <div class="flex items-center gap-3 p-2.5 bg-gray-50 rounded-lg border border-gray-200">
                                            @if($att->isImage())
                                                <img src="{{ Storage::disk($att->disk)->url($att->path) }}"
                                                     class="w-10 h-10 rounded object-cover flex-shrink-0">
                                            @else
                                                <span class="{{ $att->icon_class }} text-xl flex-shrink-0"></span>
                                            @endif
                                            <div class="flex-1 min-w-0">
                                                <p class="text-xs font-medium text-gray-800 truncate">{{ $att->original_name }}</p>
                                                <p class="text-xs text-gray-400">{{ $att->human_size }}</p>
                                            </div>
                                            <label class="flex items-center gap-1.5 text-xs text-red-600 cursor-pointer">
                                                <input type="checkbox" name="remove_attachments[]"
                                                       value="{{ $att->id }}"
                                                       class="w-3.5 h-3.5 text-red-500 border-gray-300 rounded">
                                                Remove
                                            </label>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        @endif

                        {{-- New Attachments --}}
                        <div class="mb-5">
                            <p class="text-xs font-semibold text-gray-700 mb-2 flex items-center gap-2">
                                <i class="fas fa-plus-circle text-gray-400"></i>
                                Add New Attachments <span class="text-gray-400 font-normal">(optional)</span>
                            </p>
                            <div id="edit-drop-zone"
                                 class="border-2 border-dashed border-gray-200 rounded-xl p-5 text-center cursor-pointer hover:border-indigo-400 hover:bg-indigo-50/20 transition-all"
                                 onclick="document.getElementById('edit-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="edit-file-input" name="attachments[]"
                                   multiple accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.doc,.docx,.xls,.xlsx"
                                   class="hidden">
                            <div id="edit-file-preview" class="mt-3 space-y-2"></div>
                        </div>

                        {{-- Actions --}}
                        <div class="flex items-center justify-between pt-4 border-t border-gray-100">
                            <button type="button"
                                    onclick="if(confirm('Delete this reply? This cannot be undone.')) document.getElementById('delete-form').submit();"
                                    class="inline-flex items-center gap-2 px-4 py-2 text-red-600 hover:bg-red-50 rounded-lg transition text-sm">
                                <i class="fas fa-trash"></i> Delete Reply
                            </button>
                            <div class="flex items-center gap-3">
                                <a href="{{ route('partners.forum.show', $thread) }}"
                                   class="px-5 py-2.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm">
                                    Cancel
                                </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-save"></i> Save Changes
                                </button>
                            </div>
                        </div>
                    </form>

                    <form id="delete-form" action="{{ route('partners.forum.replies.destroy', $reply) }}"
                          method="POST" class="hidden">
                        @csrf @method('DELETE')
                    </form>
                </div>
            </div>
        </div>

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

            {{-- Reply 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> Reply Info
                </h4>
                <ul class="space-y-2 text-xs">
                    <li class="flex justify-between">
                        <span class="text-gray-500">Posted</span>
                        <span class="font-medium text-gray-800">{{ $reply->created_at->format('M d, Y H:i') }}</span>
                    </li>
                    <li class="flex justify-between">
                        <span class="text-gray-500">Author</span>
                        <span class="font-medium text-gray-800">{{ $reply->user->name }}</span>
                    </li>
                    @if($reply->helpful_count > 0)
                        <li class="flex justify-between">
                            <span class="text-gray-500">Helpful Votes</span>
                            <span class="font-medium text-gray-800">{{ $reply->helpful_count }}</span>
                        </li>
                    @endif
                    @if($reply->is_best_answer)
                        <li class="col-span-2">
                            <span class="inline-flex items-center gap-1 text-green-600 font-medium">
                                <i class="fas fa-check-circle"></i> Marked as Best Answer
                            </span>
                        </li>
                    @endif
                </ul>
            </div>

            {{-- Editing Guidelines --}}
            <div class="bg-blue-50 rounded-xl border border-blue-200 p-5">
                <h4 class="text-sm font-semibold text-blue-900 mb-3 flex items-center gap-2">
                    <i class="fas fa-lightbulb text-blue-600"></i> Editing Guidelines
                </h4>
                <ul class="text-xs text-blue-800 space-y-2">
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-blue-500 mt-0.5 flex-shrink-0"></i>
                        Edits are tracked and visible to moderators.
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-blue-500 mt-0.5 flex-shrink-0"></i>
                        Maintain the original intent of your reply.
                    </li>
                    <li class="flex items-start gap-2">
                        <i class="fas fa-check text-blue-500 mt-0.5 flex-shrink-0"></i>
                        Avoid changing meaning after others have responded.
                    </li>
                </ul>
            </div>

            {{-- Original Content Preview --}}
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                <details>
                    <summary class="px-5 py-3 cursor-pointer text-xs font-medium text-gray-600 hover:bg-gray-50 flex items-center gap-2">
                        <i class="fas fa-history text-gray-400"></i> View Original Content
                    </summary>
                    <div class="px-5 py-4 border-t border-gray-100 text-xs text-gray-600 forum-content">
                        {!! $reply->content !!}
                    </div>
                </details>
            </div>
        </div>
    </div>
</div>

<link href="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.snow.css" rel="stylesheet">
<style>
    .forum-content p { margin-bottom: 0.5rem; }
    .forum-content p:last-child { margin-bottom: 0; }
    .forum-content ul,.forum-content ol { padding-left: 1.25rem; margin-bottom: 0.5rem; }
    .forum-content blockquote { border-left: 3px solid #6366f1; padding-left: 0.75rem; color: #6b7280; font-style: italic; }
    .forum-content img { max-width: 100%; border-radius: 0.375rem; }
</style>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.js"></script>
<script>
const editReplyQuill = new Quill('#edit-reply-editor', {
    theme: 'snow',
    modules: {
        toolbar: '#edit-reply-toolbar',
        clipboard: { matchVisual: false },
    },
    placeholder: 'Edit your reply...',
});

// Load existing content
editReplyQuill.root.innerHTML = {!! json_encode($reply->content) !!};

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

// File attachment preview
const editFileInput   = document.getElementById('edit-file-input');
const editFilePreview = document.getElementById('edit-file-preview');
const editDropZone    = document.getElementById('edit-drop-zone');
let editFiles = [];

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 renderEditPreviews() {
    editFilePreview.innerHTML = '';
    editFiles.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="removeEditFile(${idx})" class="text-gray-400 hover:text-red-500 transition p-1">
                <i class="fas fa-times text-xs"></i>
            </button>`;
        editFilePreview.appendChild(div);
    });
    const dt = new DataTransfer();
    editFiles.forEach(f => dt.items.add(f));
    editFileInput.files = dt.files;
}
function removeEditFile(idx) { editFiles.splice(idx, 1); renderEditPreviews(); }

editFileInput.addEventListener('change', function () {
    editFiles = [...editFiles, ...Array.from(this.files)].slice(0, 5);
    renderEditPreviews();
});
editDropZone.addEventListener('dragover', e => { e.preventDefault(); editDropZone.classList.add('border-indigo-400','bg-indigo-50'); });
editDropZone.addEventListener('dragleave', () => editDropZone.classList.remove('border-indigo-400','bg-indigo-50'));
editDropZone.addEventListener('drop', e => {
    e.preventDefault();
    editDropZone.classList.remove('border-indigo-400','bg-indigo-50');
    editFiles = [...editFiles, ...Array.from(e.dataTransfer.files)].slice(0, 5);
    renderEditPreviews();
});
</script>
@endpush

</x-app-layout>
