<x-layouts.site>
    <x-slot:title>Your {{ $attempt->assessment->title }} Results</x-slot:title>

    @php
        $band = $attempt->band;
        $percent = (int) round($attempt->percent);
        $isProfile = $attempt->assessment->isProfileMode();
        $firstName = $attempt->user?->firstName() ?? ($attempt->guest_name ? explode(' ', trim($attempt->guest_name))[0] : null);
        $dimensionLabels = $isProfile
            ? collect($attempt->assessment->profileTypes())
            : $attempt->assessment->questions
                ->groupBy('dimension')
                ->map(fn ($questions) => $questions->first()->section)
                ->filter();
        $dimensionPercents = collect($attempt->dimension_percents ?? []);
        $weakest = $isProfile ? null : $dimensionPercents->sortKeys()->sort()->keys()->first();
        $shareText = $isProfile
            ? "I just discovered my money personality: {$band?->label}. What's yours? Find out free: ".route('assessments.show', $attempt->assessment->slug)
            : "I just took the Money-Wise {$attempt->assessment->title} and scored {$percent}%. How healthy is your money? Take the free check: ".route('assessments.show', $attempt->assessment->slug);
    @endphp

    <div class="relative overflow-hidden bg-mesh">
        <div class="bg-kitenge absolute inset-0 opacity-[0.04]" aria-hidden="true"></div>
        <div class="blob -right-32 top-24 h-96 w-96 bg-wise-300/30" data-parallax="0.18" aria-hidden="true"></div>

        <div class="container-site section relative max-w-5xl">

            {{-- ===== The Reveal ===== --}}
            <div class="text-center" data-hero>
                <p class="eyebrow justify-center" data-hero-item>Your results are in</p>
                <div class="mt-6 flex justify-center" data-hero-item>
                    <span class="icon-tile h-20 w-20 shadow-wise" style="background: {{ $band?->color ?? '#58b9e6' }}1a; color: {{ $band?->color ?? '#2787b8' }}">
                        <x-icon :name="$band?->emoji ?? 'sparkles'" class="h-9 w-9" />
                    </span>
                </div>
                <h1 class="mt-5 font-display text-display-sm font-bold text-navy-900 md:text-display" data-hero-item>
                    {{ $firstName ? "{$firstName}, you're" : "You're" }} <span class="text-gradient">{{ $band?->label ?? 'on your way' }}</span>
                </h1>
                <p class="mx-auto mt-4 max-w-2xl text-lg text-navy-600" data-hero-item>{{ $band?->headline }}</p>
            </div>

            <div class="mt-12 grid items-start gap-8 lg:grid-cols-2">
                {{-- Score gauge --}}
                <div class="card p-8 text-center" data-gsap="fade-right">
                    <h2 class="font-display text-lg font-bold text-navy-900">{{ $isProfile ? 'How strongly this fits you' : 'Your overall score' }}</h2>
                    <div class="relative mx-auto mt-4 w-64" x-data="{ shown: false }" x-init="setTimeout(() => shown = true, 350)">
                        <svg viewBox="0 0 200 120" class="w-full">
                            <path d="M 20 110 A 80 80 0 0 1 180 110" fill="none" stroke="#eef1f9" stroke-width="16" stroke-linecap="round"/>
                            <path d="M 20 110 A 80 80 0 0 1 180 110" fill="none" stroke="url(#scoreGradient)" stroke-width="16" stroke-linecap="round"
                                  stroke-dasharray="251.3"
                                  :stroke-dashoffset="shown ? {{ 251.3 - (251.3 * $percent / 100) }} : 251.3"
                                  style="transition: stroke-dashoffset 1.6s cubic-bezier(.21,.61,.35,1)"/>
                            <defs>
                                <linearGradient id="scoreGradient" x1="0%" y1="0%" x2="100%" y2="0%">
                                    <stop offset="0%" stop-color="#58b9e6"/>
                                    <stop offset="100%" stop-color="#1c2b5f"/>
                                </linearGradient>
                            </defs>
                        </svg>
                        <div class="absolute inset-x-0 bottom-0 pb-1">
                            <span class="font-display text-5xl font-extrabold text-navy-900" data-countup="{{ $percent }}" data-suffix="%">0%</span>
                        </div>
                    </div>
                    <p class="mt-4 text-navy-600">
                        @if ($isProfile)
                            {{ $attempt->score }} of {{ $attempt->max_score }} answers matched this type · completed {{ $attempt->completed_at->diffForHumans() }}
                        @else
                            {{ $attempt->score }} of {{ $attempt->max_score }} points · completed {{ $attempt->completed_at->diffForHumans() }}
                        @endif
                    </p>
                </div>

                {{-- Radar chart --}}
                <div class="card p-8" data-gsap="fade-left">
                    <h2 class="text-center font-display text-lg font-bold text-navy-900">Your money map</h2>
                    <div class="mx-auto mt-2 max-w-sm">
                        <canvas id="dimensionRadar" height="280"></canvas>
                    </div>
                </div>
            </div>

            {{-- Dimension bars --}}
            <div class="card mt-8 p-8" data-gsap="fade-up">
                <h2 class="font-display text-lg font-bold text-navy-900">{{ $isProfile ? 'Your personality blend' : 'The full picture' }}</h2>
                <div class="mt-6 space-y-5">
                    @foreach ($dimensionPercents as $dimension => $dimPercent)
                        <div>
                            <div class="mb-1.5 flex items-baseline justify-between">
                                <span class="font-semibold text-navy-800">{{ $dimensionLabels[$dimension] ?? ucfirst($dimension) }}</span>
                                @if ($isProfile)
                                    <span class="text-sm font-bold text-wise-600">{{ $dimPercent }}%</span>
                                @else
                                    <span class="text-sm font-bold {{ $dimPercent >= 67 ? 'text-emerald-600' : ($dimPercent >= 34 ? 'text-amber-600' : 'text-rose-600') }}">{{ $dimPercent }}%</span>
                                @endif
                            </div>
                            <div class="h-3 overflow-hidden rounded-full bg-navy-100">
                                @if ($isProfile)
                                    <div class="h-full rounded-full bg-gradient-to-r from-wise-400 to-wise-600" data-grow-width="{{ max($dimPercent, 3) }}"></div>
                                @else
                                    <div class="h-full rounded-full {{ $dimPercent >= 67 ? 'bg-emerald-500' : ($dimPercent >= 34 ? 'bg-amber-400' : 'bg-rose-400') }}"
                                         data-grow-width="{{ max($dimPercent, 3) }}"></div>
                                @endif
                            </div>
                            @if (! $isProfile && $dimension === $weakest && $dimPercent < 67)
                                <p class="mt-1.5 flex items-center gap-1.5 text-sm text-navy-500">
                                    <x-icon name="lightbulb" class="h-4 w-4 text-amber-500" />
                                    Your biggest opportunity, small wins here move your whole score.
                                </p>
                            @endif
                        </div>
                    @endforeach
                </div>
            </div>

            {{-- What this means + advice --}}
            @if ($band)
                <div class="card mt-8 p-8" data-gsap="fade-up">
                    <h2 class="font-display text-lg font-bold text-navy-900">What this means</h2>
                    <p class="mt-3 leading-relaxed text-navy-700">{{ $band->message }}</p>

                    @if ($band->advice)
                        <h3 class="mt-8 font-display font-bold text-navy-900">Your next 3 moves</h3>
                        <ol class="mt-4 space-y-4">
                            @foreach ($band->advice as $i => $tip)
                                <li class="flex items-start gap-4">
                                    <span class="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-wise-400 font-display font-extrabold text-navy-950">{{ $i + 1 }}</span>
                                    <p class="pt-1.5 leading-relaxed text-navy-700">{{ $tip }}</p>
                                </li>
                            @endforeach
                        </ol>
                    @endif
                </div>
            @endif

            {{-- Recommended next steps, driven by the result --}}
            @php
                // Map the weakest dimension to the tool that helps most.
                $toolByDimension = [
                    'saving' => 'emergency-fund', 'debt' => 'debt-payoff', 'protection' => 'retirement',
                    'investing' => 'compound-growth', 'spending' => 'budget',
                ];
                $recommendedTool = $isProfile ? null : ($toolByDimension[$weakest] ?? null);

                $nextSteps = $isProfile
                    ? [
                        ['href' => route('tools.show', 'budget'), 'icon' => 'calculator', 'title' => 'Build your budget', 'desc' => 'Give every shilling a job, your way.', 'tool' => 'budget'],
                        ['href' => route('tools.show', 'wealth-goals'), 'icon' => 'target', 'title' => 'Plan your goals', 'desc' => 'Turn your dreams into monthly numbers.', 'tool' => 'wealth-goals'],
                        ['href' => route('learn'), 'icon' => 'graduation-cap', 'title' => 'Learn to invest', 'desc' => 'Practical courses in plain language.', 'tool' => null],
                    ]
                    : [
                        ['href' => route('tools.show', 'emergency-fund'), 'icon' => 'life-buoy', 'title' => 'Build your emergency fund', 'desc' => 'Size the cushion that protects you.', 'tool' => 'emergency-fund'],
                        ['href' => route('tools.show', 'debt-payoff'), 'icon' => 'unlink', 'title' => 'Clear your debt', 'desc' => 'See your debt-free date in 2 minutes.', 'tool' => 'debt-payoff'],
                        ['href' => route('tools.show', 'retirement'), 'icon' => 'landmark', 'title' => 'Plan for retirement', 'desc' => 'Check if your pension is on track.', 'tool' => 'retirement'],
                    ];
            @endphp
            <h2 class="mt-12 text-center font-display text-2xl font-bold text-navy-900" data-gsap="fade-up">Your recommended next steps</h2>
            <div class="mt-6 grid gap-4 sm:grid-cols-3" data-gsap-stagger>
                @foreach ($nextSteps as $bridge)
                    @php $isPick = $recommendedTool && $bridge['tool'] === $recommendedTool; @endphp
                    <a href="{{ $bridge['href'] }}" @class(['card-glow group relative p-6', 'ring-2 ring-wise-400 shadow-wise' => $isPick])>
                        @if ($isPick)
                            <span class="absolute -top-3 left-6 rounded-full bg-wise-500 px-3 py-1 text-[10px] font-extrabold uppercase tracking-wide text-white shadow-wise">Recommended for you</span>
                        @endif
                        <span class="icon-tile"><x-icon :name="$bridge['icon']" class="h-5 w-5" /></span>
                        <h3 class="mt-3 font-display font-bold text-navy-900">{{ $bridge['title'] }}</h3>
                        <p class="mt-1 text-sm text-navy-500">{{ $bridge['desc'] }}</p>
                    </a>
                @endforeach
            </div>

            {{-- Coach match (interim: links to coaching until back-end coach matching is wired) --}}
            <a href="{{ route('coaching') }}" class="card-glow group mt-4 flex items-center gap-4 p-6" data-gsap="fade-up">
                <span class="icon-tile shrink-0"><x-icon name="compass" class="h-5 w-5" /></span>
                <span class="flex-1">
                    <span class="block font-display font-bold text-navy-900">Want a guide? Get matched with a coach</span>
                    <span class="mt-0.5 block text-sm text-navy-500">Based on your result, a Money-Wise coach can help you turn this into a plan.</span>
                </span>
                <x-icon name="arrow-right" class="h-5 w-5 shrink-0 text-wise-600 transition-transform group-hover:translate-x-1" />
            </a>

            {{-- Save / share --}}
            <div class="mt-10 flex flex-col items-center gap-4 rounded-brand bg-navy-900 bg-mesh-dark p-8 text-center md:p-10" data-gsap="zoom">
                @guest
                    <h2 class="font-display text-xl font-bold text-white">Keep this result, and track your progress</h2>
                    <p class="max-w-xl text-navy-200">Create a free account to save your score, retake the check as you improve, and unlock your personal dashboard.</p>
                    <div class="flex flex-wrap justify-center gap-3">
                        <a href="{{ route('register') }}" class="btn-accent">Create my free account</a>
                        <a href="{{ route('login') }}" class="btn-white">I already have one</a>
                    </div>
                @else
                    <span class="grid h-12 w-12 place-items-center rounded-full bg-emerald-500/20 text-emerald-400 ring-1 ring-emerald-400/40">
                        <x-icon name="check-circle" class="h-6 w-6" />
                    </span>
                    <h2 class="font-display text-xl font-bold text-white">Saved to your dashboard</h2>
                    <p class="max-w-xl text-navy-200">Retake the check in {{ $attempt->assessment->cooldown_days }} days to watch your score climb.</p>
                    <a href="{{ route('dashboard') }}" class="btn-accent">Go to my dashboard</a>
                @endguest

                <a href="{{ route('assessments.results.pdf', ['assessment' => $attempt->assessment->slug, 'attempt' => $attempt->uuid]) }}"
                   class="btn-white">
                    <x-icon name="download" class="h-4 w-4" /> Download PDF report
                </a>

                <div class="mt-2 flex items-center gap-3" x-data="{ copied: false }">
                    <span class="text-sm text-navy-300">Challenge a friend:</span>
                    <a href="https://wa.me/?text={{ urlencode($shareText) }}" target="_blank" rel="noopener"
                       class="grid h-10 w-10 place-items-center rounded-full bg-white/10 text-white transition hover:-translate-y-0.5 hover:bg-emerald-500" aria-label="Share on WhatsApp">
                        <x-icon name="whatsapp" class="h-5 w-5" />
                    </a>
                    <button @click="navigator.clipboard.writeText('{{ route('assessments.show', $attempt->assessment->slug) }}'); copied = true; setTimeout(() => copied = false, 2000)"
                            class="grid h-10 w-10 place-items-center rounded-full bg-white/10 text-white transition hover:-translate-y-0.5 hover:bg-wise-400 hover:text-navy-950" aria-label="Copy link">
                        <x-icon name="copy" class="h-5 w-5" x-show="!copied" />
                        <x-icon name="check" class="h-5 w-5" x-cloak x-show="copied" />
                    </button>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(() => window.celebrate?.(), 600);

            const ctx = document.getElementById('dimensionRadar');
            if (ctx && window.Chart) {
                // Draw each score as a % right on the map.
                const scoreLabels = {
                    id: 'scoreLabels',
                    afterDatasetsDraw(chart) {
                        const c = chart.ctx;
                        const meta = chart.getDatasetMeta(0);
                        c.save();
                        c.font = '700 11px "Plus Jakarta Sans", system-ui, sans-serif';
                        c.fillStyle = '#1c2b5f';
                        c.textAlign = 'center';
                        c.textBaseline = 'middle';
                        meta.data.forEach((pt, i) => {
                            c.fillText(chart.data.datasets[0].data[i] + '%', pt.x, pt.y - 11);
                        });
                        c.restore();
                    },
                };

                new Chart(ctx, {
                    type: 'radar',
                    data: {
                        labels: @json($dimensionPercents->keys()->map(fn ($d) => $dimensionLabels[$d] ?? ucfirst($d))->values()),
                        datasets: [{
                            label: 'You today',
                            data: @json($dimensionPercents->values()),
                            backgroundColor: 'rgba(88, 185, 230, 0.25)',
                            borderColor: '#58b9e6',
                            borderWidth: 2.5,
                            pointBackgroundColor: '#1c2b5f',
                            pointRadius: 4,
                        }],
                    },
                    options: {
                        // Generous padding so axis labels (e.g. "Protecting Tomorrow") never clip.
                        layout: { padding: 18 },
                        scales: {
                            r: {
                                beginAtZero: true,
                                max: 100,
                                ticks: { display: false, stepSize: 25 },
                                pointLabels: { font: { size: 11, weight: '600' }, color: '#28366a', padding: 8 },
                                grid: { color: 'rgba(28, 43, 95, 0.08)' },
                                angleLines: { color: 'rgba(28, 43, 95, 0.08)' },
                            },
                        },
                        plugins: { legend: { display: false }, tooltip: { enabled: false } },
                    },
                    plugins: [scoreLabels],
                });
            }
        });
    </script>
    @endpush
</x-layouts.site>
