<div class="relative min-h-[calc(100vh-4.75rem)] overflow-hidden bg-mesh"
     x-data="assessmentStepper({
        questions: @js($payload),
        isAuthed: @js(auth()->check()),
     })"
     @keydown.window="onKey($event)">

    <div class="bg-kitenge absolute inset-0 opacity-[0.04]" aria-hidden="true"></div>
    <div class="blob -left-32 top-20 h-80 w-80 bg-wise-300/30" aria-hidden="true"></div>
    <div class="blob -right-24 bottom-10 h-72 w-72 bg-navy-200/40" aria-hidden="true"></div>

    <div class="container-site relative flex min-h-[calc(100vh-4.75rem)] max-w-3xl flex-col py-8 md:py-12">

        {{-- ======================= INTRO ======================= --}}
        <div x-show="phase === 'intro'" x-transition:enter="transition duration-500" x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
             class="m-auto w-full text-center">
            <span class="icon-tile mx-auto h-20 w-20 bg-wise-400 text-navy-950 shadow-wise">
                <x-icon :name="$assessment->emoji ?? 'heart-pulse'" class="h-9 w-9" />
            </span>
            @if ($campaign)
                <span class="mt-4 inline-flex items-center gap-1.5 rounded-full bg-wise-100 px-4 py-1.5 text-sm font-bold text-wise-700">
                    <x-icon name="sparkles" class="h-4 w-4" /> {{ $campaignHeadline ?: 'Welcome' }}
                </span>
            @endif
            <h1 class="mt-6 font-display text-display-sm font-bold text-navy-900 md:text-display">
                {{ $assessment->title }}
            </h1>
            <p class="mx-auto mt-4 max-w-xl text-lg text-navy-600">
                {{ $campaignIntro ?: $assessment->tagline }}
            </p>

            <div class="mx-auto mt-8 flex max-w-md flex-wrap items-center justify-center gap-3 text-sm font-semibold text-navy-700">
                <span class="chip"><x-icon name="clock" class="h-3.5 w-3.5" /> {{ $assessment->est_minutes }} minutes</span>
                <span class="chip"><x-icon name="check-circle" class="h-3.5 w-3.5" /> <span x-text="questions.length"></span>&nbsp;quick questions</span>
                <span class="chip"><x-icon name="heart" class="h-3.5 w-3.5" /> Zero judgement</span>
            </div>

            <div class="mt-10">
                <button @click="begin()" class="btn-accent btn-lg group">
                    Let's do this
                    <x-icon name="arrow-right" class="h-5 w-5 transition-transform group-hover:translate-x-1" />
                </button>
                <p class="mt-4 text-sm text-navy-500">Tip: you can answer with your keyboard, keys <span class="keycap !inline-grid !h-6 !w-6 text-[10px]">A</span> to <span class="keycap !inline-grid !h-6 !w-6 text-[10px]">D</span>.</p>
                <p class="mx-auto mt-4 flex max-w-md items-start justify-center gap-2 text-xs leading-relaxed text-navy-400">
                    <x-icon name="shield-check" class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
                    <span>Private &amp; confidential: your answers are used only to generate your result, and are never shared.</span>
                </p>
            </div>
        </div>

        {{-- ======================= QUESTION ======================= --}}
        <div x-show="phase === 'question'" x-cloak>
            {{-- Top bar --}}
            <div class="flex items-center gap-4">
                <button @click="back()" :class="index === 0 && 'invisible'"
                        class="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-white text-navy-700 shadow-brand ring-1 ring-navy-100 transition hover:bg-navy-50"
                        aria-label="Previous question">
                    <x-icon name="arrow-left" class="h-5 w-5" />
                </button>

                <div class="h-3 flex-1 overflow-hidden rounded-full bg-navy-100">
                    <div class="h-full rounded-full bg-gradient-to-r from-wise-400 to-wise-500 transition-all duration-500 ease-out"
                         :style="'width:' + Math.max(progress(), 4) + '%'"></div>
                </div>

                <span class="shrink-0 font-display text-sm font-extrabold text-navy-500">
                    <span x-text="index + 1"></span><span class="text-navy-300">/<span x-text="questions.length"></span></span>
                </span>
            </div>

            {{-- Card (re-animates per question via x-show + key) --}}
            <template x-for="(q, qi) in questions" :key="q.id">
                <div x-show="phase === 'question' && index === qi"
                     x-transition:enter="transition duration-400 ease-out" x-transition:enter-start="opacity-0 translate-x-10" x-transition:enter-end="opacity-100 translate-x-0">
                    <div class="mt-7" x-show="q.section">
                        <span class="chip" x-text="q.section"></span>
                    </div>

                    <h2 class="mt-4 font-display text-2xl font-bold leading-snug text-navy-900 md:text-3xl" x-text="q.prompt"></h2>
                    <p class="mt-2 text-navy-500" x-show="q.help" x-text="q.help"></p>

                    <div class="mt-8 grid gap-3" :class="q.type === 'this_or_that' && 'sm:grid-cols-2'">
                        <template x-for="(opt, oi) in q.options" :key="opt.key">
                            <button @click="choose(opt.key)"
                                    class="answer-card"
                                    :class="answers[q.id] === opt.key && 'selected'"
                                    :style="`animation: fade-up .5s cubic-bezier(.21,.61,.35,1) both; animation-delay: ${oi * 60}ms`">
                                <span class="keycap" x-text="opt.key"></span>
                                <span class="icon-tile !h-11 !w-11" x-show="opt.icon" x-html="iconSvg(opt.icon)"></span>
                                <span class="flex-1 font-semibold leading-snug text-navy-800" x-text="opt.label"></span>
                                <span class="grid h-6 w-6 shrink-0 place-items-center rounded-full bg-wise-500 text-white opacity-0 transition-opacity duration-150"
                                      :class="answers[q.id] === opt.key && '!opacity-100'">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round" class="h-3.5 w-3.5"><path d="M20 6 9 17l-5-5"/></svg>
                                </span>
                            </button>
                        </template>
                    </div>
                </div>
            </template>
        </div>

        {{-- ======================= INTERSTITIAL ======================= --}}
        <div x-show="phase === 'feedback'" x-cloak
             x-transition:enter="transition duration-500" x-transition:enter-start="opacity-0 scale-90" x-transition:enter-end="opacity-100 scale-100"
             class="m-auto w-full text-center">
            <div class="icon-tile mx-auto h-20 w-20 animate-float bg-wise-100">
                <x-icon name="sparkles" class="h-8 w-8" />
            </div>
            <p class="mx-auto mt-6 max-w-md font-display text-2xl font-bold text-navy-900" x-text="feedback"></p>
            <div class="mx-auto mt-4 h-3 w-48 overflow-hidden rounded-full bg-navy-100">
                <div class="h-full rounded-full bg-gradient-to-r from-wise-400 to-wise-500 transition-all duration-700" :style="'width:' + progress() + '%'"></div>
            </div>
            <p class="mt-2 text-sm font-semibold text-navy-500"><span x-text="progress()"></span>% done</p>
            <button @click="continueFeedback()" class="btn-primary mt-8">
                Keep going
                <x-icon name="arrow-right" class="h-5 w-5" />
            </button>
            <p class="mt-3 text-xs text-navy-400">or press <span class="keycap !inline-grid !h-6 !w-9 text-[9px]">Enter</span></p>
        </div>

        {{-- ======================= EMAIL CAPTURE ======================= --}}
        <div x-show="phase === 'email'" x-cloak
             x-transition:enter="transition duration-500" x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100"
             class="m-auto w-full max-w-lg">
            <div class="card p-8 text-center">
                <span class="icon-tile mx-auto h-16 w-16 bg-wise-400 text-navy-950 shadow-wise">
                    <x-icon name="award" class="h-7 w-7" />
                </span>
                <h2 class="mt-4 font-display text-2xl font-bold text-navy-900">Your results are ready!</h2>
                <p class="mt-2 text-navy-600">Enter your name and email to unlock your score, your strengths map and your personalised next steps.</p>

                <form @submit.prevent="submitWithDetails()" class="mt-6 space-y-4 text-left">
                    <div>
                        <label for="guestName" class="mb-1 block text-sm font-semibold text-navy-700">First name *</label>
                        <input type="text" id="guestName" x-model="guestName" placeholder="e.g. Amina" required
                               class="w-full rounded-2xl border-navy-200 px-4 py-3 focus:border-wise-400 focus:ring-wise-400">
                    </div>
                    <div>
                        <label for="guestEmail" class="mb-1 block text-sm font-semibold text-navy-700">Email *</label>
                        <input type="email" id="guestEmail" x-model="guestEmail" placeholder="you@example.com" required
                               class="w-full rounded-2xl border-navy-200 px-4 py-3 focus:border-wise-400 focus:ring-wise-400">
                        <p x-show="error" x-text="error" class="mt-1 text-sm font-medium text-rose-600"></p>
                    </div>

                    <button type="submit" class="btn-accent w-full btn-lg" :disabled="submitting">
                        <span x-show="!submitting" class="inline-flex items-center gap-2">Show me my results <x-icon name="arrow-right" class="h-5 w-5" /></span>
                        <span x-cloak x-show="submitting">Crunching your numbers…</span>
                    </button>
                </form>

                <p class="mt-4 text-xs text-navy-400">Your score, plus the occasional practical money tip. Unsubscribe anytime.</p>
            </div>
        </div>

        {{-- ======================= SUBMITTING (authed users land here directly) ======================= --}}
        <div x-show="phase === 'submitting'" x-cloak class="m-auto text-center">
            <div class="icon-tile mx-auto h-20 w-20 animate-float bg-wise-100"><x-icon name="sparkles" class="h-8 w-8" /></div>
            <p class="mt-6 font-display text-2xl font-bold text-navy-900">Crunching your numbers…</p>
            <p class="mt-2 text-navy-500">Building your personalised report.</p>
        </div>
    </div>
