@php
    use App\Models\Application;

    $categoryOptions = $categoryOptions ?: ['tech', 'design', 'marketing', 'sales', 'writing', 'support', 'product', 'operations', 'virtual-assistant', 'finance', 'hr', 'data', 'ai', 'general'];
    $employmentOptions = $employmentOptions ?: ['full_time', 'contract', 'part_time', 'freelance'];
    $experienceOptions = $experienceOptions ?: ['entry', 'junior', 'mid', 'senior', 'lead', 'manager', 'executive'];
    $locationOptions = $locationOptions ?: ['remote', 'hybrid', 'anywhere'];
    $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';
    $formatSalary = static fn ($job): ?string => $job->salaryLabel();
    $visibleJobsLabel = $jobs->total() > 0
        ? 'Showing '.$jobs->firstItem().'-'.$jobs->lastItem().' of '.$jobs->total()
        : '0 visible';
@endphp

<x-app-shell title="Your Remote Job Matches" max="max-w-7xl">
    <section class="mb-6 grid gap-5 lg:grid-cols-[1fr_0.42fr] lg:items-stretch">
        <div class="surface relative flex h-full overflow-hidden p-5 sm:p-7">
            <div class="absolute -right-10 -top-10 size-44 rounded-full bg-teal-200/35 blur-3xl"></div>
            <div class="relative flex min-h-full flex-col justify-center">
                <p class="eyebrow">Your match workspace</p>
                <h1 class="page-title mt-2">Browse ranked remote jobs built around your profile.</h1>
                <p class="body-copy mt-3 max-w-2xl">
                    Results use your questionnaire, profile, and resume signals. Save roles, open verified apply links, and keep each application tracked from here.
                </p>
                <div class="mt-6 flex flex-wrap gap-2">
                    <span class="chip-accent">{{ $visibleJobsLabel }}</span>
                    <span class="chip">{{ $totalMatches }} total matched</span>
                    @if ($filteredMatches !== $totalMatches)
                        <span class="chip">{{ $filteredMatches }} after filters</span>
                    @endif
                    <span class="chip" data-saved-count-label>{{ count($savedJobIds) }} saved</span>
                    <span class="chip">{{ $applicationsByJobId->count() }} applied</span>
                </div>
                <div class="mt-5 flex flex-wrap gap-2">
                    <a class="btn-secondary min-h-11 px-4 text-sm" href="{{ route('applications.pipeline') }}">Application pipeline</a>
                    <a class="btn-secondary min-h-11 px-4 text-sm" href="{{ route('job-alerts.preferences') }}">Alert preferences</a>
                </div>
            </div>
        </div>

        <div class="grid h-full gap-3 sm:grid-cols-3 lg:grid-cols-1">
            <a class="quick-link-card" href="{{ route('jobs.index') }}">
                <div class="flex items-center justify-between gap-3">
                    <span class="quick-link-icon bg-teal-50 text-teal-700">
                        <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>
                    </span>
                    <span class="quick-link-value">{{ $totalMatches }}</span>
                </div>
                <p class="quick-link-title">Matched jobs</p>
                <p class="quick-link-helper">All ranked roles</p>
            </a>

            <a class="quick-link-card" href="{{ route('jobs.index', ['saved' => 1]) }}">
                <div class="flex items-center justify-between gap-3">
                    <span class="quick-link-icon bg-sky-50 text-sky-700">
                        <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>
                    </span>
                    <span class="quick-link-value" data-saved-count>{{ count($savedJobIds) }}</span>
                </div>
                <p class="quick-link-title">Saved jobs</p>
                <p class="quick-link-helper">Shortlisted roles</p>
            </a>

            <a class="quick-link-card" href="{{ route('jobs.index', ['applied' => 1]) }}">
                <div class="flex items-center justify-between gap-3">
                    <span class="quick-link-icon bg-indigo-50 text-indigo-700">
                        <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>
                    </span>
                    <span class="quick-link-value">{{ $applicationsByJobId->count() }}</span>
                </div>
                <p class="quick-link-title">Applied jobs</p>
                <p class="quick-link-helper">Tracked actions</p>
            </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 highlighted filter or 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

    <button class="btn-secondary mb-4 w-full sm:hidden" type="button" data-open-filters>
        Open filters
    </button>

    <form method="GET" action="{{ route('jobs.index') }}" class="surface mb-5 hidden gap-3 p-4 sm:grid sm:grid-cols-2 lg:grid-cols-6">
        <input class="field-input mt-0 lg:col-span-2" name="search" value="{{ $filters['search'] ?? '' }}" placeholder="Search roles, companies, skills">

        <select class="field-input mt-0" name="category">
            <option value="">All categories</option>
            @foreach ($categoryOptions as $category)
                <option value="{{ $category }}" @selected(($filters['category'] ?? '') === $category)>{{ $formatLabel($category) }}</option>
            @endforeach
        </select>

        <select class="field-input mt-0" name="employment_type">
            <option value="">All work types</option>
            @foreach ($employmentOptions as $employment)
                <option value="{{ $employment }}" @selected(($filters['employment_type'] ?? '') === $employment)>{{ $formatLabel($employment) }}</option>
            @endforeach
        </select>

        <select class="field-input mt-0" name="experience_level">
            <option value="">All levels</option>
            @foreach ($experienceOptions as $level)
                <option value="{{ $level }}" @selected(($filters['experience_level'] ?? '') === $level)>{{ $formatLabel($level) }}</option>
            @endforeach
        </select>

        <select class="field-input mt-0" name="location_type">
            <option value="">All locations</option>
            @foreach ($locationOptions as $location)
                <option value="{{ $location }}" @selected(($filters['location_type'] ?? '') === $location)>{{ $formatLabel($location) }}</option>
            @endforeach
        </select>

        <select class="field-input mt-0" name="source_id">
            <option value="">All sources</option>
            @foreach ($sourceOptions as $source)
                <option value="{{ $source->id }}" @selected((int) ($filters['source_id'] ?? 0) === $source->id)>{{ $source->name }}</option>
            @endforeach
        </select>

        <input class="field-input mt-0" type="number" min="0" max="10000000" name="salary_min" value="{{ $filters['salary_min'] ?? '' }}" placeholder="Min salary">

        <input class="field-input mt-0" type="number" min="0" max="100" name="match_min" value="{{ $filters['match_min'] ?? '' }}" placeholder="Min match %">

        <select class="field-input mt-0" name="posted_within">
            <option value="">Any posted date</option>
            @foreach ([7 => 'Last 7 days', 14 => 'Last 14 days', 30 => 'Last 30 days', 60 => 'Last 60 days'] as $days => $label)
                <option value="{{ $days }}" @selected((int) ($filters['posted_within'] ?? 0) === $days)>{{ $label }}</option>
            @endforeach
        </select>

        <select class="field-input mt-0" name="application_status">
            <option value="">Any application status</option>
            @foreach ($statusOptions as $value => $label)
                <option value="{{ $value }}" @selected(($filters['application_status'] ?? '') === $value)>{{ $label }}</option>
            @endforeach
        </select>

        <label class="option-tile min-h-12">
            <input class="option-input" type="checkbox" name="saved" value="1" @checked((bool) ($filters['saved'] ?? false))>
            <span>Saved only</span>
        </label>

        <label class="option-tile min-h-12">
            <input class="option-input" type="checkbox" name="applied" value="1" @checked((bool) ($filters['applied'] ?? false))>
            <span>Applied only</span>
        </label>

        <div class="flex gap-2 lg:col-span-2">
            <button class="btn-primary flex-1" type="submit">
                Apply filters
            </button>
            <a class="btn-secondary min-h-12 px-5" href="{{ route('jobs.index') }}">
                Clear
            </a>
        </div>
    </form>

    <div class="fixed inset-0 z-30 hidden sm:hidden" data-filter-sheet>
        <button class="absolute inset-0 bg-slate-950/30" type="button" data-close-filters aria-label="Close filters"></button>
        <div class="absolute inset-x-0 bottom-0 max-h-[88vh] overflow-y-auto rounded-t-[2rem] bg-white p-5 shadow-2xl shadow-slate-900/20">
            <div class="mb-4 flex items-center justify-between gap-3">
                <p class="text-lg font-black text-slate-950">Filters</p>
                <button class="btn-ghost min-h-10 px-3" type="button" data-close-filters>Close</button>
            </div>

            <form method="GET" action="{{ route('jobs.index') }}" class="space-y-3">
                <input class="field-input mt-0" name="search" value="{{ $filters['search'] ?? '' }}" placeholder="Search roles, companies, skills">

                <select class="field-input mt-0" name="category">
                    <option value="">All categories</option>
                    @foreach ($categoryOptions as $category)
                        <option value="{{ $category }}" @selected(($filters['category'] ?? '') === $category)>{{ $formatLabel($category) }}</option>
                    @endforeach
                </select>

                <select class="field-input mt-0" name="employment_type">
                    <option value="">All work types</option>
                    @foreach ($employmentOptions as $employment)
                        <option value="{{ $employment }}" @selected(($filters['employment_type'] ?? '') === $employment)>{{ $formatLabel($employment) }}</option>
                    @endforeach
                </select>

                <select class="field-input mt-0" name="experience_level">
                    <option value="">All levels</option>
                    @foreach ($experienceOptions as $level)
                        <option value="{{ $level }}" @selected(($filters['experience_level'] ?? '') === $level)>{{ $formatLabel($level) }}</option>
                    @endforeach
                </select>

                <select class="field-input mt-0" name="location_type">
                    <option value="">All locations</option>
                    @foreach ($locationOptions as $location)
                        <option value="{{ $location }}" @selected(($filters['location_type'] ?? '') === $location)>{{ $formatLabel($location) }}</option>
                    @endforeach
                </select>

                <select class="field-input mt-0" name="source_id">
                    <option value="">All sources</option>
                    @foreach ($sourceOptions as $source)
                        <option value="{{ $source->id }}" @selected((int) ($filters['source_id'] ?? 0) === $source->id)>{{ $source->name }}</option>
                    @endforeach
                </select>

                <input class="field-input mt-0" type="number" min="0" max="10000000" name="salary_min" value="{{ $filters['salary_min'] ?? '' }}" placeholder="Min salary">
                <input class="field-input mt-0" type="number" min="0" max="100" name="match_min" value="{{ $filters['match_min'] ?? '' }}" placeholder="Min match %">

                <select class="field-input mt-0" name="posted_within">
                    <option value="">Any posted date</option>
                    @foreach ([7 => 'Last 7 days', 14 => 'Last 14 days', 30 => 'Last 30 days', 60 => 'Last 60 days'] as $days => $label)
                        <option value="{{ $days }}" @selected((int) ($filters['posted_within'] ?? 0) === $days)>{{ $label }}</option>
                    @endforeach
                </select>

                <select class="field-input mt-0" name="application_status">
                    <option value="">Any application status</option>
                    @foreach ($statusOptions as $value => $label)
                        <option value="{{ $value }}" @selected(($filters['application_status'] ?? '') === $value)>{{ $label }}</option>
                    @endforeach
                </select>

                <label class="option-tile">
                    <input class="option-input" type="checkbox" name="saved" value="1" @checked((bool) ($filters['saved'] ?? false))>
                    <span>Saved only</span>
                </label>

                <label class="option-tile">
                    <input class="option-input" type="checkbox" name="applied" value="1" @checked((bool) ($filters['applied'] ?? false))>
                    <span>Applied only</span>
                </label>

                <button class="btn-primary w-full" type="submit">
                    Apply filters
                </button>
            </form>
        </div>
    </div>

    @if ($jobs->isEmpty())
        <section class="surface p-8 text-center">
            <div class="mx-auto flex size-16 items-center justify-center rounded-3xl bg-teal-50 text-teal-700">
                <svg class="size-8" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M10.5 19a8.5 8.5 0 1 1 6.01-2.49L21 21" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><path d="M8 11h8M12 7v8" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
            </div>
            <p class="mt-4 text-xl font-black text-slate-950">No matching jobs for these filters.</p>
            <p class="muted-copy mx-auto mt-2 max-w-md">Try clearing filters or wait for the next approved source sync. New active roles will appear here automatically.</p>
            <a class="btn-secondary mt-5" href="{{ route('jobs.index') }}">Clear filters</a>
        </section>
    @else
        <section class="grid gap-4">
            @foreach ($jobs as $job)
                @php
                    $application = $applicationsByJobId->get($job->id);
                    $isSaved = in_array($job->id, $savedJobIds, true);
                    $skills = array_slice($job->skills ?? $job->tags ?? [], 0, 5);
                @endphp

                <article class="job-card relative overflow-hidden" data-job-card data-job-id="{{ $job->id }}">
                    <div class="absolute left-0 top-0 h-full w-1.5 bg-gradient-to-b from-teal-400 via-sky-400 to-emerald-400"></div>
                    <div class="grid gap-5 lg:grid-cols-[1fr_0.34fr] lg:items-start">
                        <div class="min-w-0 pl-2">
                            <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->source)
                                    <span class="chip">{{ $job->source->name }}</span>
                                @endif
                            </div>

                            <h2 class="mt-4 text-xl font-black tracking-tight text-slate-950 sm:text-2xl">{{ $job->title }}</h2>
                            <div class="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-sm font-bold text-slate-500">
                                <span>{{ $job->company }}</span>
                                <span>{{ $formatLabel($job->location_type) }}{{ $job->country_code ? ' · '.$job->country_code : '' }}</span>
                                @if ($job->posted_at)
                                    <span>{{ $job->posted_at->diffForHumans() }}</span>
                                @endif
                            </div>

                            @if ($job->displaySummary())
                                <p class="muted-copy mt-3 max-w-3xl">{{ $job->displaySummary(320) }}</p>
                            @endif

                            <div class="mt-4 flex flex-wrap gap-2">
                                @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
                                @foreach ($skills as $skill)
                                    <span class="rounded-full bg-slate-100 px-3 py-1.5 text-xs font-bold text-slate-600">{{ $skill }}</span>
                                @endforeach
                            </div>

                            <p class="mt-4 text-xs font-bold uppercase tracking-wide text-slate-400">Source attribution: {{ $job->attribution() }}</p>
                        </div>

                        <div class="rounded-3xl border border-slate-200 bg-slate-50/70 p-4">
                            <div class="grid gap-2">
                                <a class="btn-secondary min-h-11 px-4 text-sm" href="{{ route('jobs.show', $job) }}">
                                    View details
                                </a>

                                @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 min-h-11 w-full 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 job" data-saved-label="Saved">
                                        @csrf
                                        <button class="btn-secondary min-h-11 w-full px-4 text-sm" 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 min-h-11 w-full px-5 text-sm" type="submit">
                                        {{ $application ? 'Open apply link' : 'Apply and track' }}
                                    </button>
                                </form>
                            </div>

                            @if ($application)
                                <div class="mt-4 border-t border-slate-200 pt-4">
                                    <p class="mb-3 text-xs font-black uppercase tracking-[0.16em] text-slate-500">Tracker</p>
                                    <form method="POST" action="{{ route('applications.update', $application) }}" class="grid gap-3">
                                        @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" name="notes" placeholder="Private notes">{{ $application->notes }}</textarea>
                                        <button class="btn-secondary min-h-10 px-4 text-sm" type="submit">Update status</button>
                                    </form>
                                </div>
                            @endif
                        </div>
                    </div>
                </article>
            @endforeach
        </section>

        @if ($jobs->hasPages())
            @php
                $currentPage = $jobs->currentPage();
                $lastPage = $jobs->lastPage();
                $startPage = max(1, $currentPage - 2);
                $endPage = min($lastPage, $currentPage + 2);
            @endphp

            <nav class="mt-6 rounded-3xl border border-slate-200 bg-white/90 p-3 shadow-sm shadow-slate-900/5 sm:flex sm:items-center sm:justify-between sm:gap-4" aria-label="Jobs pagination">
                <p class="px-2 py-2 text-center text-sm font-bold text-slate-500 sm:text-left">
                    Page {{ $currentPage }} of {{ $lastPage }}
                </p>

                <div class="mt-3 flex flex-wrap items-center justify-center gap-2 sm:mt-0">
                    @if ($jobs->onFirstPage())
                        <span class="pagination-button is-disabled">Previous</span>
                    @else
                        <a class="pagination-button" href="{{ $jobs->previousPageUrl() }}">Previous</a>
                    @endif

                    @if ($startPage > 1)
                        <a class="pagination-number" href="{{ $jobs->url(1) }}">1</a>
                        @if ($startPage > 2)
                            <span class="px-1 text-sm font-bold text-slate-400">...</span>
                        @endif
                    @endif

                    @for ($page = $startPage; $page <= $endPage; $page++)
                        @if ($page === $currentPage)
                            <span class="pagination-number is-current" aria-current="page">{{ $page }}</span>
                        @else
                            <a class="pagination-number" href="{{ $jobs->url($page) }}">{{ $page }}</a>
                        @endif
                    @endfor

                    @if ($endPage < $lastPage)
                        @if ($endPage < $lastPage - 1)
                            <span class="px-1 text-sm font-bold text-slate-400">...</span>
                        @endif
                        <a class="pagination-number" href="{{ $jobs->url($lastPage) }}">{{ $lastPage }}</a>
                    @endif

                    @if ($jobs->hasMorePages())
                        <a class="pagination-button" href="{{ $jobs->nextPageUrl() }}">Next</a>
                    @else
                        <span class="pagination-button is-disabled">Next</span>
                    @endif
                </div>
            </nav>
        @endif
    @endif

</x-app-shell>
