@php
    use App\Models\Application;

    $resumeReport = $user->resumeReport;
    $profile = $user->profile;
    $statusOptions = [
        Application::STATUS_APPLIED => 'Applied',
        Application::STATUS_INTERVIEW => 'Interview',
        Application::STATUS_REJECTED => 'Rejected',
        Application::STATUS_OFFER => 'Offer',
        Application::STATUS_FOLLOW_UP_NEEDED => 'Follow-up Needed',
    ];

    $analyticsCards = [
        ['label' => 'Matched jobs', 'helper' => 'All ranked roles', 'value' => $analytics['matched_jobs'], 'tone' => 'bg-teal-50 text-teal-800', 'svg' => 'target', 'url' => route('jobs.index')],
        ['label' => 'High matches', 'helper' => '75% and above', 'value' => $analytics['high_matches'], 'tone' => 'bg-emerald-50 text-emerald-800', 'svg' => 'spark', 'url' => route('jobs.index', ['match_min' => 75])],
        ['label' => 'Saved jobs', 'helper' => 'Shortlisted roles', 'value' => $analytics['saved_jobs'], 'tone' => 'bg-sky-50 text-sky-800', 'svg' => 'bookmark', 'url' => route('jobs.index', ['saved' => 1])],
        ['label' => 'Applied jobs', 'helper' => 'Tracked actions', 'value' => $analytics['applied_jobs'], 'tone' => 'bg-indigo-50 text-indigo-800', 'svg' => 'send', 'url' => route('jobs.index', ['applied' => 1])],
        ['label' => 'Follow-ups', 'helper' => 'Needs attention', 'value' => $analytics['follow_up_needed'], 'tone' => 'bg-amber-50 text-amber-800', 'svg' => 'bell', 'url' => route('jobs.index', ['application_status' => Application::STATUS_FOLLOW_UP_NEEDED])],
    ];

    $formatSalary = static fn ($job): ?string => $job->salaryLabel();
@endphp

