<x-layouts.site>
    <x-slot:title>My Dashboard</x-slot:title>

    @php
        $user = auth()->user();
        $attempts = $user->attempts()->with(['assessment', 'band'])->where('status', 'completed')->get();
        $latest = $attempts->first();
        $history = $attempts->reverse()->values();
        $plans = $user->toolResults()->get();
        $enrollments = $user->enrollments()->with('course.modules.lessons')->get();
        $completedLessonIds = $user->completedLessons()->pluck('lessons.id')->all();

        $cooldownDays = $latest?->assessment->cooldown_days ?? 30;
        $nextRetake = $latest?->completed_at?->addDays($cooldownDays);
        $canRetake = ! $latest || $nextRetake->isPast();

        $toolMeta = [
            'debt-payoff' => ['icon' => 'unlink', 'title' => 'Debt payoff plan'],
            'compound-growth' => ['icon' => 'trending-up', 'title' => 'Growth projection'],
            'emergency-fund' => ['icon' => 'life-buoy', 'title' => 'Emergency fund plan'],
            'wealth-goals' => ['icon' => 'target', 'title' => 'Wealth & goals plan'],
            'values-clarification' => ['icon' => 'compass', 'title' => 'My money compass'],
            'loan-cost' => ['icon' => 'receipt', 'title' => 'Loan cost analysis'],
            'retirement' => ['icon' => 'landmark', 'title' => 'Retirement plan'],
        ];
    @endphp

    <div class="relative min-h-[70vh] overflow-hidden bg-navy-50/40">
        <div class="bg-kitenge absolute inset-0 opacity-[0.04]" aria-hidden="true"></div>
        <div class="container-site section relative">
            {{-- Greeting --}}
            <div class="flex flex-wrap items-end justify-between gap-4" data-hero>
                <div data-hero-item>
                    <p class="eyebrow">My dashboard</p>
                    <h1 class="mt-2 font-display text-3xl font-bold text-navy-900">Karibu back, {{ $user->firstName() }}</h1>
                </div>
                <a href="{{ route('profile') }}" class="btn-ghost btn-sm" data-hero-item><x-icon name="user" class="h-4 w-4" /> Edit profile</a>
            </div>

            <div class="mt-8 grid gap-6 lg:grid-cols-3">
                {{-- Health score --}}
                <div class="card p-7 lg:col-span-1" data-gsap="fade-up">
                    <h2 class="flex items-center gap-2 font-display font-bold text-navy-900">
                        <x-icon name="heart-pulse" class="h-5 w-5 text-wise-600" /> My Financial Health Check
                    </h2>
                    @if ($latest)
                        <div class="mt-4 text-center">
                            <div class="relative mx-auto w-44" x-data="{ shown: false }" x-init="setTimeout(() => shown = true, 300)">
                                <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="#58b9e6" stroke-width="16" stroke-linecap="round"
                                          stroke-dasharray="251.3"
                                          :stroke-dashoffset="shown ? {{ 251.3 - (251.3 * round($latest->percent) / 100) }} : 251.3"
                                          style="transition: stroke-dashoffset 1.4s cubic-bezier(.21,.61,.35,1)"/>
                                </svg>
                                <div class="absolute inset-x-0 bottom-0">
                                    <span class="font-display text-4xl font-extrabold text-navy-900">{{ round($latest->percent) }}%</span>
                                </div>
                            </div>
                            <p class="mt-3 flex items-center justify-center gap-2 font-display text-lg font-bold text-navy-900">
                                <x-icon :name="$latest->band?->emoji ?? 'sparkles'" class="h-5 w-5 text-wise-600" />
                                {{ $latest->band?->label }}
                            </p>
                            <p class="text-xs text-navy-400">Last checked {{ $latest->completed_at->diffForHumans() }}</p>

                            @if ($canRetake)
                                <a href="{{ route('assessments.show', $latest->assessment->slug) }}" class="btn-accent btn-sm mt-4 w-full">Retake the check, beat your score</a>
                            @else
                                <p class="mt-4 flex items-center justify-center gap-2 rounded-2xl bg-navy-50 px-4 py-2.5 text-xs font-semibold text-navy-600">
                                    <x-icon name="lock" class="h-3.5 w-3.5" /> Next retake unlocks {{ $nextRetake->diffForHumans() }}, time to work the plan!
                                </p>
                            @endif

                            <a href="{{ route('assessments.results', ['assessment' => $latest->assessment->slug, 'attempt' => $latest->uuid]) }}"
                               class="mt-2 inline-flex items-center gap-1 text-sm font-bold text-wise-600 transition hover:text-wise-700">
                                View full report <x-icon name="arrow-right" class="h-3.5 w-3.5" />
                            </a>
                        </div>
                    @else
                        <div class="mt-4 text-center">
                            <span class="icon-tile mx-auto h-16 w-16"><x-icon name="heart-pulse" class="h-7 w-7" /></span>
                            <p class="mt-3 text-sm leading-relaxed text-navy-600">You haven't taken the Financial Health Check yet, it's free and takes 3 minutes.</p>
                            <a href="{{ route('assessments.show', 'financial-health') }}" class="btn-accent btn-sm mt-4 w-full">Take the Financial Health Check</a>
                        </div>
                    @endif
                </div>

                {{-- Progress --}}
                <div class="card p-7 lg:col-span-2" data-gsap="fade-up" data-gsap-delay="0.1">
                    <h2 class="flex items-center gap-2 font-display font-bold text-navy-900">
                        <x-icon name="chart-line" class="h-5 w-5 text-wise-600" /> My progress
                    </h2>
                    @if ($history->count() > 1)
                        <div class="mt-3"><canvas id="historyChart" height="120"></canvas></div>
                    @elseif ($latest)
                        <div class="mt-4 space-y-4">
                            @php
                                $labels = $latest->assessment->questions->groupBy('dimension')->map(fn ($q) => $q->first()->section);
                            @endphp
                            @foreach ($latest->dimension_percents ?? [] as $dimension => $pct)
                                <div>
                                    <div class="mb-1 flex justify-between text-sm">
                                        <span class="font-semibold text-navy-800">{{ $labels[$dimension] ?? ucfirst($dimension) }}</span>
                                        <span class="font-bold {{ $pct >= 67 ? 'text-emerald-600' : ($pct >= 34 ? 'text-amber-600' : 'text-rose-600') }}">{{ $pct }}%</span>
                                    </div>
                                    <div class="h-2.5 rounded-full bg-navy-100">
                                        <div class="h-full rounded-full {{ $pct >= 67 ? 'bg-emerald-500' : ($pct >= 34 ? 'bg-amber-400' : 'bg-rose-400') }}" data-grow-width="{{ max($pct, 3) }}"></div>
                                    </div>
                                </div>
                            @endforeach
                            <p class="text-xs text-navy-400">Retake the check after working your plan, your progress line starts with your second score.</p>
                        </div>
                    @else
                        <div class="mt-6 grid place-items-center rounded-2xl border-2 border-dashed border-navy-200 py-10 text-center">
                            <p class="text-sm text-navy-500">Your progress chart will live here.<br>It starts with your first assessment.</p>
                        </div>
                    @endif
                </div>
            </div>

            {{-- Learning --}}
            <div class="mt-8" data-gsap="fade-up">
                <div class="flex items-center justify-between">
                    <h2 class="flex items-center gap-2 font-display text-lg font-bold text-navy-900">
                        <x-icon name="graduation-cap" class="h-5 w-5 text-wise-600" /> My learning
                    </h2>
                    <a href="{{ route('learn') }}" class="inline-flex items-center gap-1 text-sm font-bold text-wise-600 transition hover:text-wise-700">Browse courses <x-icon name="arrow-right" class="h-3.5 w-3.5" /></a>
                </div>
                @if ($enrollments->isNotEmpty())
                    <div class="mt-4 grid gap-4 md:grid-cols-2" data-gsap-stagger>
                        @foreach ($enrollments as $enrollment)
                            @php
                                $nextLesson = $enrollment->course->modules
                                    ->flatMap->lessons
                                    ->first(fn ($l) => ! in_array($l->id, $completedLessonIds, true))
                                    ?? $enrollment->course->modules->flatMap->lessons->first();
                            @endphp
                            <div class="card-glow p-6">
                                <div class="flex items-center justify-between gap-3">
                                    <h3 class="flex items-center gap-2 font-display font-bold text-navy-900">
                                        <x-icon :name="$enrollment->course->emoji ?? 'graduation-cap'" class="h-5 w-5 text-wise-600" />
                                        {{ $enrollment->course->title }}
                                    </h3>
                                    <span class="font-display text-sm font-extrabold text-wise-600">{{ $enrollment->progress }}%</span>
                                </div>
                                <div class="mt-3 h-3 rounded-full bg-navy-100">
                                    <div class="h-full rounded-full bg-gradient-to-r from-wise-400 to-wise-500" data-grow-width="{{ max($enrollment->progress, 2) }}"></div>
                                </div>
                                <div class="mt-4 flex items-center justify-between gap-3">
                                    <p class="text-xs font-semibold text-navy-400">
                                        @if ($enrollment->status === 'completed')
                                            <span class="inline-flex items-center gap-1 text-emerald-600"><x-icon name="award" class="h-4 w-4" /> Completed, well done!</span>
                                        @else
                                            Next: {{ \Illuminate\Support\Str::limit($nextLesson?->title ?? 'Start the course', 32) }}
                                        @endif
                                    </p>
                                    @if ($nextLesson)
                                        <a href="{{ route('learn.lesson', ['course' => $enrollment->course->slug, 'lesson' => $nextLesson->slug]) }}" class="btn-primary btn-sm shrink-0">
                                            <x-icon name="play" class="h-3.5 w-3.5" /> {{ $enrollment->status === 'completed' ? 'Review' : 'Continue' }}
                                        </a>
                                    @endif
                                </div>
                            </div>
                        @endforeach
                    </div>
                @else
                    <div class="card mt-4 flex flex-col items-center gap-4 p-8 text-center sm:flex-row sm:text-left">
                        <span class="icon-tile h-14 w-14"><x-icon name="graduation-cap" class="h-6 w-6" /></span>
                        <div class="flex-1">
                            <h3 class="font-display font-bold text-navy-900">Start learning to invest</h3>
                            <p class="mt-1 text-sm text-navy-500">The first lesson of Investable is free, see if it's your style.</p>
                        </div>
                        <a href="{{ route('learn') }}" class="btn-accent btn-sm shrink-0">Explore courses</a>
                    </div>
                @endif
            </div>

            {{-- Saved plans --}}
            <div class="mt-8" data-gsap="fade-up">
                <div class="flex items-center justify-between">
                    <h2 class="flex items-center gap-2 font-display text-lg font-bold text-navy-900">
                        <x-icon name="sliders" class="h-5 w-5 text-wise-600" /> My saved plans
                    </h2>
                    <a href="{{ route('tools.index') }}" class="inline-flex items-center gap-1 text-sm font-bold text-wise-600 transition hover:text-wise-700">All tools <x-icon name="arrow-right" class="h-3.5 w-3.5" /></a>
                </div>
                @if ($plans->isNotEmpty())
                    <div class="mt-4 grid gap-4 md:grid-cols-2 lg:grid-cols-3" data-gsap-stagger>
                        @foreach ($plans as $plan)
                            @php $meta = $toolMeta[$plan->tool] ?? ['icon' => 'sliders', 'title' => $plan->label ?? $plan->tool]; @endphp
                            <a href="{{ route('tools.show', $plan->tool) }}" class="card-glow group p-6">
                                <div class="flex items-start justify-between">
                                    <span class="icon-tile"><x-icon :name="$meta['icon']" class="h-5 w-5" /></span>
                                    <span class="text-xs font-semibold text-navy-400">{{ $plan->created_at->format('j M Y') }}</span>
                                </div>
                                <h3 class="mt-3 font-display font-bold text-navy-900">{{ $plan->label ?? $meta['title'] }}</h3>
                                <p class="mt-1 text-sm text-navy-500">
                                    @if ($plan->tool === 'debt-payoff' && isset($plan->outputs['freedomDate']))
                                        Debt-free {{ $plan->outputs['freedomDate'] }}
                                    @elseif ($plan->tool === 'compound-growth' && isset($plan->outputs['futureValue']))
                                        Grows to KES {{ number_format($plan->outputs['futureValue']) }}
                                    @elseif ($plan->tool === 'emergency-fund' && isset($plan->outputs['target']))
                                        Target KES {{ number_format($plan->outputs['target']) }} · {{ $plan->outputs['pct'] ?? 0 }}% funded
                                    @elseif ($plan->tool === 'wealth-goals' && isset($plan->outputs['totalMonthly']))
                                        {{ count($plan->inputs['goals'] ?? []) }} goals · KES {{ number_format($plan->outputs['totalMonthly']) }}/month
                                    @elseif ($plan->tool === 'values-clarification' && isset($plan->outputs['ranked'][0]['value']))
                                        #1 value: {{ $plan->outputs['ranked'][0]['value'] }}
                                    @else
                                        Open to view your plan
                                    @endif
                                </p>
                            </a>
                        @endforeach
                    </div>
                @else
                    <div class="mt-4 grid gap-4 md:grid-cols-3" data-gsap-stagger>
                        @foreach ($toolMeta as $slug => $meta)
                            <a href="{{ route('tools.show', $slug) }}" class="group rounded-brand border-2 border-dashed border-navy-200 p-6 transition hover:border-wise-300 hover:bg-white">
                                <span class="icon-tile bg-navy-50 text-navy-400 group-hover:bg-wise-50 group-hover:text-wise-600"><x-icon :name="$meta['icon']" class="h-5 w-5" /></span>
                                <h3 class="mt-3 font-display text-sm font-bold text-navy-700">{{ $meta['title'] }}</h3>
                                <p class="mt-1 text-xs text-navy-400">Not created yet, takes 2 minutes</p>
                            </a>
                        @endforeach
                    </div>
                @endif
            </div>
        </div>
    </div>

    @if ($history->count() > 1)
        @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', () => {
                const ctx = document.getElementById('historyChart');
                if (!ctx || !window.Chart) return;
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: @json($history->map(fn ($a) => $a->completed_at->format('j M y'))),
                        datasets: [{
                            label: 'Financial Health',
                            data: @json($history->map(fn ($a) => round($a->percent))),
                            borderColor: window.brand.sky,
                            backgroundColor: 'rgba(88, 185, 230, 0.15)',
                            fill: true, tension: 0.35, borderWidth: 3,
                            pointBackgroundColor: window.brand.navy, pointRadius: 5,
                        }],
                    },
                    options: {
                        scales: { y: { min: 0, max: 100, ticks: { callback: (v) => v + '%' } } },
                        plugins: { legend: { display: false } },
                    },
                });
            });
        </script>
        @endpush
    @endif
</x-layouts.site>
