@php
    $categories = [
        'tech' => 'Tech',
        'design' => 'Design',
        'marketing' => 'Marketing',
        'sales' => 'Sales',
        'writing' => 'Writing',
        'support' => 'Support',
        'product' => 'Product',
        'operations' => 'Operations',
        'virtual-assistant' => 'Virtual assistant',
        'finance' => 'Finance',
        'hr' => 'HR',
        'data' => 'Data',
        'ai' => 'AI',
        'general' => 'General remote jobs',
    ];

    $selectedCategories = old('preferred_categories', $profile?->preferred_categories ?? $questionnaire?->preferred_categories ?? []);
    $preferredRoles = old('preferred_roles', $profile?->preferred_roles ?? $resumeReport?->role_suggestions ?? $questionnaire?->preferred_roles ?? []);
    $skills = old('skills', $profile?->skills ?? $resumeReport?->extracted_skills ?? $questionnaire?->skills ?? []);
    $links = old('links', $profile?->links ?? []);
@endphp

<x-app-shell title="Complete Your Profile" max="max-w-5xl">
    <section class="mb-6 surface p-5 sm:p-7">
        <div class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
            <div>
                <p class="eyebrow">Profile</p>
                <h1 class="page-title mt-2">Shape your final job matches.</h1>
                <p class="body-copy mt-3 max-w-2xl">Confirm the profile details we will use to rank jobs and prepare tracked Apply actions.</p>
            </div>

            @if (auth()->user()?->canViewMatchedJobs())
                <div class="flex shrink-0 gap-2">
                    <a class="btn-secondary min-h-11 px-4 text-sm" href="{{ route('applicant.dashboard') }}">Dashboard</a>
                    <a class="btn-secondary min-h-11 px-4 text-sm" href="{{ route('jobs.index') }}">Jobs</a>
                </div>
            @endif
        </div>
    </section>

    @if ($errors->any())
        <div class="alert-error mb-5">
            <p class="font-bold">Please fix the highlighted profile 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

    <form method="POST" action="{{ route('profile.update') }}" class="flex flex-1 flex-col" data-profile-form>
        @csrf

        <div class="grid gap-5 lg:grid-cols-[0.34fr_0.66fr]">
            <aside class="surface h-fit p-5">
                <p class="text-sm font-black uppercase tracking-wide text-slate-500">Match inputs</p>
                <div class="mt-4 space-y-3">
                    @foreach ([
                        ['Resume', $resumeReport?->isCompleted() ? 'Analyzed' : 'Pending'],
                        ['Questionnaire', $questionnaire ? 'Complete' : 'Missing'],
                        ['Profile', $profile ? 'Editing' : 'New'],
                    ] as [$label, $state])
                        <div class="flex items-center justify-between gap-3 rounded-2xl border border-slate-200 bg-white p-3">
                            <span class="text-sm font-bold text-slate-700">{{ $label }}</span>
                            <span class="chip-accent">{{ $state }}</span>
                        </div>
                    @endforeach
                </div>
            </aside>

            <div class="surface space-y-6 p-5 sm:p-7">
                <section class="space-y-4">
                    <div>
                        <h2 class="text-xl font-black text-slate-950">Account access</h2>
                        <p class="muted-copy mt-1">Your email is locked to protect account ownership. Add a username and password if you want to login without Google.</p>
                    </div>

                    <div class="grid gap-4 sm:grid-cols-2">
                        <label class="block">
                            <span class="field-label">Email address</span>
                            <input class="field-input bg-slate-50 text-slate-500" value="{{ $user->email }}" disabled>
                            <span class="mt-2 block text-xs font-semibold text-slate-400">Email cannot be changed from profile.</span>
                        </label>

                        <label class="block">
                            <span class="field-label">Username</span>
                            <input class="field-input" name="username" value="{{ old('username', $user->username) }}" placeholder="remote_candidate">
                        </label>
                    </div>

                    <div class="grid gap-4 sm:grid-cols-3">
                        @if ($user->password_set_at)
                            <label class="block">
                                <span class="field-label">Current password</span>
                                <input class="field-input" type="password" name="current_password" autocomplete="current-password">
                            </label>
                        @endif

                        <label class="block">
                            <span class="field-label">New password</span>
                            <input class="field-input" type="password" name="new_password" autocomplete="new-password">
                        </label>

                        <label class="block">
                            <span class="field-label">Confirm password</span>
                            <input class="field-input" type="password" name="new_password_confirmation" autocomplete="new-password">
                        </label>
                    </div>
                </section>

                <section class="space-y-4">
                    <div>
                        <h2 class="text-xl font-black text-slate-950">Positioning</h2>
                        <p class="muted-copy mt-1">This is the profile context used for ranking, not a public profile page.</p>
                    </div>

                    <label class="block">
                        <span class="field-label">Headline</span>
                        <input class="field-input" name="headline" value="{{ old('headline', $profile?->headline) }}" placeholder="Remote customer support lead with SaaS experience" required>
                    </label>

                    <label class="block">
                        <span class="field-label">Summary</span>
                        <textarea class="field-textarea" name="summary" placeholder="A short profile summary for matching context">{{ old('summary', $profile?->summary ?? $resumeReport?->analysis['summary'] ?? '') }}</textarea>
                    </label>
                </section>

                <section class="space-y-4">
                    <h2 class="text-xl font-black text-slate-950">Work details</h2>

                    <div class="grid gap-4 sm:grid-cols-2">
                        <label class="block">
                            <span class="field-label">Current role</span>
                            <input class="field-input" name="current_role" value="{{ old('current_role', $profile?->current_role) }}" placeholder="Marketing manager">
                        </label>

                        <label class="block">
                            <span class="field-label">Experience level</span>
                            <select class="field-input" name="experience_level">
                                @foreach (['entry' => 'Entry', 'junior' => 'Junior', 'mid' => 'Mid-level', 'senior' => 'Senior', 'lead' => 'Lead', 'manager' => 'Manager', 'executive' => 'Executive'] as $value => $label)
                                    <option value="{{ $value }}" @selected(old('experience_level', $profile?->experience_level ?? $questionnaire?->experience_level) === $value)>{{ $label }}</option>
                                @endforeach
                            </select>
                        </label>

                        <label class="block">
                            <span class="field-label">Country code</span>
                            <input class="field-input uppercase" name="country_code" maxlength="2" value="{{ old('country_code', $profile?->country_code ?? $questionnaire?->country_code) }}" placeholder="IN">
                        </label>

                        <label class="block">
                            <span class="field-label">City</span>
                            <input class="field-input" name="city" value="{{ old('city', $profile?->city) }}" placeholder="Kolkata">
                        </label>

                        <label class="block">
                            <span class="field-label">Timezone</span>
                            <input class="field-input" name="timezone" value="{{ old('timezone', $profile?->timezone ?? $questionnaire?->preferred_timezone) }}" placeholder="Asia/Kolkata">
                        </label>

                        <label class="block">
                            <span class="field-label">Availability</span>
                            <select class="field-input" name="availability">
                                @foreach (['immediate' => 'Immediate', 'two_weeks' => 'In two weeks', 'one_month' => 'In one month', 'flexible' => 'Flexible'] as $value => $label)
                                    <option value="{{ $value }}" @selected(old('availability', $profile?->availability ?? $questionnaire?->availability) === $value)>{{ $label }}</option>
                                @endforeach
                            </select>
                        </label>
                    </div>
                </section>

                <section class="space-y-4">
                    <h2 class="text-xl font-black text-slate-950">Roles and skills</h2>

                    <label class="block">
                        <span class="field-label">Preferred roles</span>
                        <textarea class="field-textarea min-h-24" data-list-source="preferred_roles" placeholder="Product manager, operations lead, virtual assistant">{{ implode(', ', $preferredRoles) }}</textarea>
                    </label>

                    <label class="block">
                        <span class="field-label">Skills</span>
                        <textarea class="field-textarea min-h-24" data-list-source="skills" placeholder="SEO, Excel, customer support, Figma">{{ implode(', ', $skills) }}</textarea>
                    </label>

                    <fieldset class="space-y-3">
                        <legend class="field-label">Preferred categories</legend>
                        <div class="grid grid-cols-2 gap-3 sm:grid-cols-3">
                            @foreach ($categories as $value => $label)
                                <label class="option-tile">
                                    <input class="option-input" type="checkbox" name="preferred_categories[]" value="{{ $value }}" @checked(in_array($value, $selectedCategories, true))>
                                    <span>{{ $label }}</span>
                                </label>
                            @endforeach
                        </div>
                    </fieldset>
                </section>

                <section class="space-y-4">
                    <h2 class="text-xl font-black text-slate-950">Compensation and links</h2>

                    <div class="grid gap-4 sm:grid-cols-2">
                        <label class="block">
                            <span class="field-label">Salary currency</span>
                            <input class="field-input uppercase" name="salary_currency" maxlength="3" value="{{ old('salary_currency', $profile?->salary_currency ?? $questionnaire?->salary_currency ?? 'USD') }}" placeholder="USD">
                        </label>

                        <label class="block">
                            <span class="field-label">Minimum monthly salary</span>
                            <input class="field-input" type="number" min="0" max="10000000" name="salary_min" value="{{ old('salary_min', $profile?->salary_min ?? $questionnaire?->salary_min) }}" placeholder="3000">
                        </label>
                    </div>

                    <div class="grid gap-3 sm:grid-cols-2">
                        <label class="option-tile">
                            <input type="hidden" name="open_to_contract" value="0">
                            <input class="option-input" type="checkbox" name="open_to_contract" value="1" @checked(old('open_to_contract', $profile?->open_to_contract ?? $questionnaire?->open_to_contract ?? true))>
                            <span>Open to contract roles</span>
                        </label>

                        <label class="option-tile">
                            <input type="hidden" name="open_to_full_time" value="0">
                            <input class="option-input" type="checkbox" name="open_to_full_time" value="1" @checked(old('open_to_full_time', $profile?->open_to_full_time ?? $questionnaire?->open_to_full_time ?? true))>
                            <span>Open to full-time roles</span>
                        </label>
                    </div>

                    <div class="space-y-3">
                        <p class="field-label">Profile links</p>
                        @for ($index = 0; $index < 3; $index++)
                            <input class="field-input mt-0" name="links[]" value="{{ $links[$index] ?? '' }}" placeholder="{{ ['LinkedIn URL', 'Portfolio URL', 'GitHub or website URL'][$index] }}">
                        @endfor
                    </div>
                </section>
            </div>
        </div>

        <div class="sticky-action">
            <button class="btn-primary w-full" type="submit">
                {{ $profile ? 'Save profile updates' : 'Complete profile' }}
            </button>
        </div>
    </form>

    <script>
        (() => {
            const form = document.querySelector('[data-profile-form]');
            if (!form) {
                return;
            }

            form.addEventListener('submit', () => {
                form.querySelectorAll('[data-list-source]').forEach((textarea) => {
                    const name = `${textarea.dataset.listSource}[]`;
                    form.querySelectorAll(`[data-generated-list="${name}"]`).forEach((input) => input.remove());

                    textarea.value
                        .split(',')
                        .map((value) => value.trim())
                        .filter(Boolean)
                        .forEach((value) => {
                            const input = document.createElement('input');
                            input.type = 'hidden';
                            input.name = name;
                            input.value = value;
                            input.dataset.generatedList = name;
                            form.appendChild(input);
                        });
                });
            });
        })();
    </script>
</x-app-shell>