</div>

@script
<script>
    Alpine.data('assessmentStepper', ({ questions, isAuthed }) => ({
        questions,
        isAuthed,
        phase: 'intro',
        index: 0,
        answers: {},
        feedback: null,
        guestName: '',
        guestEmail: '',
        error: '',
        submitting: false,
        locked: false,

        progress() {
            return Math.round(Object.keys(this.answers).length / this.questions.length * 100);
        },

        begin() {
            this.phase = 'question';
        },

        current() {
            return this.questions[this.index];
        },

        choose(key) {
            if (this.locked || this.phase !== 'question') return;
            this.locked = true;

            const q = this.current();
            this.answers[q.id] = key;

            // Brief beat so the selection state is felt, then advance instantly.
            setTimeout(() => {
                this.locked = false;
                const isLast = this.index >= this.questions.length - 1;

                if (q.feedback && !isLast) {
                    this.feedback = q.feedback;
                    this.phase = 'feedback';
                    return;
                }

                this.advance();
            }, 240);
        },

        advance() {
            if (this.index >= this.questions.length - 1) {
                this.isAuthed ? this.finish() : this.phase = 'email';
                return;
            }
            this.index++;
            this.phase = 'question';
        },

        continueFeedback() {
            this.feedback = null;
            this.advance();
        },

        back() {
            if (this.phase === 'email') { this.phase = 'question'; return; }
            if (this.index > 0) { this.index--; this.phase = 'question'; }
        },

        submitWithDetails() {
            if (!this.guestName.trim()) {
                this.error = 'Please tell us your name.';
                return;
            }
            if (!this.guestEmail.includes('@')) {
                this.error = 'That email doesn\'t look quite right, mind checking it?';
                return;
            }
            this.error = '';
            this.finish();
        },

        finish() {
            if (this.submitting) return;
            this.submitting = true;
            if (this.phase !== 'email') this.phase = 'submitting';
            $wire.submit(this.answers, this.guestName || null, this.guestEmail || null);
        },

        onKey(e) {
            if (this.phase === 'question') {
                const q = this.current();
                const keys = q.options.map(o => o.key.toLowerCase());
                const pressed = e.key.toLowerCase();
                const numeric = parseInt(e.key, 10);

                if (keys.includes(pressed)) this.choose(q.options[keys.indexOf(pressed)].key);
                else if (numeric >= 1 && numeric <= q.options.length) this.choose(q.options[numeric - 1].key);
                else if (e.key === 'Backspace') { e.preventDefault(); this.back(); }
            } else if (this.phase === 'feedback' && e.key === 'Enter') {
                this.continueFeedback();
            } else if (this.phase === 'intro' && e.key === 'Enter') {
                this.begin();
            }
        },

        // Minimal icon set used inside option cards
        iconSvg(name) {
            const icons = @js($this->iconMap());
            const paths = icons[name] ?? icons['sparkles'];
            return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="h-5 w-5">${paths}</svg>`;
        },
    }));
</script>
@endscript
