@extends('layouts.site')

@section('title', 'Submit a Research Publication')
@section('meta-description', 'Submit your research paper, clinical study, or innovative project to the SSHIA Research & Innovation Centre for peer review and publication.')

@section('content')

{{-- ── Hero ──────────────────────────────────────────────────────────────── --}}
<div class="bg-gradient-to-r from-indigo-700 to-purple-700 shadow-lg">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12 text-center">
        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-white/20 mb-4">
            <i class="fas fa-upload text-white text-2xl"></i>
        </div>
        <h1 class="text-3xl md:text-4xl font-bold text-white font-serif mb-3">
            Submit Your Research
        </h1>
        <p class="text-indigo-100 text-lg max-w-2xl mx-auto">
            Share your research with the SSHIA community. Fill in the form below — no account needed to start.
            You will be asked to register or log in as a Contributor only at the final step.
        </p>
    </div>
</div>

{{-- ── Breadcrumb ───────────────────────────────────────────────────────── --}}
<div class="bg-gray-50 border-b border-gray-200">
    <div class="max-w-4xl 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-indigo-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('research.public.index') }}" class="hover:text-indigo-600 transition">Research</a>
            <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
            <span class="text-gray-900 font-medium">Submit Publication</span>
        </nav>
    </div>
</div>

