@php
    use App\Models\Application;
    use App\Models\JobAiAssistance;

    $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',
    ];

    $formatLabel = static fn (?string $value): string => $value ? str($value)->replace(['-', '_'], ' ')->headline()->toString() : 'Not specified';
    $isSaved = in_array($job->id, $savedJobIds, true);
    $summary = $job->displaySummary(620);
    $descriptionParagraphs = collect($job->displayDescriptionParagraphs())
        ->reject(fn (string $paragraph): bool => filled($summary) && trim($paragraph) === trim($summary))
        ->values()
        ->all();
    $salary = $job->salaryLabel();
    $company = filled($job->company) ? $job->company : 'Company not listed';
    $location = $formatLabel($job->location_type).($job->country_code ? ' · '.$job->country_code : '');
    $posted = $job->posted_at ? $job->posted_at->diffForHumans() : 'Recently posted';
    $coverLetter = $aiAssistances->get(JobAiAssistance::TYPE_COVER_LETTER);
    $interviewPrep = $aiAssistances->get(JobAiAssistance::TYPE_INTERVIEW_PREP);
    $aiMatchExplanation = $aiAssistances->get(JobAiAssistance::TYPE_MATCH_EXPLANATION);
@endphp

<x-app-shell title="{{ $job->title }}" max="max-w-7xl">
    <div class="mb-5 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <a class="btn-secondary min-h-11 px-4 text-sm" href="{{ route('jobs.index') }}">← Back to matched jobs</a>

        <nav class="grid grid-cols-3 gap-2 sm:flex" aria-label="Job list shortcuts">
            <a class="btn-ghost min-h-10 px-3 text-xs" href="{{ route('jobs.index') }}">Matched</a>
            <a class="btn-ghost min-h-10 px-3 text-xs" href="{{ route('jobs.index', ['saved' => 1]) }}">Saved</a>
            <a class="btn-ghost min-h-10 px-3 text-xs" href="{{ route('jobs.index', ['applied' => 1]) }}">Applied</a>
        </nav>
    </div>

    @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 highlighted tracker details.</p>
            <ul class="mt-2 list-disc space-y-1 pl-5">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <section class="grid gap-5 lg:grid-cols-[1fr_0.36fr]">
        <article class="surface overflow-hidden">
            <header class="relative overflow-hidden border-b border-slate-200 bg-[linear-gradient(135deg,#ECFEFF_0%,#F0FDFA_42%,#F8FAFC_100%)] p-5 sm:p-7">
                <div class="absolute right-0 top-0 size-52 rounded-full bg-sky-200/30 blur-3xl"></div>
                <div class="relative">
                    <div class="flex flex-wrap items-center gap-2">
                        <span class="chip-accent">{{ $job->match_score }}% match</span>
                        <span class="chip">{{ $formatLabel($job->category) }}</span>
                        @if ($job->employment_type)
                            <span class="chip">{{ $formatLabel($job->employment_type) }}</span>
                        @endif
                        @if ($job->experience_level)
                            <span class="chip">{{ $formatLabel($job->experience_level) }}</span>
                        @endif
                    </div>

                    <div class="mt-5 grid gap-5 xl:grid-cols-[1fr_0.34fr] xl:items-end">
                        <div>
                            <h1 class="page-title">{{ $job->title }}</h1>
                            <div class="mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm font-bold text-slate-600">
                                <span>{{ $company }}</span>
                                <span>{{ $location }}</span>
                                @if ($job->timezone)
                                    <span>{{ $job->timezone }}</span>
                                @endif
                                <span>{{ $posted }}</span>
                            </div>
                        </div>

                        <div class="salary-badge-strong">
                            <p class="text-xs font-black uppercase tracking-[0.16em] text-emerald-700">Compensation</p>
                            @if ($salary)
                                <p class="mt-2 text-2xl font-black tracking-tight text-emerald-950">{{ $salary }}</p>
                            @else
                                <p class="mt-2 text-lg font-black tracking-tight text-slate-800">Salary not listed</p>
                            @endif
                            <p class="mt-2 text-xs font-bold leading-5 text-slate-500">Shown when provided by the job source or detected from the imported description.</p>
                        </div>
                    </div>
                </div>
            </header>

            <div class="grid gap-5 p-5 sm:p-7">
                <section class="job-detail-section">
                    <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
                        <div>
                            <p class="eyebrow">Job snapshot</p>
                            <h2 class="section-title mt-2">Key details at a glance.</h2>
                        </div>
                        <span class="chip">{{ $job->attribution() }}</span>
                    </div>

                    <div class="mt-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                        <div class="job-detail-fact">
                            <p class="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Company</p>
                            <p class="mt-2 text-base font-black text-slate-950">{{ $company }}</p>
                        </div>

                        <div class="job-detail-fact">
                            <p class="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Location</p>
                            <p class="mt-2 text-base font-black text-slate-950">{{ $location }}</p>
                        </div>

                        <div class="job-detail-fact">
                            <p class="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Work type</p>
                            <p class="mt-2 text-base font-black text-slate-950">{{ $formatLabel($job->employment_type) }}</p>
                        </div>

                        <div class="job-detail-fact">
                            <p class="text-xs font-black uppercase tracking-[0.16em] text-slate-500">Posted</p>
                            <p class="mt-2 text-base font-black text-slate-950">{{ $posted }}</p>
                        </div>
                    </div>
                </section>

                @if ($summary)
                    <section class="job-detail-section bg-[linear-gradient(135deg,#F8FAFC,#ECFEFF)]">
                        <p class="eyebrow">Role overview</p>
                        <p class="mt-3 max-w-4xl text-lg leading-8 text-slate-700">{{ $summary }}</p>
                    </section>
                @endif

                <section class="job-detail-section bg-[linear-gradient(135deg,#F0FDFA,#FFFFFF)]">
                    <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
                        <div>
                            <p class="eyebrow">Why this matches you</p>
                            <h2 class="section-title mt-2">Profile signals behind this ranking.</h2>
                        </div>
                        <span class="chip-accent">{{ $job->match_score }}% match</span>
                    </div>

                    <div class="mt-5 grid gap-3">
                        @foreach ($matchReasons as $reason)
                            <div class="flex gap-3 rounded-2xl border border-teal-100 bg-white/80 p-4 text-sm leading-6 text-slate-700">
                                <span class="mt-1 flex size-5 shrink-0 items-center justify-center rounded-full bg-teal-100 text-xs font-black text-teal-800">✓</span>
                                <p>{{ $reason }}</p>
                            </div>
                        @endforeach
                    </div>
                </section>

                <section class="job-detail-section">
                    <div class="flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
                        <div>
                            <p class="eyebrow">Full role details</p>
                            <h2 class="section-title mt-2">Responsibilities, requirements, and context.</h2>
                        </div>
                        <span class="chip">External apply URL hidden</span>
                    </div>

                    <div class="job-detail-description mt-5">
                        @forelse ($descriptionParagraphs as $paragraph)
                            @php
                                $isBullet = str($paragraph)->startsWith('- ');
                                $bulletText = $isBullet ? str($paragraph)->after('- ')->trim()->toString() : $paragraph;
                                $isHeading = ! $isBullet && mb_strlen($paragraph) <= 90 && ! str_contains($paragraph, '.');
                            @endphp

                            @if ($isBullet)
                                <div class="flex gap-3 rounded-2xl border border-teal-100 bg-teal-50/60 p-4 text-slate-700">
                                    <span class="mt-2 size-2 shrink-0 rounded-full bg-teal-500"></span>
                                    <p class="leading-7">{{ $bulletText }}</p>
                                </div>
                            @elseif ($isHeading)
                                <h3 class="rounded-2xl border border-slate-200 bg-slate-100/80 px-4 py-3 text-sm font-black uppercase tracking-[0.14em] text-slate-700">{{ $paragraph }}</h3>
                            @else
                                <p>{{ $paragraph }}</p>
                            @endif
                        @empty
                            <p>The imported source did not provide a long description. Use the tracked apply action to continue on the original employer or source website.</p>
                        @endforelse
                    </div>
                </section>

                <section class="grid gap-5 md:grid-cols-2">
                    <div class="job-detail-section">
                        <p class="eyebrow">Skills</p>
                        <div class="mt-4 flex flex-wrap gap-2">
                            @forelse ($job->skills ?? [] as $skill)
                                <span class="chip">{{ $skill }}</span>
                            @empty
                                <span class="muted-copy">No skills were provided by this source.</span>
                            @endforelse
                        </div>
                    </div>

                    <div class="job-detail-section">
                        <p class="eyebrow">Tags</p>
                        <div class="mt-4 flex flex-wrap gap-2">
                            @forelse ($job->tags ?? [] as $tag)
                                <span class="chip">{{ $tag }}</span>
                            @empty
                                <span class="muted-copy">No tags were provided by this source.</span>
                            @endforelse
                        </div>
                    </div>
                </section>
            </div>
        </article>

        <aside class="grid h-fit gap-5 lg:sticky lg:top-6">
            <div class="surface p-5 sm:p-6">
                <p class="eyebrow">Actions</p>
                <h2 class="mt-2 text-xl font-black text-slate-950">Save or apply with tracking.</h2>
                <p class="muted-copy mt-2">RemoteMatch records the action before sending you to the original job source in a new tab.</p>

                <div class="mt-5 grid gap-3">
                    @if ($isSaved)
                        <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 job" data-saved-label="Saved">
                            @csrf
                            @method('DELETE')
                            <button class="btn-secondary w-full" 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 job" data-saved-label="Saved">
                            @csrf
                            <button class="btn-secondary w-full" type="submit" data-save-job-button aria-pressed="false">Save job</button>
                        </form>
                    @endif

                    <form method="POST" action="{{ route('jobs.apply', $job) }}" target="_blank" rel="noopener">
                        @csrf
                        <button class="btn-primary w-full" type="submit">{{ $application ? 'Open apply link again' : 'Apply and track' }}</button>
                    </form>
                </div>
            </div>

            <div class="surface p-5 sm:p-6">
                <p class="eyebrow">Your job lists</p>
                <div class="mt-4 grid gap-3">
                    <a class="quick-link-card" href="{{ route('jobs.index') }}">
                        <div class="flex items-center justify-between gap-3">
                            <span class="text-sm font-black text-slate-950">Matched jobs</span>
                            <span class="text-teal-700">→</span>
                        </div>
                        <p class="muted-copy mt-1">All ranked opportunities.</p>
                    </a>

                    <a class="quick-link-card" href="{{ route('jobs.index', ['saved' => 1]) }}">
                        <div class="flex items-center justify-between gap-3">
                            <span class="text-sm font-black text-slate-950">Saved jobs</span>
                            <span class="text-teal-700">→</span>
                        </div>
                        <p class="muted-copy mt-1">Jobs you marked for later.</p>
                    </a>

                    <a class="quick-link-card" href="{{ route('jobs.index', ['applied' => 1]) }}">
                        <div class="flex items-center justify-between gap-3">
                            <span class="text-sm font-black text-slate-950">Applied jobs</span>
                            <span class="text-teal-700">→</span>
                        </div>
                        <p class="muted-copy mt-1">Tracked apply actions.</p>
                    </a>
                </div>
            </div>

            <div class="surface p-5 sm:p-6">
                <p class="eyebrow">Source attribution</p>
                <p class="mt-3 text-sm font-bold leading-6 text-slate-700">{{ $job->attribution() }}</p>
                <p class="muted-copy mt-2">External URLs are intentionally hidden until the tracked apply action redirects server-side.</p>
            </div>

            @if ($application)
                <div class="surface p-5 sm:p-6">
                    <p class="eyebrow">Application tracker</p>
                    <h2 class="mt-2 text-xl font-black text-slate-950">{{ $statusOptions[$application->status] ?? str($application->status)->headline() }}</h2>
                    <p class="muted-copy mt-2">Applied {{ $application->applied_at?->diffForHumans() }}.</p>

                    <form method="POST" action="{{ route('applications.update', $application) }}" class="mt-5 grid gap-3">
                        @csrf
                        @method('PATCH')
                        <label>
                            <span class="field-label">Status</span>
                            <select class="field-input" name="status">
                                @foreach ($statusOptions as $value => $label)
                                    <option value="{{ $value }}" @selected($application->status === $value)>{{ $label }}</option>
                                @endforeach
                            </select>
                        </label>

                        <label>
                            <span class="field-label">Follow-up date</span>
                            <input class="field-input" type="date" name="follow_up_at" value="{{ $application->follow_up_at?->format('Y-m-d') }}">
                        </label>

                        <label>
                            <span class="field-label">Private notes</span>
                            <textarea class="field-textarea" name="notes" placeholder="Add interview notes or follow-up context">{{ $application->notes }}</textarea>
                        </label>

                        <button class="btn-secondary" type="submit">Update tracker</button>
                    </form>
                </div>
            @endif

            <div class="surface p-5 sm:p-6">
                <p class="eyebrow">Private job notes</p>
                <form method="POST" action="{{ route('jobs.notes.update', $job) }}" class="mt-4 grid gap-3" data-job-note-form>
                    @csrf
                    @method('PATCH')
                    <textarea class="field-textarea mt-0" name="body" placeholder="Add your thoughts, questions, recruiter details, or follow-up context.">{{ $jobNote?->body }}</textarea>
                    <button class="btn-secondary" type="submit" data-job-note-button>Save note</button>
                    <p class="hidden text-xs font-bold text-teal-700" data-job-note-status></p>
                </form>
            </div>

            <div class="surface p-5 sm:p-6">
                <p class="eyebrow">AI job assistant</p>
                <h2 class="mt-2 text-xl font-black text-slate-950">Generate job-specific help.</h2>
                <p class="muted-copy mt-2">Uses your profile, resume analysis, and this job. Outputs are editable guidance, not guarantees.</p>

                <div class="mt-5 grid gap-4">
                    @foreach ([
                        JobAiAssistance::TYPE_COVER_LETTER => ['label' => 'Cover letter', 'button' => 'Generate cover letter', 'record' => $coverLetter],
                        JobAiAssistance::TYPE_INTERVIEW_PREP => ['label' => 'Interview prep', 'button' => 'Generate interview questions', 'record' => $interviewPrep],
                        JobAiAssistance::TYPE_MATCH_EXPLANATION => ['label' => 'AI match explanation', 'button' => 'Generate AI explanation', 'record' => $aiMatchExplanation],
                    ] as $type => $item)
                        <div class="rounded-3xl border border-slate-200 bg-slate-50 p-4" data-ai-panel="{{ $type }}">
                            <div class="flex items-center justify-between gap-3">
                                <p class="text-sm font-black text-slate-950">{{ $item['label'] }}</p>
                                @if ($item['record']?->generated_at)
                                    <span class="text-xs font-bold text-slate-400">{{ $item['record']->generated_at->diffForHumans() }}</span>
                                @endif
                            </div>

                            <div class="mt-3 whitespace-pre-line rounded-2xl border border-slate-200 bg-white p-4 text-sm leading-6 text-slate-700" data-ai-output>
                                {{ $item['record']?->content ?: 'Not generated yet.' }}
                            </div>

                            <form method="POST" action="{{ route('jobs.ai.store', $job) }}" class="mt-3" data-ai-assist-form data-ai-type="{{ $type }}">
                                @csrf
                                <input type="hidden" name="type" value="{{ $type }}">
                                <input type="hidden" name="regenerate" value="{{ $item['record'] ? 1 : 0 }}">
                                <button class="btn-secondary w-full" type="submit" data-ai-assist-button>
                                    {{ $item['record'] ? 'Regenerate' : $item['button'] }}
                                </button>
                                <p class="mt-2 hidden text-xs font-bold text-rose-700" data-ai-error></p>
                            </form>
                        </div>
                    @endforeach
                </div>
            </div>
        </aside>
    </section>
</x-app-shell>
