@php
    $categories = [
        'tech' => ['Tech', 'Engineering, QA, security'],
        'design' => ['Design', 'UI, product, creative'],
        'marketing' => ['Marketing', 'Growth, SEO, lifecycle'],
        'sales' => ['Sales', 'SDR, AE, partnerships'],
        'writing' => ['Writing', 'Content, copy, editing'],
        'support' => ['Support', 'Customer support, success'],
        'product' => ['Product', 'PM, product ops'],
        'operations' => ['Operations', 'Processes, admin, ops'],
        'virtual-assistant' => ['Virtual Assistant', 'Founder and team support'],
        'finance' => ['Finance', 'Accounting, analysis'],
        'hr' => ['HR', 'Recruiting, people ops'],
        'data' => ['Data', 'Analytics, BI, research'],
        'ai' => ['AI', 'AI ops, prompts, automation'],
        'general' => ['General Remote Jobs', 'Flexible remote roles'],
    ];

    $roles = [
        'Software Developer',
        'UI/UX Designer',
        'Digital Marketer',
        'Sales Representative',
        'Content Writer',
        'Customer Support Specialist',
        'Product Manager',
        'Operations Coordinator',
        'Virtual Assistant',
        'Finance Analyst',
        'HR Recruiter',
        'Data Analyst',
        'AI Specialist',
        'General Remote Assistant',
    ];

    $skills = [
        'Remote communication',
        'Project management',
        'Customer support',
        'Sales outreach',
        'SEO',
        'Content writing',
        'Figma',
        'Laravel',
        'React',
        'Excel',
        'Data analysis',
        'Recruiting',
        'Bookkeeping',
        'AI tools',
        'Operations',
        'CRM',
        'Email support',
        'Copywriting',
        'Product strategy',
        'Virtual assistance',
    ];

    $experienceLevels = [
        'entry' => 'Entry',
        'junior' => 'Junior',
        'mid' => 'Mid-level',
        'senior' => 'Senior',
        'lead' => 'Lead',
        'manager' => 'Manager',
        'executive' => 'Executive',
    ];

    $availabilityOptions = [
        'immediate' => 'Immediate',
        'two_weeks' => 'In two weeks',
        'one_month' => 'In one month',
        'flexible' => 'Flexible',
    ];

    $locations = [
        'IN' => ['India', 'Asia/Kolkata'],
        'US' => ['United States', 'America/New_York'],
        'GB' => ['United Kingdom', 'Europe/London'],
        'CA' => ['Canada', 'America/New_York'],
        'AU' => ['Australia', 'Australia/Sydney'],
        'DE' => ['Germany', 'Europe/Berlin'],
        'SG' => ['Singapore', 'Asia/Singapore'],
        'AE' => ['United Arab Emirates', 'UTC'],
    ];

    $salaryRanges = [
        0 => 'Open / flexible',
        1000 => '$1,000+ monthly',
        2500 => '$2,500+ monthly',
        5000 => '$5,000+ monthly',
        8000 => '$8,000+ monthly',
    ];

    $selectedCategories = old('preferred_categories', []);
    $selectedRoles = old('preferred_roles', []);
    $selectedSkills = old('skills', []);
    $selectedCountry = old('country_code', 'IN');
    $selectedTimezone = old('preferred_timezone', $locations[$selectedCountry][1] ?? 'Asia/Kolkata');
@endphp

