<x-app-layout>

    <x-module-hero
        title="Edit Publication: {{ $publication->title }}"
        description="Update your research publication details"
        icon="fa-edit">

        <x-slot name="backButton">
            <a href="{{ route('research.show', $publication) }}"
               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 Publication
            </a>
        </x-slot>

        <x-slot name="tabs">
            @can('view own publications')
            <a href="{{ route('research.index') }}"
               class="module-hero-tab {{ request()->routeIs('research.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-list text-sm"></i> My Publications
            </a>
            @endcan
            @can('create publications')
            <a href="{{ route('research.create') }}"
               class="module-hero-tab {{ request()->routeIs('research.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 Publication
            </a>
            @endcan
            @can('review publications')
            <a href="{{ route('research.review.index') }}"
               class="module-hero-tab {{ request()->routeIs('research.review.*') ? '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-clipboard-check text-sm"></i> Review Queue
            </a>
            @endcan
        </x-slot>

    </x-module-hero>

    <div class="p-6">

        @if($publication->status === 'under_review')
        <div class="mb-4 p-4 bg-yellow-100 border border-yellow-400 text-yellow-700 rounded-lg flex items-center text-sm">
            <i class="fas fa-exclamation-triangle mr-3"></i>
            This publication is currently under review. Some fields may be locked until the review is complete.
        </div>
        @endif

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

        <form action="{{ route('research.update', $publication) }}" method="POST" enctype="multipart/form-data"
              x-data="{
                  coverPreview: {{ $publication->cover_image ? json_encode(Storage::url($publication->cover_image)) : 'null' }},
                  files: [],
                  handleCoverImage(event) {
                      const file = event.target.files[0];
                      if (file) {
                          const reader = new FileReader();
                          reader.onload = (e) => this.coverPreview = e.target.result;
                          reader.readAsDataURL(file);
                      }
                  },
                  handleFiles(event) { this.files = Array.from(event.target.files); }
              }">
            @csrf
            @method('PUT')

            {{-- Basic Information --}}
            <div class="mb-6">
                <h3 class="text-base font-semibold text-gray-800 border-b pb-2 mb-4">
                    <i class="fas fa-info-circle text-green-700 mr-2"></i> Basic Information
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="md:col-span-2">
                        <label for="title" class="block text-sm font-medium text-gray-700 mb-1">
                            Title <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="title" name="title"
                               value="{{ old('title', $publication->title) }}" required
                               class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 text-sm">
                        @error('title')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                    </div>
                    <div>
                        <label for="category" class="block text-sm font-medium text-gray-700 mb-1">
                            Category <span class="text-red-500">*</span>
                        </label>
                        <select id="category" name="category" required
                                class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 text-sm">
                            <option value="">Select a category</option>
                            @foreach($categories as $key => $label)
                            <option value="{{ $key }}" {{ old('category', $publication->category) === $key ? 'selected' : '' }}>{{ $label }}</option>
                            @endforeach
                        </select>
                        @error('category')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                    </div>
                    <div>
                        <label for="cover_image" class="block text-sm font-medium text-gray-700 mb-1">Cover Image</label>
                        <div class="flex items-start gap-4">
                            <div class="flex-1">
                                <input type="file" id="cover_image" name="cover_image" accept="image/*"
                                       @change="handleCoverImage($event)"
                                       class="w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm">
                                <p class="mt-1 text-xs text-gray-500">Recommended: 1200×630px. Max 5MB.</p>
                            </div>
                            <div class="w-20 h-16 bg-gray-100 rounded-lg overflow-hidden flex-shrink-0">
                                <img x-show="coverPreview" :src="coverPreview" class="w-full h-full object-cover">
                                <div x-show="!coverPreview" class="w-full h-full flex items-center justify-center text-gray-400">
                                    <i class="fas fa-image"></i>
                                </div>
                            </div>
                        </div>
                        @error('cover_image')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                    </div>
                    <div class="md:col-span-2">
                        <label for="abstract" class="block text-sm font-medium text-gray-700 mb-1">
                            Abstract <span class="text-red-500">*</span>
                        </label>
                        <textarea id="abstract" name="abstract" rows="5" required
                                  class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 text-sm">{{ old('abstract', $publication->abstract) }}</textarea>
                        @error('abstract')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                    </div>
                </div>
            </div>

            {{-- Research Content --}}
            <div class="mb-6">
                <h3 class="text-base font-semibold text-gray-800 border-b pb-2 mb-4">
                    <i class="fas fa-file-alt text-green-700 mr-2"></i> Research Content
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="methodology" class="block text-sm font-medium text-gray-700 mb-1">Methodology</label>
                        <textarea id="methodology" name="methodology" rows="7"
                                  class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 text-sm">{{ old('methodology', $publication->methodology) }}</textarea>
                        @error('methodology')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                    </div>
                    <div>
                        <label for="findings" class="block text-sm font-medium text-gray-700 mb-1">Key Findings</label>
                        <textarea id="findings" name="findings" rows="7"
                                  class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 text-sm">{{ old('findings', $publication->findings) }}</textarea>
                        @error('findings')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                    </div>
                    <div class="md:col-span-2">
                        <label for="references" class="block text-sm font-medium text-gray-700 mb-1">References</label>
                        <textarea id="references" name="references" rows="5"
                                  class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 text-sm">{{ old('references', $publication->references) }}</textarea>
                        @error('references')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                    </div>
                </div>
            </div>

            {{-- Supporting Documents --}}
            <div class="mb-6">
                <h3 class="text-base font-semibold text-gray-800 border-b pb-2 mb-4">
                    <i class="fas fa-paperclip text-green-700 mr-2"></i> Supporting Documents
                </h3>
                @if($publication->files->count() > 0)
                <div class="mb-4">
                    <p class="text-sm font-medium text-gray-700 mb-2">Current Files</p>
                    <div class="space-y-2">
                        @foreach($publication->files as $file)
                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg text-sm">
                            <div class="flex items-center gap-2">
                                <i class="fas {{ $file->icon }} text-green-600"></i>
                                <span class="text-gray-700">{{ $file->original_name }}</span>
                                <span class="text-xs text-gray-500">({{ $file->formatted_size }})</span>
                            </div>
                            <button type="button"
                                    onclick="deleteFile({{ $publication->id }}, {{ $file->id }})"
                                    class="text-red-500 hover:text-red-700 text-xs">
                                <i class="fas fa-trash"></i> Remove
                            </button>
                        </div>
                        @endforeach
                    </div>
                </div>
                @endif
                <div class="border-2 border-dashed border-gray-300 rounded-lg p-5 text-center hover:border-green-500 transition">
                    <i class="fas fa-cloud-upload-alt text-2xl text-gray-400 mb-2"></i>
                    <p class="text-gray-600 text-sm mb-1">Add more files</p>
                    <input type="file" name="files[]" multiple
                           accept=".pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg"
                           @change="handleFiles($event)"
                           class="w-full text-sm text-gray-500">
                    <p class="text-xs text-gray-400 mt-1">PDF, DOC, XLS, PNG, JPG — max 10MB each</p>
                </div>
            </div>

            {{-- Actions --}}
            <div class="flex justify-between items-center pt-4 border-t border-gray-200">
                <a href="{{ route('research.show', $publication) }}"
                   class="px-5 py-2.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition text-sm font-medium">
                    <i class="fas fa-times mr-2"></i> Cancel
                </a>
                <div class="flex gap-3">
                    <button type="submit" name="action" value="draft"
                            class="px-5 py-2.5 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition text-sm font-medium">
                        <i class="fas fa-save mr-2"></i> Save Changes
                    </button>
                    @if(in_array($publication->status, ['draft', 'revision_required']))
                    <button type="submit" name="action" value="submit"
                            class="px-5 py-2.5 bg-green-700 text-white rounded-lg hover:bg-green-800 transition text-sm font-medium">
                        <i class="fas fa-paper-plane mr-2"></i> Submit for Review
                    </button>
                    @endif
                </div>
            </div>

        </form>
    </div>

</x-app-layout>

@push('scripts')
<script>
function deleteFile(publicationId, fileId) {
    if (!confirm('Are you sure you want to delete this file?')) return;
    fetch(`/dashboard/research/${publicationId}/files/${fileId}`, {
        method: 'DELETE',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json'
        }
    })
    .then(r => r.json())
    .then(data => { if (data.success) location.reload(); else alert('Failed: ' + data.message); })
    .catch(() => alert('An error occurred.'));
}
</script>
@endpush