<x-app-shell title="Applicant Dashboard" max="max-w-7xl">
    <section class="mb-6 grid gap-5 lg:grid-cols-[1fr_0.42fr]">
        <div class="surface relative overflow-hidden p-5 sm:p-7">
            <div class="absolute right-0 top-0 h-40 w-40 rounded-full bg-teal-200/30 blur-3xl"></div>
            <div class="relative">
                <p class="eyebrow">Applicant workspace</p>
                <div class="mt-3 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
                    <div>
                        <h1 class="page-title">Your remote job command center.</h1>
                        <p class="body-copy mt-3 max-w-2xl">
                            Track profile readiness, resume intelligence, saved jobs, and the best matched opportunities from one clean dashboard.
                        </p>
                    </div>

                    <a class="btn-primary shrink-0" href="{{ $nextAction['url'] }}">
                        {{ $nextAction['label'] }}
                    </a>
                </div>

                <div class="mt-7 grid gap-3 sm:grid-cols-3">
                    <div class="rounded-2xl border border-teal-100 bg-teal-50/80 p-4">
                        <p class="text-xs font-black uppercase tracking-[0.16em] text-teal-700">Profile strength</p>
                        <div class="mt-3 flex items-end justify-between gap-4">
                            <p class="text-4xl font-black text-slate-950">{{ $profileCompletion }}%</p>
                            <div class="h-2 flex-1 overflow-hidden rounded-full bg-white">
                                <div class="h-full rounded-full bg-teal-500" style="width: {{ $profileCompletion }}%"></div>
                            </div>
                        </div>
                    </div>

                    <div class="rounded-2xl border border-sky-100 bg-sky-50/80 p-4">
                        <p class="text-xs font-black uppercase tracking-[0.16em] text-sky-700">ATS score</p>
                        <p class="mt-3 text-4xl font-black text-slate-950">{{ $analytics['ats_score'] ?: '—' }}<span class="text-base text-slate-500">/100</span></p>
                    </div>

                    <div class="rounded-2xl border border-emerald-100 bg-emerald-50/80 p-4">
                        <p class="text-xs font-black uppercase tracking-[0.16em] text-emerald-700">Remote readiness</p>
                        <p class="mt-3 text-4xl font-black text-slate-950">{{ $analytics['remote_readiness_score'] ?: '—' }}<span class="text-base text-slate-500">/100</span></p>
                    </div>
                </div>
            </div>
        </div>

        <aside class="surface p-5 sm:p-6">
            <p class="eyebrow">Next best step</p>
            <h2 class="mt-3 text-2xl font-black tracking-tight text-slate-950">{{ $nextAction['label'] }}</h2>
            <p class="muted-copy mt-2">Keep your profile fresh so matching stays useful as new sources sync into the platform.</p>

            <div class="mt-5 grid gap-3">
                <a class="btn-secondary w-full justify-between" href="{{ route('profile.edit') }}">
                    Update profile
                    <span aria-hidden="true">→</span>
                </a>
                <a class="btn-secondary w-full justify-between" href="{{ route('resume.show') }}">
                    Resume analysis
                    <span aria-hidden="true">→</span>
                </a>
                <a class="btn-secondary w-full justify-between" href="{{ route('jobs.index') }}">
                    Browse matches
                    <span aria-hidden="true">→</span>
                </a>
                <a class="btn-secondary w-full justify-between" href="{{ route('applications.pipeline') }}">
                    Application pipeline
                    <span aria-hidden="true">→</span>
                </a>
                <a class="btn-secondary w-full justify-between" href="{{ route('job-alerts.preferences') }}">
                    Job alert settings
                    <span aria-hidden="true">→</span>
                </a>
            </div>
        </aside>
    </section>

    <section class="mb-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
        @foreach ($analyticsCards as $card)
            <a class="quick-link-card" href="{{ $card['url'] }}">
                <div class="flex items-center justify-between gap-3">
                    <span class="quick-link-icon {{ $card['tone'] }}">
                        @if ($card['svg'] === 'target')
                            <svg class="size-5" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Z" stroke="currentColor" stroke-width="1.8"/><path d="M12 16a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z" stroke="currentColor" stroke-width="1.8"/><path d="M12 12h.01" stroke="currentColor" stroke-width="3" stroke-linecap="round"/></svg>
                        @elseif ($card['svg'] === 'spark')
                            <svg class="size-5" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="m12 3 1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8L12 3Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/></svg>
                        @elseif ($card['svg'] === 'bookmark')
                            <svg class="size-5" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M7 4h10a1 1 0 0 1 1 1v16l-6-3-6 3V5a1 1 0 0 1 1-1Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/></svg>
                        @elseif ($card['svg'] === 'send')
                            <svg class="size-5" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="m4 12 16-8-5 16-3-7-8-1Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/></svg>
                        @else
                            <svg class="size-5" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M18 8a6 6 0 1 0-12 0c0 7-3 7-3 7h18s-3 0-3-7Z" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><path d="M10 19a2 2 0 0 0 4 0" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
                        @endif
                    </span>
                    <span class="quick-link-value" @if ($card['label'] === 'Saved jobs') data-saved-count @endif>{{ $card['value'] }}</span>
                </div>
                <p class="quick-link-title">{{ $card['label'] }}</p>
                <p class="quick-link-helper">{{ $card['helper'] }}</p>
            </a>
        @endforeach
    </section>

    <section class="mb-6 grid gap-5 lg:grid-cols-[0.68fr_0.32fr]">
        <div class="surface p-5 sm:p-6">
            <div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
                <div>
                    <p class="eyebrow">Best matches</p>
                    <h2 class="section-title mt-2">Top ranked jobs right now.</h2>
                </div>
                <a class="btn-secondary min-h-11 px-4 text-sm" href="{{ route('jobs.index') }}">View all jobs</a>
            </div>

            @if ($topJobs->isEmpty())
                <div class="mt-5 rounded-3xl border border-dashed border-slate-300 bg-slate-50 p-8 text-center">
                    <p class="text-lg font-black text-slate-950">No synced matches yet.</p>
                    <p class="muted-copy mx-auto mt-2 max-w-md">When admins add or sync active remote jobs, your best matches will appear here automatically.</p>
                </div>
            @else
                <div class="mt-5 grid gap-4">
                    @foreach ($topJobs as $job)
                        <article class="rounded-3xl border border-slate-200 bg-white p-4 shadow-sm shadow-slate-900/5 transition hover:-translate-y-0.5 hover:border-teal-200 hover:shadow-lg" data-job-card data-job-id="{{ $job->id }}">
                            <div class="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
                                <div class="min-w-0">
                                    <div class="flex flex-wrap items-center gap-2">
                                        <span class="chip-accent">{{ $job->match_score }}% match</span>
                                        <span class="chip">{{ str($job->category)->replace('-', ' ')->headline() }}</span>
                                        @if ($salary = $formatSalary($job))
                                            <span class="salary-badge">
                                                <svg class="size-4" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3v18M17 7.5c-.8-1-2.3-1.8-4.2-1.8-2.5 0-4.3 1.2-4.3 3 0 4.1 9 1.7 9 6.1 0 2-1.9 3.5-4.8 3.5-2.2 0-4-.8-5.1-2.1" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
                                                {{ $salary }}
                                            </span>
                                        @endif
                                    </div>
                                    <h3 class="mt-3 text-lg font-black tracking-tight text-slate-950">{{ $job->title }}</h3>
                                    <p class="mt-1 text-sm font-bold text-slate-500">{{ $job->company }}</p>
                                    <p class="muted-copy mt-3 line-clamp-2">{{ $job->displaySummary() ?: 'Full job context is available on the protected detail screen.' }}</p>
                                </div>

                                <div class="flex shrink-0 flex-wrap gap-2 md:flex-col">
                                    <a class="btn-secondary min-h-11 px-4 text-sm" href="{{ route('jobs.show', $job) }}">Details</a>
                                    @if (in_array($job->id, $savedJobIds, true))
                                        <form method="POST" action="{{ route('jobs.unsave', $job) }}" data-save-job-form data-job-id="{{ $job->id }}" data-save-url="{{ route('jobs.save', $job) }}" data-unsave-url="{{ route('jobs.unsave', $job) }}" data-saved="1" data-save-label="Save" data-saved-label="Saved">
                                            @csrf
                                            @method('DELETE')
                                            <button class="btn-secondary min-h-11 px-4 text-sm" type="submit" data-save-job-button aria-pressed="true">Saved</button>
                                        </form>
                                    @else
                                        <form method="POST" action="{{ route('jobs.save', $job) }}" data-save-job-form data-job-id="{{ $job->id }}" data-save-url="{{ route('jobs.save', $job) }}" data-unsave-url="{{ route('jobs.unsave', $job) }}" data-saved="0" data-save-label="Save" data-saved-label="Saved">
                                            @csrf
                                            <button class="btn-secondary min-h-11 px-4 text-sm" type="submit" data-save-job-button aria-pressed="false">Save</button>
                                        </form>
                                    @endif
                                </div>
                            </div>
                        </article>
                    @endforeach
                </div>
            @endif
        </div>

        <aside class="grid gap-5">
            <div class="surface p-5 sm:p-6">
                <p class="eyebrow">Resume intelligence</p>
                <h2 class="mt-2 text-xl font-black text-slate-950">{{ $resumeReport?->original_filename ?? 'Resume ready' }}</h2>
                <p class="muted-copy mt-2">{{ $resumeReport?->analysis['summary'] ?? 'Your ATS and remote-readiness signals feed directly into match ranking.' }}</p>

                <div class="mt-5 space-y-3">
                    @foreach ([
                        ['label' => 'Skills detected', 'value' => count($resumeReport?->extracted_skills ?? [])],
                        ['label' => 'Role suggestions', 'value' => count($resumeReport?->role_suggestions ?? [])],
                        ['label' => 'Missing keywords', 'value' => count($resumeReport?->missing_keywords ?? [])],
                    ] as $row)
                        <div class="flex items-center justify-between rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3">
                            <span class="text-sm font-bold text-slate-600">{{ $row['label'] }}</span>
                            <span class="text-lg font-black text-slate-950">{{ $row['value'] }}</span>
                        </div>
                    @endforeach
                </div>
            </div>

            <div class="surface p-5 sm:p-6">
                <p class="eyebrow">Profile snapshot</p>
                <h2 class="mt-2 text-xl font-black text-slate-950">{{ $profile?->headline ?: 'Applicant profile' }}</h2>
                <div class="mt-4 flex flex-wrap gap-2">
                    @foreach (array_slice($profile?->preferred_categories ?? [], 0, 5) as $category)
                        <span class="chip">{{ str($category)->replace('-', ' ')->headline() }}</span>
                    @endforeach
                </div>
                <a class="btn-secondary mt-5 w-full" href="{{ route('profile.edit') }}">Edit matching profile</a>
            </div>

            <div class="surface p-5 sm:p-6">
                <p class="eyebrow">Applicant tools</p>
                <div class="mt-4 grid gap-3">
                    <a class="quick-link-card" href="{{ route('resume.history') }}">
                        <div class="flex items-center justify-between gap-3">
                            <span class="text-sm font-black text-slate-950">Resume versions</span>
                            <span class="text-teal-700">→</span>
                        </div>
                        <p class="muted-copy mt-1">Compare uploaded resumes.</p>
                    </a>
                    <a class="quick-link-card" href="{{ route('applications.pipeline') }}">
                        <div class="flex items-center justify-between gap-3">
                            <span class="text-sm font-black text-slate-950">Application kanban</span>
                            <span class="text-teal-700">→</span>
                        </div>
                        <p class="muted-copy mt-1">Track statuses and follow-ups.</p>
                    </a>
                </div>
            </div>
        </aside>
    </section>

    <section class="surface p-5 sm:p-6">
        <div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
            <div>
                <p class="eyebrow">Application tracker</p>
                <h2 class="section-title mt-2">Recent apply actions.</h2>
            </div>
            <a class="btn-secondary min-h-11 px-4 text-sm" href="{{ route('jobs.index', ['applied' => 1]) }}">View applied jobs</a>
        </div>

        @if ($recentApplications->isEmpty())
            <div class="mt-5 rounded-3xl border border-dashed border-slate-300 bg-slate-50 p-8 text-center">
                <p class="text-lg font-black text-slate-950">No applications tracked yet.</p>
                <p class="muted-copy mx-auto mt-2 max-w-md">When you click Apply inside an unlocked job, RemoteMatch records it before sending you to the original source.</p>
            </div>
        @else
            <div class="mt-5 grid gap-4">
                @foreach ($recentApplications as $application)
                    <article class="rounded-3xl border border-slate-200 bg-white p-4 shadow-sm shadow-slate-900/5">
                        <div class="grid gap-4 lg:grid-cols-[1fr_0.9fr] lg:items-start">
                            <div>
                                <div class="flex flex-wrap items-center gap-2">
                                    <span class="chip-accent">{{ $statusOptions[$application->status] ?? str($application->status)->headline() }}</span>
                                    <span class="chip">{{ $application->applied_at?->diffForHumans() }}</span>
                                </div>
                                <h3 class="mt-3 text-lg font-black text-slate-950">{{ $application->importedJob?->title ?? 'Imported job' }}</h3>
                                <p class="muted-copy mt-1">{{ $application->source_attribution ?: $application->importedJob?->attribution() }}</p>
                            </div>

                            <form method="POST" action="{{ route('applications.update', $application) }}" class="grid gap-3 sm:grid-cols-2">
                                @csrf
                                @method('PATCH')
                                <select class="field-input mt-0 text-sm" name="status">
                                    @foreach ($statusOptions as $value => $label)
                                        <option value="{{ $value }}" @selected($application->status === $value)>{{ $label }}</option>
                                    @endforeach
                                </select>
                                <input class="field-input mt-0 text-sm" type="date" name="follow_up_at" value="{{ $application->follow_up_at?->format('Y-m-d') }}">
                                <textarea class="field-textarea mt-0 min-h-20 text-sm sm:col-span-2" name="notes" placeholder="Private notes">{{ $application->notes }}</textarea>
                                <button class="btn-primary min-h-11 px-4 text-sm sm:col-span-2" type="submit">Update tracker</button>
                            </form>
                        </div>
                    </article>
                @endforeach
            </div>
        @endif
    </section>
</x-app-shell>