<x-app-shell title="Remote Job Match Questionnaire" max="max-w-5xl">
    <section class="mx-auto w-full max-w-3xl">
        <div class="surface sticky top-3 z-10 mb-5 overflow-hidden p-4 sm:p-5">
            <div class="flex items-center justify-between gap-4">
                <div>
                    <p class="eyebrow">Questionnaire</p>
                    <h1 class="mt-1 text-2xl font-black tracking-tight text-slate-950 sm:text-3xl">Build your remote match profile.</h1>
                </div>
                <div class="rounded-2xl bg-teal-50 px-3 py-2 text-sm font-black text-teal-800">
                    <span data-step-label>1</span>/4
                </div>
            </div>

            <div class="mt-4">
                <div class="flex items-center justify-between text-xs font-black uppercase tracking-[0.16em] text-slate-400">
                    <span>Progress</span>
                    <span data-progress-label>0% complete</span>
                </div>
                <div class="mt-2 h-3 overflow-hidden rounded-full bg-slate-200">
                    <div class="h-full rounded-full bg-gradient-to-r from-teal-500 to-sky-400 transition-all duration-300" style="width: 0%" data-progress-fill></div>
                </div>
                <div class="mt-3 grid grid-cols-4 gap-2" aria-hidden="true">
                    @for ($index = 1; $index <= 4; $index++)
                        <span class="h-2 rounded-full bg-slate-200 transition" data-progress-segment></span>
                    @endfor
                </div>
            </div>
        </div>

        @if ($errors->any())
            <div class="alert-error mb-5">
                <p class="font-bold">Please fix the highlighted answers.</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('questionnaire.store') }}" class="flex flex-1 flex-col" data-questionnaire-form>
            @csrf

            <input type="hidden" name="answers[source]" value="questionnaire_v2_multiple_choice">
            <input type="hidden" name="answers[mode]" value="multiple_choice">

            <div class="surface min-h-[34rem] flex-1 p-4 sm:p-7">
                <fieldset class="space-y-5" data-step="1">
                    <div>
                        <legend class="section-title">Choose your remote job categories.</legend>
                        <p class="muted-copy mt-1">Pick 1 to 8 paths. These guide your first locked preview and later job ranking.</p>
                    </div>

                    <div class="hidden rounded-2xl border border-rose-200 bg-rose-50 p-3 text-sm font-bold text-rose-900" data-step-error></div>

                    <div class="grid gap-3 sm:grid-cols-2" data-choice-group data-min="1" data-max="8" data-error="Choose at least one category and no more than eight.">
                        @foreach ($categories as $value => [$label, $description])
                            <label class="option-tile min-h-20 items-start">
                                <input class="option-input mt-1" type="checkbox" name="preferred_categories[]" value="{{ $value }}" @checked(in_array($value, $selectedCategories, true))>
                                <span>
                                    <span class="block">{{ $label }}</span>
                                    <span class="mt-1 block text-xs font-semibold leading-5 text-slate-500">{{ $description }}</span>
                                </span>
                            </label>
                        @endforeach
                    </div>
                </fieldset>

                <fieldset class="hidden space-y-6" data-step="2">
                    <div>
                        <legend class="section-title">Choose roles and strengths.</legend>
                        <p class="muted-copy mt-1">No typing needed. Pick the roles and skills closest to your profile.</p>
                    </div>

                    <div class="hidden rounded-2xl border border-rose-200 bg-rose-50 p-3 text-sm font-bold text-rose-900" data-step-error></div>

                    <section>
                        <p class="field-label mb-3">Preferred roles</p>
                        <div class="grid gap-3 sm:grid-cols-2" data-choice-group data-min="1" data-max="12" data-error="Choose at least one preferred role.">
                            @foreach ($roles as $role)
                                <label class="option-tile">
                                    <input class="option-input" type="checkbox" name="preferred_roles[]" value="{{ $role }}" @checked(in_array($role, $selectedRoles, true))>
                                    <span>{{ $role }}</span>
                                </label>
                            @endforeach
                        </div>
                    </section>

                    <section>
                        <p class="field-label mb-3">Skills</p>
                        <div class="grid gap-3 sm:grid-cols-2" data-choice-group data-min="1" data-max="30" data-error="Choose at least one skill.">
                            @foreach ($skills as $skill)
                                <label class="option-tile">
                                    <input class="option-input" type="checkbox" name="skills[]" value="{{ $skill }}" @checked(in_array($skill, $selectedSkills, true))>
                                    <span>{{ $skill }}</span>
                                </label>
                            @endforeach
                        </div>
                    </section>
                </fieldset>

                <fieldset class="hidden space-y-6" data-step="3">
                    <div>
                        <legend class="section-title">Choose your work setup.</legend>
                        <p class="muted-copy mt-1">These choices help rank jobs by level, timing, and remote compatibility.</p>
                    </div>

                    <div class="hidden rounded-2xl border border-rose-200 bg-rose-50 p-3 text-sm font-bold text-rose-900" data-step-error></div>

                    <section>
                        <p class="field-label mb-3">Experience level</p>
                        <div class="grid grid-cols-2 gap-3 sm:grid-cols-3" data-choice-group data-min="1" data-error="Choose your experience level.">
                            @foreach ($experienceLevels as $value => $label)
                                <label class="option-tile">
                                    <input class="option-input" type="radio" name="experience_level" value="{{ $value }}" @checked(old('experience_level', 'mid') === $value)>
                                    <span>{{ $label }}</span>
                                </label>
                            @endforeach
                        </div>
                    </section>

                    <section>
                        <p class="field-label mb-3">Availability</p>
                        <div class="grid gap-3 sm:grid-cols-2" data-choice-group data-min="1" data-error="Choose your availability.">
                            @foreach ($availabilityOptions as $value => $label)
                                <label class="option-tile">
                                    <input class="option-input" type="radio" name="availability" value="{{ $value }}" @checked(old('availability', 'immediate') === $value)>
                                    <span>{{ $label }}</span>
                                </label>
                            @endforeach
                        </div>
                    </section>

                    <section>
                        <p class="field-label mb-3">Primary work location / timezone</p>
                        <div class="grid gap-3 sm:grid-cols-2" data-choice-group data-min="1" data-error="Choose your primary work location.">
                            @foreach ($locations as $countryCode => [$countryName, $timezone])
                                <label class="option-tile min-h-20 items-start">
                                    <input class="option-input mt-1" type="radio" name="country_code" value="{{ $countryCode }}" data-timezone="{{ $timezone }}" @checked($selectedCountry === $countryCode)>
                                    <span>
                                        <span class="block">{{ $countryName }}</span>
                                        <span class="mt-1 block text-xs font-semibold text-slate-500">{{ $timezone }}</span>
                                    </span>
                                </label>
                            @endforeach
                        </div>
                        <input type="hidden" name="preferred_timezone" value="{{ $selectedTimezone }}" data-timezone-field>
                    </section>
                </fieldset>

                <fieldset class="hidden space-y-6" data-step="4">
                    <div>
                        <legend class="section-title">Final matching preferences.</legend>
                        <p class="muted-copy mt-1">Choose salary, currency, and work formats to prioritize.</p>
                    </div>

                    <div class="hidden rounded-2xl border border-rose-200 bg-rose-50 p-3 text-sm font-bold text-rose-900" data-step-error></div>

                    <section>
                        <p class="field-label mb-3">Preferred currency</p>
                        <div class="grid grid-cols-2 gap-3 sm:grid-cols-4" data-choice-group data-min="1" data-error="Choose a currency.">
                            @foreach (['USD', 'INR', 'EUR', 'GBP'] as $currency)
                                <label class="option-tile">
                                    <input class="option-input" type="radio" name="salary_currency" value="{{ $currency }}" @checked(old('salary_currency', 'USD') === $currency)>
                                    <span>{{ $currency }}</span>
                                </label>
                            @endforeach
                        </div>
                    </section>

                    <section>
                        <p class="field-label mb-3">Minimum monthly salary</p>
                        <div class="grid gap-3 sm:grid-cols-2" data-choice-group data-min="1" data-error="Choose a salary range.">
                            @foreach ($salaryRanges as $value => $label)
                                <label class="option-tile">
                                    <input class="option-input" type="radio" name="salary_min" value="{{ $value }}" @checked((string) old('salary_min', '2500') === (string) $value)>
                                    <span>{{ $label }}</span>
                                </label>
                            @endforeach
                        </div>
                    </section>

                    <section>
                        <p class="field-label mb-3">Work formats</p>
                        <input type="hidden" name="open_to_contract" value="0">
                        <input type="hidden" name="open_to_full_time" value="0">
                        <div class="grid gap-3 sm:grid-cols-2" data-choice-group data-min="1" data-error="Choose at least one work format.">
                            <label class="option-tile">
                                <input class="option-input" type="checkbox" name="open_to_contract" value="1" @checked(old('open_to_contract', true))>
                                <span>Open to contract roles</span>
                            </label>

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

            <div class="sticky-action">
                <div class="mx-auto flex max-w-3xl gap-3">
                    <button class="btn-secondary hidden flex-1" type="button" data-prev>
                        Back
                    </button>
                    <button class="btn-primary flex-1" type="button" data-next>
                        Continue
                    </button>
                    <button class="btn-primary hidden flex-1" type="submit" data-submit>
                        See locked preview
                    </button>
                </div>
            </div>
        </form>
    </section>

    <script>
        (() => {
            const form = document.querySelector('[data-questionnaire-form]');
            const steps = [...document.querySelectorAll('[data-step]')];
            const label = document.querySelector('[data-step-label]');
            const previous = document.querySelector('[data-prev]');
            const next = document.querySelector('[data-next]');
            const submit = document.querySelector('[data-submit]');
            const progressFill = document.querySelector('[data-progress-fill]');
            const progressLabel = document.querySelector('[data-progress-label]');
            const progressSegments = [...document.querySelectorAll('[data-progress-segment]')];
            const timezoneField = document.querySelector('[data-timezone-field]');
            const completedSteps = new Set();
            let current = 0;

            const selectedCount = (group) => [...group.querySelectorAll('input[type="checkbox"], input[type="radio"]')]
                .filter((input) => input.checked)
                .length;

            const validateStep = (index) => {
                const step = steps[index];
                const errorBox = step.querySelector('[data-step-error]');
                let message = '';

                step.querySelectorAll('[data-choice-group]').forEach((group) => {
                    const count = selectedCount(group);
                    const min = Number(group.dataset.min || 1);
                    const max = Number(group.dataset.max || 999);

                    if (!message && (count < min || count > max)) {
                        message = group.dataset.error || 'Please choose an option before continuing.';
                    }
                });

                if (errorBox) {
                    errorBox.textContent = message;
                    errorBox.classList.toggle('hidden', message === '');
                }

                return message === '';
            };

            const syncTimezone = () => {
                const selected = form.querySelector('input[name="country_code"]:checked');

                if (selected && timezoneField) {
                    timezoneField.value = selected.dataset.timezone || 'UTC';
                }
            };

            const render = () => {
                steps.forEach((step, index) => step.classList.toggle('hidden', index !== current));
                label.textContent = String(current + 1);
                previous.classList.toggle('hidden', current === 0);
                next.classList.toggle('hidden', current === steps.length - 1);
                submit.classList.toggle('hidden', current !== steps.length - 1);

                const completedPercent = Math.round((completedSteps.size / steps.length) * 100);
                progressFill.style.width = `${completedPercent}%`;
                progressLabel.textContent = `${completedPercent}% complete`;
                progressSegments.forEach((segment, index) => {
                    segment.classList.toggle('bg-teal-500', completedSteps.has(index));
                    segment.classList.toggle('bg-slate-200', !completedSteps.has(index));
                });

                window.scrollTo({ top: 0, behavior: 'smooth' });
            };

            previous.addEventListener('click', () => {
                current = Math.max(0, current - 1);
                render();
            });

            next.addEventListener('click', () => {
                if (!validateStep(current)) {
                    return;
                }

                completedSteps.add(current);
                current = Math.min(steps.length - 1, current + 1);
                render();
            });

            form.addEventListener('change', (event) => {
                if (event.target.matches('input[name="country_code"]')) {
                    syncTimezone();
                }
            });

            form.addEventListener('submit', (event) => {
                for (let index = 0; index < steps.length; index++) {
                    if (!validateStep(index)) {
                        event.preventDefault();
                        current = index;
                        render();
                        return;
                    }

                    completedSteps.add(index);
                }

                syncTimezone();
            });

            syncTimezone();
            render();
        })();
    </script>
</x-app-shell>
