@php
    $isRunning = $resumeReport && in_array($resumeReport->status, [\App\Models\ResumeReport::STATUS_PENDING, \App\Models\ResumeReport::STATUS_PROCESSING], true);
    $isCompleted = $resumeReport?->isCompleted();
    $hasFailed = $resumeReport?->hasFailed();
@endphp

<x-app-shell title="Resume Analysis" max="max-w-5xl">
    <section class="mb-6 surface relative overflow-hidden p-5 sm:p-7">
        <div class="absolute right-0 top-0 size-44 rounded-full bg-sky-200/30 blur-3xl"></div>
        <div class="relative">
            <p class="eyebrow">Resume intelligence</p>
            <h1 class="page-title mt-2">Upload once. Watch analysis update live.</h1>
            <p class="body-copy mt-3 max-w-2xl">
                We analyze your resume for ATS strength, remote-readiness, extracted skills, role suggestions, missing keywords, and practical improvements.
            </p>
            <a class="btn-secondary mt-5" href="{{ route('resume.history') }}">View resume history</a>
        </div>
    </section>

    @if (session('status'))
        <div class="alert-success mb-5">
            {{ session('status') }}
        </div>
    @endif

    @if ($errors->any())
        <div class="alert-error mb-5">
            <p class="font-bold">Please fix the upload.</p>
            <ul class="mt-2 list-disc space-y-1 pl-5">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <div class="alert-success mb-5 hidden" data-upload-success></div>
    <div class="alert-error mb-5 hidden" data-upload-error></div>

    <section
        class="grid gap-5 lg:grid-cols-[0.9fr_1.1fr]"
        data-resume-page
        data-status-url="{{ route('resume.status') }}"
        data-report-url="{{ route('resume.report') }}"
    >
        <div class="surface p-5 sm:p-6">
            <div class="mb-5">
                <p class="text-sm font-black uppercase tracking-wide text-slate-500">Current file</p>
                <p class="mt-2 break-words text-xl font-black text-slate-950" data-current-filename>
                    {{ $resumeReport?->original_filename ?? 'No resume uploaded yet.' }}
                </p>
                <p class="mt-1 text-sm text-slate-500">
                    Status:
                    <span class="font-black text-slate-800" data-current-status>
                        {{ $resumeReport ? str($resumeReport->status)->headline() : 'Waiting for upload' }}
                    </span>
                </p>
            </div>

            <div class="{{ $isRunning ? '' : 'hidden' }} soft-panel p-4" data-progress-panel>
                <div class="h-3 w-full overflow-hidden rounded-full bg-slate-200">
                    <div class="h-full w-1/2 animate-pulse rounded-full bg-teal-500"></div>
                </div>
                <p class="muted-copy mt-3" data-analysis-state>
                    Analysis is queued or running. Keep this page open; it will update automatically.
                </p>
            </div>

            <div class="{{ $hasFailed ? '' : 'hidden' }} alert-error mt-4" data-failure-box>
                {{ $resumeReport?->failure_reason }}
            </div>

            <div class="{{ $isCompleted ? '' : 'hidden' }} mt-5" data-score-panel>
                <div class="grid gap-3 sm:grid-cols-2">
                    <div class="metric-card">
                        <p class="muted-copy">ATS score</p>
                        <p class="mt-1 text-3xl font-black text-slate-950"><span data-ats-score>{{ $resumeReport?->ats_score ?? 0 }}</span>/100</p>
                    </div>
                    <div class="metric-card">
                        <p class="muted-copy">Remote-readiness</p>
                        <p class="mt-1 text-3xl font-black text-slate-950"><span data-readiness-score>{{ $resumeReport?->remote_readiness_score ?? 0 }}</span>/100</p>
                    </div>
                </div>

                <a class="btn-primary mt-5 w-full" href="{{ route('profile.edit') }}" data-profile-link>
                    Continue to profile
                </a>
            </div>
        </div>

        <div class="surface p-5 sm:p-6">
            <form method="POST" action="{{ route('resume.store') }}" enctype="multipart/form-data" class="space-y-4" data-resume-upload-form>
                @csrf

                <label class="block">
                    <span class="field-label">Resume file</span>
                    <input class="mt-2 block w-full cursor-pointer rounded-2xl border border-slate-200 bg-white text-sm text-slate-600 shadow-sm shadow-slate-900/5 file:mr-4 file:min-h-12 file:border-0 file:bg-slate-950 file:px-4 file:text-sm file:font-black file:text-white hover:file:bg-slate-800" type="file" name="resume" accept=".pdf,.doc,.docx,.txt" required>
                </label>

                <div class="alert-warn">
                    PDF, DOC, DOCX, and TXT uploads are accepted. DOCX and TXT can be extracted in PHP; PDF and legacy DOC extraction require configured server binaries on your host.
                </div>

                <div class="grid gap-3 sm:grid-cols-3">
                    @foreach (['ATS score', 'Skills', 'Remote fit'] as $item)
                        <div class="soft-panel p-4">
                            <p class="text-sm font-black text-slate-800">{{ $item }}</p>
                            <p class="mt-1 text-xs font-semibold text-slate-500">Generated after upload</p>
                        </div>
                    @endforeach
                </div>

                <button class="btn-primary w-full" type="submit" data-upload-button>
                    Upload and analyze
                </button>
            </form>
        </div>
    </section>

    <section class="mt-5 grid gap-5 lg:grid-cols-2">
        <div class="surface p-5 sm:p-6">
            <p class="eyebrow">Detected signals</p>
            <p class="muted-copy mt-2" data-summary>{{ $resumeReport?->analysis['summary'] ?? 'Resume summary will appear here after analysis completes.' }}</p>

            <div class="mt-5 space-y-5">
                <div>
                    <p class="field-label">Extracted skills</p>
                    <div class="mt-3 flex flex-wrap gap-2" data-skills-list>
                        @forelse ($resumeReport?->extracted_skills ?? [] as $skill)
                            <span class="chip">{{ $skill }}</span>
                        @empty
                            <span class="muted-copy">Waiting for analysis.</span>
                        @endforelse
                    </div>
                </div>

                <div>
                    <p class="field-label">Role suggestions</p>
                    <div class="mt-3 flex flex-wrap gap-2" data-roles-list>
                        @forelse ($resumeReport?->role_suggestions ?? [] as $role)
                            <span class="chip-accent">{{ $role }}</span>
                        @empty
                            <span class="muted-copy">Waiting for analysis.</span>
                        @endforelse
                    </div>
                </div>
            </div>
        </div>

        <div class="surface p-5 sm:p-6">
            <p class="eyebrow">Improvement plan</p>
            <div class="mt-5 grid gap-4">
                <div class="rounded-3xl border border-slate-200 bg-slate-50 p-4">
                    <p class="field-label">Missing keywords</p>
                    <div class="mt-3 flex flex-wrap gap-2" data-keywords-list>
                        @forelse ($resumeReport?->missing_keywords ?? [] as $keyword)
                            <span class="chip">{{ $keyword }}</span>
                        @empty
                            <span class="muted-copy">Waiting for analysis.</span>
                        @endforelse
                    </div>
                </div>

                <div class="rounded-3xl border border-slate-200 bg-slate-50 p-4">
                    <p class="field-label">Resume improvements</p>
                    <ul class="mt-3 space-y-2 text-sm leading-6 text-slate-600" data-improvements-list>
                        @forelse ($resumeReport?->resume_improvements ?? [] as $improvement)
                            <li class="rounded-2xl bg-white px-3 py-2 shadow-sm shadow-slate-900/5">{{ $improvement }}</li>
                        @empty
                            <li class="muted-copy">Waiting for analysis.</li>
                        @endforelse
                    </ul>
                </div>
            </div>
        </div>
    </section>

    <script>
        (() => {
            const page = document.querySelector('[data-resume-page]');
            const form = document.querySelector('[data-resume-upload-form]');

            if (!page || !form) {
                return;
            }

            const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
            const successBox = document.querySelector('[data-upload-success]');
            const errorBox = document.querySelector('[data-upload-error]');
            const button = document.querySelector('[data-upload-button]');
            const progressPanel = document.querySelector('[data-progress-panel]');
            const failureBox = document.querySelector('[data-failure-box]');
            const scorePanel = document.querySelector('[data-score-panel]');
            const currentFilename = document.querySelector('[data-current-filename]');
            const currentStatus = document.querySelector('[data-current-status]');
            const analysisState = document.querySelector('[data-analysis-state]');
            const summary = document.querySelector('[data-summary]');
            let pollTimer = null;

            const setText = (selector, value) => {
                const element = document.querySelector(selector);
                if (element) {
                    element.textContent = value ?? '';
                }
            };

            const showBox = (box, message) => {
                if (!box) {
                    return;
                }

                box.textContent = message;
                box.classList.remove('hidden');
            };

            const hideBox = (box) => {
                if (box) {
                    box.classList.add('hidden');
                    box.textContent = '';
                }
            };

            const renderChips = (selector, values, accent = false) => {
                const container = document.querySelector(selector);
                if (!container) {
                    return;
                }

                container.innerHTML = '';

                if (!values || values.length === 0) {
                    const empty = document.createElement('span');
                    empty.className = 'muted-copy';
                    empty.textContent = 'Waiting for analysis.';
                    container.appendChild(empty);
                    return;
                }

                values.forEach((value) => {
                    const chip = document.createElement('span');
                    chip.className = accent ? 'chip-accent' : 'chip';
                    chip.textContent = value;
                    container.appendChild(chip);
                });
            };

            const renderList = (selector, values) => {
                const container = document.querySelector(selector);
                if (!container) {
                    return;
                }

                container.innerHTML = '';

                if (!values || values.length === 0) {
                    const empty = document.createElement('li');
                    empty.className = 'muted-copy';
                    empty.textContent = 'Waiting for analysis.';
                    container.appendChild(empty);
                    return;
                }

                values.forEach((value) => {
                    const item = document.createElement('li');
                    item.className = 'rounded-2xl bg-white px-3 py-2 shadow-sm shadow-slate-900/5';
                    item.textContent = value;
                    container.appendChild(item);
                });
            };

            const renderResume = (resume) => {
                if (!resume) {
                    return;
                }

                currentFilename.textContent = resume.filename ?? 'Resume uploaded';
                currentStatus.textContent = resume.status_label ?? resume.status ?? 'Processing';
                setText('[data-ats-score]', resume.ats_score ?? 0);
                setText('[data-readiness-score]', resume.remote_readiness_score ?? 0);
                summary.textContent = resume.summary ?? 'Resume summary will appear here after analysis completes.';
                renderChips('[data-skills-list]', resume.extracted_skills);
                renderChips('[data-roles-list]', resume.role_suggestions, true);
                renderChips('[data-keywords-list]', resume.missing_keywords);
                renderList('[data-improvements-list]', resume.resume_improvements);

                if (resume.has_failed) {
                    progressPanel.classList.add('hidden');
                    scorePanel.classList.add('hidden');
                    showBox(failureBox, resume.failure_reason || 'Resume analysis failed. Please try uploading again.');
                    stopPolling();
                    return;
                }

                hideBox(failureBox);

                if (resume.is_completed) {
                    progressPanel.classList.add('hidden');
                    scorePanel.classList.remove('hidden');
                    stopPolling();
                    return;
                }

                progressPanel.classList.remove('hidden');
                scorePanel.classList.add('hidden');
                analysisState.textContent = 'Analysis is queued or running. Keep this page open; it will update automatically.';
                startPolling();
            };

            const stopPolling = () => {
                if (pollTimer) {
                    window.clearInterval(pollTimer);
                    pollTimer = null;
                }
            };

            window.addEventListener('remotematch:before-page-swap', stopPolling, { once: true });

            const poll = async () => {
                const response = await fetch(page.dataset.statusUrl, {
                    headers: {
                        'Accept': 'application/json',
                    },
                });

                if (!response.ok) {
                    return;
                }

                const payload = await response.json();
                renderResume(payload.resume);
            };

            const startPolling = () => {
                if (pollTimer) {
                    return;
                }

                pollTimer = window.setInterval(poll, 2500);
            };

            form.addEventListener('submit', async (event) => {
                event.preventDefault();
                hideBox(successBox);
                hideBox(errorBox);
                hideBox(failureBox);

                button.disabled = true;
                button.textContent = 'Uploading...';

                try {
                    const response = await fetch(form.action, {
                        method: 'POST',
                        body: new FormData(form),
                        headers: {
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': token,
                        },
                    });

                    const payload = await response.json();

                    if (!response.ok) {
                        const firstError = payload.errors ? Object.values(payload.errors).flat()[0] : payload.message;
                        throw new Error(firstError || 'Resume upload failed.');
                    }

                    showBox(successBox, payload.message || 'Resume uploaded. Analysis has started.');
                    form.reset();
                    renderResume(payload.resume);
                    await poll();
                } catch (error) {
                    showBox(errorBox, error.message || 'Resume upload failed.');
                } finally {
                    button.disabled = false;
                    button.textContent = 'Upload and analyze';
                }
            });

            @if ($isRunning)
                startPolling();
            @endif
        })();
    </script>
</x-app-shell>