{{-- ── Main Form ────────────────────────────────────────────────────────── --}}
<div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">

    {{-- Flash messages --}}
    @if(session('error'))
    <div class="mb-6 flex items-center gap-3 bg-red-50 border border-red-200 text-red-800 rounded-xl px-5 py-4">
        <i class="fas fa-exclamation-circle text-red-500 flex-shrink-0"></i>
        <span class="text-sm">{{ session('error') }}</span>
    </div>
    @endif

    <form
        action="{{ route('research.public.submit.store') }}"
        method="POST"
        enctype="multipart/form-data"
        x-data="{
            step: 1,
            totalSteps: 4,
            coverPreview: null,
            paperFile: null,
            paperName: '',
            paperSize: '',
            stepErrors: {},

            /* ── helpers ── */
            formatBytes(bytes) {
                if (bytes < 1024) return bytes + ' B';
                if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
                return (bytes / 1048576).toFixed(1) + ' MB';
            },
            handleCover(e) {
                const f = e.target.files[0];
                if (!f) return;
                const reader = new FileReader();
                reader.onload = ev => this.coverPreview = ev.target.result;
                reader.readAsDataURL(f);
            },
            handlePaper(e) {
                const f = e.target.files[0];
                if (!f) return;
                this.paperFile = f;
                this.paperName = f.name;
                this.paperSize = this.formatBytes(f.size);
            },
            removePaper() {
                this.paperFile = null;
                this.paperName = '';
                this.paperSize = '';
                document.getElementById('full_paper').value = '';
            },

            /* ── step validation ── */
            validateStep() {
                this.stepErrors = {};
                if (this.step === 1) {
                    const title    = document.getElementById('title').value.trim();
                    const abstract = document.getElementById('abstract').value.trim();
                    const category = document.getElementById('category').value;
                    if (title.length < 10)     this.stepErrors.title    = 'Title must be at least 10 characters.';
                    if (abstract.length < 100) this.stepErrors.abstract = 'Abstract must be at least 100 characters.';
                    if (!category)             this.stepErrors.category = 'Please select a research category.';
                    return Object.keys(this.stepErrors).length === 0;
                }
                return true;
            },
            next() {
                if (this.validateStep()) {
                    this.step++;
                    if (this.step === 4) this.populateReview();
                }
            },
            prev() { this.step--; },

            /* ── populate review summary ── */
            populateReview() {
                this.$nextTick(() => {
                    const titleEl    = document.getElementById('review-title');
                    const catEl      = document.getElementById('review-category');
                    const absEl      = document.getElementById('review-abstract');
                    const titleInput = document.getElementById('title');
                    const catInput   = document.getElementById('category');
                    const absInput   = document.getElementById('abstract');
                    if (titleEl && titleInput) titleEl.textContent = titleInput.value || '—';
                    if (catEl && catInput)     catEl.textContent   = catInput.options[catInput.selectedIndex]?.text || '—';
                    if (absEl && absInput) {
                        const abs = absInput.value;
                        absEl.textContent = abs ? abs.substring(0, 200) + (abs.length > 200 ? '…' : '') : '—';
                    }
                });
            },

            /* ── progress ── */
            get progress() { return Math.round((this.step / this.totalSteps) * 100); },
            stepLabel(n) {
                return ['Basic Info', 'Research Content', 'Upload Paper', 'Review & Submit'][n - 1];
            }
        }"
    >
        @csrf

        {{-- ── Progress Bar ──────────────────────────────────────────────── --}}
        <div class="mb-8">
            <div class="flex items-center justify-between mb-2">
                <span class="text-sm font-semibold text-gray-700">
                    Step <span x-text="step"></span> of <span x-text="totalSteps"></span>
                    — <span x-text="stepLabel(step)"></span>
                </span>
                <span class="text-sm font-semibold text-indigo-600" x-text="progress + '%'"></span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-2.5">
                <div class="bg-indigo-600 h-2.5 rounded-full transition-all duration-500"
                     :style="'width:' + progress + '%'"></div>
            </div>
            {{-- Step dots --}}
            <div class="flex justify-between mt-3">
                @foreach(['Basic Info','Research Content','Upload Paper','Review & Submit'] as $i => $label)
                <div class="flex flex-col items-center" style="width:25%">
                    <div class="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition-all duration-300"
                         :class="step > {{ $i + 1 }} ? 'bg-indigo-600 text-white' : (step === {{ $i + 1 }} ? 'bg-indigo-600 text-white ring-4 ring-indigo-200' : 'bg-gray-200 text-gray-500')">
                        <template x-if="step > {{ $i + 1 }}"><i class="fas fa-check text-xs"></i></template>
                        <template x-if="step <= {{ $i + 1 }}"><span>{{ $i + 1 }}</span></template>
                    </div>
                    <span class="text-xs mt-1 text-center hidden sm:block"
                          :class="step >= {{ $i + 1 }} ? 'text-indigo-600 font-semibold' : 'text-gray-400'">
                        {{ $label }}
                    </span>
                </div>
                @endforeach
            </div>
        </div>

        {{-- ══════════════════════════════════════════════════════════════════
             STEP 1 — Basic Information
        ══════════════════════════════════════════════════════════════════ --}}
        <div x-show="step === 1" x-transition:enter="transition ease-out duration-200"
             x-transition:enter-start="opacity-0 translate-x-4"
             x-transition:enter-end="opacity-100 translate-x-0">

            <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-8 mb-6">
                <h2 class="text-xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                    <span class="w-8 h-8 rounded-full bg-indigo-600 text-white flex items-center justify-center text-sm font-bold">1</span>
                    Basic Information
                </h2>

                {{-- Title --}}
                <div class="mb-5">
                    <label for="title" class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Publication Title <span class="text-red-500">*</span>
                    </label>
                    <input type="text" id="title" name="title"
                           value="{{ old('title') }}"
                           placeholder="Enter the full title of your research publication"
                           class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm transition"
                           :class="stepErrors.title ? 'border-red-400 focus:ring-red-400' : ''"
                           required minlength="10" maxlength="191">
                    <p class="mt-1 text-xs text-gray-400">Minimum 10 characters. Be specific and descriptive.</p>
                    <p x-show="stepErrors.title" x-text="stepErrors.title" class="mt-1 text-xs text-red-600" x-cloak></p>
                    @error('title')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>

                {{-- Category --}}
                <div class="mb-5">
                    <label for="category" class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Research Category <span class="text-red-500">*</span>
                    </label>
                    <select id="category" name="category" required
                            :class="stepErrors.category ? 'border-red-400' : ''"
                            class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm transition bg-white">
                        <option value="">— Select a category —</option>
                        @foreach($categories as $key => $label)
                        <option value="{{ $key }}" {{ old('category') === $key ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                    <p x-show="stepErrors.category" x-text="stepErrors.category" class="mt-1 text-xs text-red-600" x-cloak></p>
                    @error('category')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>

                {{-- Abstract --}}
                <div class="mb-5">
                    <label for="abstract" class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Abstract <span class="text-red-500">*</span>
                    </label>
                    <textarea id="abstract" name="abstract" rows="6" required minlength="100" maxlength="5000"
                              placeholder="Provide a concise summary of your research (minimum 100 words). Include the purpose, methods, key findings, and conclusions."
                              :class="stepErrors.abstract ? 'border-red-400 focus:ring-red-400' : ''"
                              class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm transition resize-none">{{ old('abstract') }}</textarea>
                    <p class="mt-1 text-xs text-gray-400">Minimum 100 characters. Maximum 5,000 characters.</p>
                    <p x-show="stepErrors.abstract" x-text="stepErrors.abstract" class="mt-1 text-xs text-red-600" x-cloak></p>
                    @error('abstract')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>

                {{-- Cover Image --}}
                <div>
                    <label for="cover_image" class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Cover Image <span class="text-gray-400 font-normal">(optional)</span>
                    </label>
                    <div class="flex items-start gap-4">
                        <div class="flex-1">
                            <label for="cover_image"
                                   class="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-gray-300 rounded-xl cursor-pointer hover:border-indigo-400 hover:bg-indigo-50 transition">
                                <i class="fas fa-image text-gray-400 text-2xl mb-2"></i>
                                <span class="text-sm text-gray-500">Click to upload cover image</span>
                                <span class="text-xs text-gray-400 mt-1">JPEG, PNG, WebP — max 2 MB</span>
                                <input type="file" id="cover_image" name="cover_image"
                                       accept="image/jpeg,image/png,image/jpg,image/webp"
                                       @change="handleCover($event)" class="hidden">
                            </label>
                        </div>
                        <div x-show="coverPreview" class="w-32 h-32 rounded-xl overflow-hidden border border-gray-200 flex-shrink-0">
                            <img :src="coverPreview" class="w-full h-full object-cover" alt="Cover preview">
                        </div>
                    </div>
                    @error('cover_image')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════════════════════════
             STEP 2 — Research Content
        ══════════════════════════════════════════════════════════════════ --}}
        <div x-show="step === 2" x-transition:enter="transition ease-out duration-200"
             x-transition:enter-start="opacity-0 translate-x-4"
             x-transition:enter-end="opacity-100 translate-x-0">

            <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-8 mb-6">
                <h2 class="text-xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                    <span class="w-8 h-8 rounded-full bg-indigo-600 text-white flex items-center justify-center text-sm font-bold">2</span>
                    Research Content
                    <span class="text-sm font-normal text-gray-400 ml-1">(all fields optional but recommended)</span>
                </h2>

                {{-- Methodology --}}
                <div class="mb-5">
                    <label for="methodology" class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Methodology
                    </label>
                    <textarea id="methodology" name="methodology" rows="6" maxlength="10000"
                              placeholder="Describe your research design, data collection methods, sample size, analysis techniques, and any tools or instruments used."
                              class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm transition resize-none">{{ old('methodology') }}</textarea>
                    @error('methodology')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>

                {{-- Findings --}}
                <div class="mb-5">
                    <label for="findings" class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Key Findings
                    </label>
                    <textarea id="findings" name="findings" rows="6" maxlength="10000"
                              placeholder="Present your main research findings, results, and observations. Include statistical data where applicable."
                              class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm transition resize-none">{{ old('findings') }}</textarea>
                    @error('findings')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>

                {{-- References --}}
                <div>
                    <label for="references" class="block text-sm font-semibold text-gray-700 mb-1.5">
                        References &amp; Citations
                    </label>
                    <textarea id="references" name="references" rows="5" maxlength="15000"
                              placeholder="List your references in APA, MLA, or Vancouver format. One reference per line."
                              class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm transition resize-none">{{ old('references') }}</textarea>
                    @error('references')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════════════════════════
             STEP 3 — Upload Full Paper
        ══════════════════════════════════════════════════════════════════ --}}
        <div x-show="step === 3" x-transition:enter="transition ease-out duration-200"
             x-transition:enter-start="opacity-0 translate-x-4"
             x-transition:enter-end="opacity-100 translate-x-0">

            <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-8 mb-6">
                <h2 class="text-xl font-bold text-gray-900 mb-2 flex items-center gap-3">
                    <span class="w-8 h-8 rounded-full bg-indigo-600 text-white flex items-center justify-center text-sm font-bold">3</span>
                    Upload Full Paper
                </h2>
                <p class="text-sm text-gray-500 mb-6 ml-11">
                    Upload the complete research document. Accepted formats: PDF, DOC, DOCX. Maximum size: 20 MB.
                </p>

                {{-- Drop zone --}}
                <label for="full_paper"
                       class="flex flex-col items-center justify-center w-full min-h-[200px] border-2 border-dashed rounded-2xl cursor-pointer transition"
                       :class="paperFile ? 'border-indigo-400 bg-indigo-50' : 'border-gray-300 hover:border-indigo-400 hover:bg-indigo-50'">

                    <template x-if="!paperFile">
                        <div class="flex flex-col items-center py-8 px-4 text-center">
                            <div class="w-16 h-16 rounded-full bg-indigo-100 flex items-center justify-center mb-4">
                                <i class="fas fa-cloud-upload-alt text-indigo-500 text-2xl"></i>
                            </div>
                            <p class="text-base font-semibold text-gray-700 mb-1">Drag &amp; drop your paper here</p>
                            <p class="text-sm text-gray-500 mb-3">or click to browse files</p>
                            <span class="px-4 py-2 bg-indigo-600 text-white text-sm font-medium rounded-lg hover:bg-indigo-700 transition">
                                Choose File
                            </span>
                            <p class="text-xs text-gray-400 mt-3">PDF, DOC, DOCX — max 20 MB</p>
                        </div>
                    </template>

                    <template x-if="paperFile">
                        <div class="flex items-center gap-4 py-6 px-6 w-full">
                            <div class="w-14 h-14 rounded-xl bg-indigo-100 flex items-center justify-center flex-shrink-0">
                                <i class="fas fa-file-pdf text-indigo-600 text-2xl"></i>
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="font-semibold text-gray-900 truncate" x-text="paperName"></p>
                                <p class="text-sm text-gray-500" x-text="paperSize"></p>
                                <p class="text-xs text-indigo-600 mt-1">
                                    <i class="fas fa-check-circle mr-1"></i>File ready for upload
                                </p>
                            </div>
                            <button type="button" @click.prevent="removePaper()"
                                    class="w-9 h-9 rounded-full bg-red-100 text-red-600 hover:bg-red-200 flex items-center justify-center transition flex-shrink-0">
                                <i class="fas fa-times text-sm"></i>
                            </button>
                        </div>
                    </template>

                    <input type="file" id="full_paper" name="full_paper"
                           accept=".pdf,.doc,.docx"
                           @change="handlePaper($event)" class="hidden">
                </label>

                @error('full_paper')<p class="mt-2 text-xs text-red-600">{{ $message }}</p>@enderror

                {{-- Info box --}}
                <div class="mt-6 bg-amber-50 border border-amber-200 rounded-xl p-4">
                    <h4 class="text-sm font-semibold text-amber-800 mb-2 flex items-center gap-2">
                        <i class="fas fa-info-circle"></i> Before you continue
                    </h4>
                    <ul class="text-xs text-amber-700 space-y-1.5">
                        <li><i class="fas fa-check text-amber-500 mr-1.5"></i>Ensure your paper is the final version ready for review</li>
                        <li><i class="fas fa-check text-amber-500 mr-1.5"></i>Remove any identifying information if you prefer blind review</li>
                        <li><i class="fas fa-check text-amber-500 mr-1.5"></i>File upload is optional — you can also submit with just the form content</li>
                        <li><i class="fas fa-check text-amber-500 mr-1.5"></i>Your submission will be reviewed by our editorial team before publication</li>
                    </ul>
                </div>
            </div>
        </div>

        {{-- ══════════════════════════════════════════════════════════════════
             STEP 4 — Review & Submit
        ══════════════════════════════════════════════════════════════════ --}}
        <div x-show="step === 4" x-transition:enter="transition ease-out duration-200"
             x-transition:enter-start="opacity-0 translate-x-4"
             x-transition:enter-end="opacity-100 translate-x-0">

            <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-8 mb-6">
                <h2 class="text-xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                    <span class="w-8 h-8 rounded-full bg-indigo-600 text-white flex items-center justify-center text-sm font-bold">4</span>
                    Review &amp; Submit
                </h2>

                {{-- Summary card --}}
                <div class="bg-gray-50 rounded-xl border border-gray-200 p-5 mb-6 space-y-3 text-sm">
                    <div class="flex gap-3">
                        <span class="text-gray-500 w-28 flex-shrink-0">Title</span>
                        <span class="font-medium text-gray-900" id="review-title">—</span>
                    </div>
                    <div class="flex gap-3">
                        <span class="text-gray-500 w-28 flex-shrink-0">Category</span>
                        <span class="font-medium text-gray-900" id="review-category">—</span>
                    </div>
                    <div class="flex gap-3">
                        <span class="text-gray-500 w-28 flex-shrink-0">Abstract</span>
                        <span class="text-gray-700 line-clamp-3" id="review-abstract">—</span>
                    </div>
                    <div class="flex gap-3">
                        <span class="text-gray-500 w-28 flex-shrink-0">Full Paper</span>
                        <span class="font-medium text-gray-900" x-text="paperName || 'No file selected'"></span>
                    </div>
                </div>

                {{-- What happens next --}}
                <div class="bg-indigo-50 border border-indigo-200 rounded-xl p-5 mb-6">
                    <h4 class="text-sm font-bold text-indigo-800 mb-3 flex items-center gap-2">
                        <i class="fas fa-route"></i> What happens next?
                    </h4>
                    <ol class="space-y-2 text-sm text-indigo-700">
                        <li class="flex items-start gap-2">
                            <span class="w-5 h-5 rounded-full bg-indigo-200 text-indigo-700 flex items-center justify-center text-xs font-bold flex-shrink-0 mt-0.5">1</span>
                            <span>Click <strong>Submit</strong> — your form data is saved securely.</span>
                        </li>
                        <li class="flex items-start gap-2">
                            <span class="w-5 h-5 rounded-full bg-indigo-200 text-indigo-700 flex items-center justify-center text-xs font-bold flex-shrink-0 mt-0.5">2</span>
                            <span>You will be asked to <strong>register as a Contributor</strong> or <strong>log in</strong> if you already have an account.</span>
                        </li>
                        <li class="flex items-start gap-2">
                            <span class="w-5 h-5 rounded-full bg-indigo-200 text-indigo-700 flex items-center justify-center text-xs font-bold flex-shrink-0 mt-0.5">3</span>
                            <span>Your submission is automatically linked to your new account and sent for peer review.</span>
                        </li>
                        <li class="flex items-start gap-2">
                            <span class="w-5 h-5 rounded-full bg-indigo-200 text-indigo-700 flex items-center justify-center text-xs font-bold flex-shrink-0 mt-0.5">4</span>
                            <span>Our editorial team reviews your paper and notifies you of the decision by email.</span>
                        </li>
                    </ol>
                </div>

                {{-- Already logged in notice --}}
                @auth
                <div class="bg-green-50 border border-green-200 rounded-xl p-4 mb-4 flex items-center gap-3">
                    <i class="fas fa-check-circle text-green-500 text-lg flex-shrink-0"></i>
                    <div>
                        <p class="text-sm font-semibold text-green-800">You are already logged in as {{ auth()->user()->name }}</p>
                        <p class="text-xs text-green-700 mt-0.5">Your submission will be linked to your account directly.</p>
                    </div>
                </div>
                @endauth
            </div>
        </div>

        {{-- ── Navigation Buttons ──────────────────────────────────────────── --}}
        <div class="flex items-center justify-between pt-2">
            <button type="button" @click="prev()" x-show="step > 1"
                    class="inline-flex items-center gap-2 px-6 py-3 bg-gray-100 text-gray-700 rounded-xl hover:bg-gray-200 transition font-medium text-sm">
                <i class="fas fa-arrow-left"></i> Previous
            </button>
            <div x-show="step === 1" class="w-1"></div>

            <div class="flex items-center gap-3 ml-auto">
                {{-- Next button (steps 1–3) --}}
                <button type="button" @click="next()" x-show="step < totalSteps"
                        class="inline-flex items-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition font-medium text-sm shadow-sm">
                    Next Step <i class="fas fa-arrow-right"></i>
                </button>

                {{-- Submit button (step 4) --}}
                <button type="submit" x-show="step === totalSteps"
                        class="inline-flex items-center gap-2 px-8 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition font-semibold text-sm shadow-md">
                    <i class="fas fa-paper-plane"></i>
                    Submit Publication
                </button>
            </div>
        </div>

    </form>
</div>

@push('scripts')
<script>
// Review summary is populated by Alpine's populateReview() method when step 4 is reached.
// No additional JavaScript needed here.
</script>
@endpush

@endsection
