@extends('layouts.app')

@push('styles')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" crossorigin="anonymous" />
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
    .tr-hero {
        background: linear-gradient(135deg, #4f46e5 0%, #3730a3 60%, #1e1b4b 100%);
        position: relative; overflow: hidden;
    }
    .tr-hero::before {
        content:''; position:absolute; top:-60px; right:-60px;
        width:260px; height:260px; background:rgba(255,255,255,0.06); border-radius:50%;
    }
    .tr-card {
        background:#fff; border-radius:16px;
        border:1px solid #e2e8f0;
        box-shadow:0 1px 3px rgba(0,0,0,0.06),0 4px 16px rgba(79,70,229,0.04);
        transition:transform 0.22s cubic-bezier(0.34,1.56,0.64,1),box-shadow 0.22s ease;
    }
    .tr-card:hover { transform:translateY(-3px); box-shadow:0 8px 32px rgba(79,70,229,0.12); }
    .kpi-icon { width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0; }
    .sec-title {
        font-size:0.68rem;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;
        color:#64748b;display:flex;align-items:center;gap:8px;margin-bottom:1rem;
    }
    .pbar-wrap { background:#e2e8f0;border-radius:999px;height:8px;overflow:hidden; }
    .pbar-fill  { height:100%;border-radius:999px;transition:width 0.8s cubic-bezier(0.4,0,0.2,1); }
    .badge-pill { display:inline-flex;align-items:center;padding:2px 10px;border-radius:999px;font-size:0.68rem;font-weight:600; }
    .qa-btn {
        display:flex;flex-direction:column;align-items:center;gap:8px;
        padding:16px 10px;border-radius:14px;border:1.5px solid #e2e8f0;
        background:#f8fafc;transition:all 0.2s cubic-bezier(0.34,1.56,0.64,1);text-decoration:none;
    }
    .qa-btn:hover { border-color:#4f46e5;background:#eef2ff;transform:translateY(-2px) scale(1.04);box-shadow:0 4px 16px rgba(79,70,229,0.12); }
    .session-card {
        border-radius:14px;border:1px solid #e2e8f0;padding:1rem;
        transition:all 0.2s cubic-bezier(0.34,1.56,0.64,1);
    }
    .session-card:hover { border-color:#4f46e5;box-shadow:0 4px 16px rgba(79,70,229,0.1);transform:translateY(-2px); }
    .leaderboard-row { display:flex;align-items:center;gap:10px;padding:10px 0;border-bottom:1px solid #f1f5f9; }
    .leaderboard-row:last-child { border-bottom:none; }
    .rank-badge { width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:0.7rem;font-weight:700;flex-shrink:0; }
    .portal-banner { background:linear-gradient(135deg,#4f46e5 0%,#7c3aed 100%);border-radius:16px;padding:1.5rem 2rem;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:1rem; }
</style>
@endpush

@section('content')
@php
    $totalSessions   = $stats['total_sessions'] ?? 0;
    $totalTrainees   = $stats['total_trainees'] ?? 0;
    $certsIssued     = $stats['certificates_issued'] ?? 0;
    $pendAttendance  = $stats['pending_attendance'] ?? 0;
    $upcomingSessions= $stats['upcoming_sessions'] ?? collect();
    $leaderboard     = $stats['leaderboard'] ?? collect();
    $expYears        = $stats['experience_years'] ?? 0;
    $specialization  = $stats['specialization'] ?? 'Not specified';
    $certification   = $stats['certification'] ?? 'Not Set';

    // Self-paced stats for this trainer
    $spCourses   = \App\Models\SelfPaced\Course::where('created_by', $user->id)->count();
    $spEnrolls   = \App\Models\SelfPaced\Enrollment::whereHas('course', fn($q) => $q->where('created_by', $user->id))->count();
    $spActive    = \App\Models\SelfPaced\Enrollment::whereHas('course', fn($q) => $q->where('created_by', $user->id))->where('status','active')->count();
    $spCompleted = \App\Models\SelfPaced\Enrollment::whereHas('course', fn($q) => $q->where('created_by', $user->id))->where('status','completed')->count();
    $spExams     = \App\Models\SelfPaced\ExamAttempt::whereHas('exam.course', fn($q) => $q->where('created_by', $user->id))->where('status','submitted')->count();
    $spPassed    = \App\Models\SelfPaced\ExamAttempt::whereHas('exam.course', fn($q) => $q->where('created_by', $user->id))->where('status','submitted')->where('passed',true)->count();
    $spPassRate  = $spExams > 0 ? round(($spPassed/$spExams)*100) : 0;
    $spCerts     = \App\Models\SelfPaced\SelfPacedCertificate::whereHas('course', fn($q) => $q->where('created_by', $user->id))->where('is_revoked',false)->count();

    // Enrollment trend (last 8 weeks)
    $enrollTrend = \App\Models\SelfPaced\Enrollment::whereHas('course', fn($q) => $q->where('created_by', $user->id))
        ->where('created_at', '>=', now()->subWeeks(8))
        ->selectRaw('YEARWEEK(created_at,1) as yw, COUNT(*) as count')
        ->groupBy('yw')->orderBy('yw')
        ->pluck('count')->values()->toArray();
    $enrollLabels = collect(range(7,0))->map(fn($w) => now()->subWeeks($w)->format('M d'))->values()->toArray();

    // Exam score distribution
    $scoreRanges = [
        '0-49'   => \App\Models\SelfPaced\ExamAttempt::whereHas('exam.course', fn($q) => $q->where('created_by', $user->id))->where('status','submitted')->where('score','<',50)->count(),
        '50-69'  => \App\Models\SelfPaced\ExamAttempt::whereHas('exam.course', fn($q) => $q->where('created_by', $user->id))->where('status','submitted')->whereBetween('score',[50,69])->count(),
        '70-84'  => \App\Models\SelfPaced\ExamAttempt::whereHas('exam.course', fn($q) => $q->where('created_by', $user->id))->where('status','submitted')->whereBetween('score',[70,84])->count(),
        '85-100' => \App\Models\SelfPaced\ExamAttempt::whereHas('exam.course', fn($q) => $q->where('created_by', $user->id))->where('status','submitted')->where('score','>=',85)->count(),
    ];

    // Course completion rates
    $courseStats = \App\Models\SelfPaced\Course::where('created_by', $user->id)
        ->withCount(['enrollments', 'enrollments as completed_count' => fn($q) => $q->where('status','completed')])
        ->latest()->take(5)->get();
@endphp

{{-- ═══════════════════════════════════════════════════════════════
     HERO
═══════════════════════════════════════════════════════════════ --}}
<div class="tr-hero px-6 py-8 md:py-10">
    <div class="relative z-10 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <div class="flex items-center gap-3 mb-2">
                <div class="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-chalkboard-teacher text-white text-lg"></i>
                </div>
                <span class="text-indigo-200 text-sm font-medium uppercase tracking-widest">Trainer Dashboard</span>
            </div>
            <h1 class="text-2xl md:text-3xl font-bold text-white">
                Welcome, {{ $user->name ?? 'Trainer' }}
            </h1>
            <p class="text-indigo-300 text-sm mt-1">
                {{ now()->format('l, d F Y') }} &mdash; Your self-paced learning overview
            </p>
        </div>
        <div class="flex flex-wrap gap-3">
            @can('view training sessions')
            <a href="{{ route('training.sessions.index') }}"
               class="flex items-center gap-2 px-4 py-2 bg-white/15 hover:bg-white/25 text-white text-sm font-medium rounded-xl border border-white/20 transition">
                <i class="fas fa-calendar-check text-xs"></i> My Sessions
            </a>
            @endcan
            @can('view self-paced courses')
            <a href="{{ route('self-paced.dashboard.index') }}"
               class="flex items-center gap-2 px-4 py-2 bg-white text-indigo-700 text-sm font-semibold rounded-xl hover:bg-indigo-50 transition">
                <i class="fas fa-graduation-cap text-xs"></i> SP Portal
            </a>
            @endcan
        </div>
    </div>
</div>

<div class="px-6 py-6 space-y-8">

{{-- Contextual Notifications --}}
@if($pendAttendance > 0)
<div class="bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 flex items-center gap-3" x-data="{show:true}" x-show="show">
    <i class="fas fa-exclamation-circle text-amber-500 flex-shrink-0"></i>
    <p class="text-sm font-medium text-amber-800 flex-1">
        {{ $pendAttendance }} completed session(s) have no attendance recorded. Mark attendance to enable certificate generation.
    </p>
    <button @click="show=false" class="text-amber-400 hover:text-amber-600"><i class="fas fa-times text-xs"></i></button>
</div>
@endif

{{-- ═══════════════════════════════════════════════════════════════
     ROW 1 — PRIMARY KPI CARDS
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
    <div class="tr-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-indigo-50"><i class="fas fa-book-open text-indigo-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">SP Courses</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spCourses) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Created by you</p>
        </div>
    </div>
    <div class="tr-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-blue-50"><i class="fas fa-users text-blue-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">SP Enrollments</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spEnrolls) }}</p>
            <p class="text-xs text-indigo-500 font-medium mt-0.5">{{ $spActive }} active</p>
        </div>
    </div>
    <div class="tr-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-emerald-50"><i class="fas fa-clipboard-question text-emerald-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Exams Taken</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spExams) }}</p>
            <p class="text-xs text-emerald-600 font-medium mt-0.5">{{ $spPassRate }}% pass rate</p>
        </div>
    </div>
    <div class="tr-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-amber-50"><i class="fas fa-certificate text-amber-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">SP Certificates</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spCerts) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Issued</p>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 2 — SECONDARY KPI (Training Sessions)
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
    <div class="tr-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-violet-50"><i class="fas fa-calendar-check text-violet-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Training Sessions</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($totalSessions) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Assigned to you</p>
        </div>
    </div>
    <div class="tr-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-teal-50"><i class="fas fa-user-graduate text-teal-600 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Trainees</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($totalTrainees) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Across packages</p>
        </div>
    </div>
    <div class="tr-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-red-50"><i class="fas fa-award text-red-500 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">Training Certs</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($certsIssued) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Issued by you</p>
        </div>
    </div>
    <div class="tr-card p-5 flex items-center gap-4">
        <div class="kpi-icon bg-slate-50"><i class="fas fa-check-double text-slate-500 text-xl"></i></div>
        <div>
            <p class="text-xs text-slate-500 font-semibold uppercase tracking-wide">SP Completed</p>
            <p class="text-2xl font-bold text-slate-800">{{ number_format($spCompleted) }}</p>
            <p class="text-xs text-slate-400 mt-0.5">Course completions</p>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 3 — ENROLLMENT TREND + EXAM SCORE DISTRIBUTION
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

    {{-- Enrollment Trend --}}
    <div class="tr-card p-6">
        <p class="sec-title"><i class="fas fa-chart-line text-indigo-500"></i> SP Enrollment Trend (8 Weeks)</p>
        <div class="relative h-52">
            <canvas id="enrollTrendChart"
                data-labels="{{ json_encode($enrollLabels) }}"
                data-values="{{ json_encode($enrollTrend) }}">
            </canvas>
        </div>
        <div class="flex items-center gap-4 mt-3 text-xs text-slate-500">
            <span class="flex items-center gap-1.5"><span class="w-3 h-3 rounded-full bg-indigo-500 inline-block"></span> New Enrollments</span>
        </div>
    </div>

    {{-- Exam Score Distribution --}}
    <div class="tr-card p-6">
        <p class="sec-title"><i class="fas fa-chart-bar text-violet-500"></i> Exam Score Distribution</p>
        <div class="relative h-52">
            <canvas id="scoreDistChart"
                data-labels="{{ json_encode(array_keys($scoreRanges)) }}"
                data-values="{{ json_encode(array_values($scoreRanges)) }}">
            </canvas>
        </div>
        <div class="grid grid-cols-4 gap-2 mt-3">
            @php $scoreColors = ['bg-red-100 text-red-700','bg-amber-100 text-amber-700','bg-blue-100 text-blue-700','bg-emerald-100 text-emerald-700']; $si=0; @endphp
            @foreach($scoreRanges as $range => $count)
            <div class="text-center">
                <span class="badge-pill {{ $scoreColors[$si] }}">{{ $range }}</span>
                <p class="text-sm font-bold text-slate-700 mt-1">{{ $count }}</p>
            </div>
            @php $si++; @endphp
            @endforeach
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 4 — COURSE COMPLETION RATES + PASS RATE GAUGE
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    {{-- Course Completion Progress --}}
    <div class="tr-card p-6 lg:col-span-2">
        <p class="sec-title"><i class="fas fa-tasks text-teal-500"></i> Course Completion Rates</p>
        @if($courseStats->isNotEmpty())
        <div class="space-y-4">
            @foreach($courseStats as $course)
            @php
                $rate = $course->enrollments_count > 0 ? round(($course->completed_count/$course->enrollments_count)*100) : 0;
                $barColor = $rate >= 70 ? 'bg-emerald-500' : ($rate >= 40 ? 'bg-amber-400' : 'bg-red-400');
            @endphp
            <div>
                <div class="flex justify-between text-xs text-slate-600 mb-1.5">
                    <span class="font-medium truncate max-w-[60%]">{{ $course->title }}</span>
                    <span class="font-bold text-slate-700">{{ $course->completed_count }}/{{ $course->enrollments_count }} ({{ $rate }}%)</span>
                </div>
                <div class="pbar-wrap">
                    <div class="pbar-fill {{ $barColor }}" style="width:{{ $rate }}%"></div>
                </div>
            </div>
            @endforeach
        </div>
        @else
        <div class="flex flex-col items-center justify-center py-10 text-slate-400">
            <i class="fas fa-book-open text-3xl text-slate-200 mb-2"></i>
            <p class="text-sm">No courses created yet.</p>
        </div>
        @endif
    </div>

    {{-- Pass Rate Gauge + SP Summary --}}
    <div class="tr-card p-6">
        <p class="sec-title"><i class="fas fa-chart-pie text-indigo-500"></i> SP Pass Rate</p>
        <div class="flex flex-col items-center justify-center py-4">
            <div class="relative w-28 h-28 mb-3">
                <canvas id="passRateGauge" data-score="{{ $spPassRate }}"></canvas>
                <div class="absolute inset-0 flex flex-col items-center justify-center">
                    <span class="text-3xl font-bold text-slate-800">{{ $spPassRate }}%</span>
                    <span class="text-xs text-slate-400">Pass Rate</span>
                </div>
            </div>
            <span class="badge-pill {{ $spPassRate >= 70 ? 'bg-emerald-100 text-emerald-700' : ($spPassRate >= 50 ? 'bg-amber-100 text-amber-700' : 'bg-red-100 text-red-700') }} text-sm px-4 py-1.5">
                {{ $spPassRate >= 70 ? 'Excellent' : ($spPassRate >= 50 ? 'Average' : 'Needs Improvement') }}
            </span>
        </div>
        <div class="border-t border-slate-100 pt-4 space-y-3 mt-2">
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-check text-emerald-400 w-4"></i> Passed</span>
                <span class="font-bold text-slate-700">{{ $spPassed }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-times text-red-400 w-4"></i> Failed</span>
                <span class="font-bold text-slate-700">{{ $spExams - $spPassed }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
                <span class="text-slate-500 flex items-center gap-2"><i class="fas fa-clipboard-question text-violet-400 w-4"></i> Total Attempts</span>
                <span class="font-bold text-slate-700">{{ $spExams }}</span>
            </div>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 5 — ENROLLMENT STATUS PIE + UPCOMING SESSIONS
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    {{-- Enrollment Status Pie --}}
    <div class="tr-card p-6">
        <p class="sec-title"><i class="fas fa-chart-pie text-blue-500"></i> Enrollment Status</p>
        @php
            $spPending2 = \App\Models\SelfPaced\Enrollment::whereHas('course', fn($q) => $q->where('created_by', $user->id))->where('status','pending')->count();
        @endphp
        <div class="relative h-44 flex items-center justify-center">
            <canvas id="enrollStatusPie"
                data-active="{{ $spActive }}"
                data-completed="{{ $spCompleted }}"
                data-pending="{{ $spPending2 }}">
            </canvas>
        </div>
        <div class="mt-3 space-y-2">
            <div class="flex items-center justify-between text-xs">
                <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-indigo-500 inline-block"></span> Active</span>
                <span class="font-bold text-slate-700">{{ $spActive }}</span>
            </div>
            <div class="flex items-center justify-between text-xs">
                <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-emerald-500 inline-block"></span> Completed</span>
                <span class="font-bold text-slate-700">{{ $spCompleted }}</span>
            </div>
            <div class="flex items-center justify-between text-xs">
                <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-full bg-amber-400 inline-block"></span> Pending</span>
                <span class="font-bold text-slate-700">{{ $spPending2 }}</span>
            </div>
        </div>
    </div>

    {{-- Upcoming Sessions --}}
    <div class="tr-card p-6 lg:col-span-2">
        <p class="sec-title"><i class="fas fa-clock text-teal-500"></i> Upcoming Training Sessions</p>
        @can('view training sessions')
        @forelse($upcomingSessions as $session)
        @php
            $typeBadge = match($session->session_type) {
                'online'  => ['bg'=>'bg-blue-100','text'=>'text-blue-700','label'=>'Online'],
                'hybrid'  => ['bg'=>'bg-purple-100','text'=>'text-purple-700','label'=>'Hybrid'],
                default   => ['bg'=>'bg-green-100','text'=>'text-green-700','label'=>'In-Person'],
            };
        @endphp
        <div class="session-card mb-3">
            <div class="flex items-start justify-between mb-2">
                <div class="flex-1 min-w-0">
                    <p class="font-semibold text-slate-800 text-sm truncate">{{ $session->session_name }}</p>
                    <p class="text-xs text-slate-500 truncate mt-0.5">{{ $session->trainingPackage?->name ?? 'Unknown Package' }}</p>
                </div>
                <span class="ml-2 flex-shrink-0 badge-pill {{ $typeBadge['bg'] }} {{ $typeBadge['text'] }}">{{ $typeBadge['label'] }}</span>
            </div>
            <div class="flex flex-wrap gap-3 text-xs text-slate-500 mb-3">
                <span class="flex items-center gap-1.5"><i class="fas fa-calendar text-indigo-400"></i> {{ $session->session_date->format('D, d M Y') }}</span>
                <span class="flex items-center gap-1.5"><i class="fas fa-clock text-indigo-400"></i> {{ $session->getFormattedTimeRange() }}</span>
                @if($session->isOnline() && $session->meeting_link)
                <a href="{{ $session->meeting_link }}" target="_blank" class="flex items-center gap-1.5 text-blue-600 hover:underline">
                    <i class="fas fa-video text-blue-400"></i> Join Meeting
                </a>
                @elseif($session->venue_name)
                <span class="flex items-center gap-1.5"><i class="fas fa-map-marker-alt text-red-400"></i> {{ $session->venue_name }}</span>
                @endif
            </div>
            @can('manage training attendance')
            <a href="{{ route('training.sessions.attendance', $session) }}"
               class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-medium rounded-lg transition">
                <i class="fas fa-clipboard-check"></i> Take Attendance
            </a>
            @else
            <a href="{{ route('training.sessions.show', $session) }}"
               class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-medium rounded-lg transition">
                <i class="fas fa-eye"></i> View Session
            </a>
            @endcan
        </div>
        @empty
        <div class="flex flex-col items-center justify-center py-10 text-slate-400">
            <i class="fas fa-calendar-times text-3xl text-slate-200 mb-2"></i>
            <p class="text-sm">No upcoming sessions.</p>
        </div>
        @endforelse
        @endcan
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     ROW 6 — LEADERBOARD + PROFILE
═══════════════════════════════════════════════════════════════ --}}
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

    {{-- Trainee Leaderboard --}}
    @can('view training registrations')
    <div class="tr-card p-6">
        <p class="sec-title"><i class="fas fa-trophy text-amber-500"></i> Trainee Leaderboard</p>
        @forelse($leaderboard->take(8) as $reg)
        @php
            $rank = $loop->iteration;
            $rankStyle = match($rank) {
                1 => 'bg-amber-400 text-white',
                2 => 'bg-slate-300 text-slate-700',
                3 => 'bg-amber-700 text-white',
                default => 'bg-slate-100 text-slate-500',
            };
            $pct = $reg->attendance_percentage ?? 0;
        @endphp
        <div class="leaderboard-row">
            <div class="rank-badge {{ $rankStyle }}">{{ $rank }}</div>
            <div class="flex-1 min-w-0">
                <p class="text-sm font-semibold text-slate-700 truncate">{{ $reg->user?->name ?? 'Unknown' }}</p>
                <p class="text-xs text-slate-400 truncate">{{ $reg->trainingPackage?->name ?? 'N/A' }}</p>
            </div>
            <div class="text-right">
                <p class="text-sm font-bold text-slate-800">{{ $pct }}%</p>
                <p class="text-xs text-slate-400">Attendance</p>
            </div>
        </div>
        @empty
        <div class="flex flex-col items-center justify-center py-8 text-slate-400">
            <i class="fas fa-trophy text-3xl text-slate-200 mb-2"></i>
            <p class="text-sm">No leaderboard data yet.</p>
        </div>
        @endforelse
    </div>
    @endcan

    {{-- Trainer Profile + Quick Actions --}}
    <div class="space-y-6">
        <div class="tr-card p-6">
            <p class="sec-title"><i class="fas fa-user-circle text-indigo-500"></i> Trainer Profile</p>
            <div class="space-y-3">
                <div class="flex justify-between py-2 border-b border-slate-50">
                    <span class="text-slate-500 text-sm">Email</span>
                    <span class="text-slate-800 text-sm font-medium truncate max-w-[60%]">{{ $user->email }}</span>
                </div>
                <div class="flex justify-between py-2 border-b border-slate-50">
                    <span class="text-slate-500 text-sm">Phone</span>
                    <span class="text-slate-800 text-sm">{{ $user->profile?->phone ?? 'Not Set' }}</span>
                </div>
                <div class="flex justify-between py-2 border-b border-slate-50">
                    <span class="text-slate-500 text-sm">Experience</span>
                    <span class="text-slate-800 text-sm font-medium">{{ $expYears }} Years</span>
                </div>
                <div class="flex justify-between py-2 border-b border-slate-50">
                    <span class="text-slate-500 text-sm">Specialization</span>
                    <span class="text-slate-800 text-sm">{{ $specialization }}</span>
                </div>
                <div class="flex justify-between py-2">
                    <span class="text-slate-500 text-sm">Certification</span>
                    <span class="text-slate-800 text-sm">{{ $certification }}</span>
                </div>
            </div>
            <a href="{{ route('profile.edit') }}"
               class="mt-4 inline-flex items-center gap-2 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white text-sm rounded-xl transition">
                <i class="fas fa-edit"></i> Edit Profile
            </a>
        </div>

        <div class="tr-card p-6">
            <p class="sec-title"><i class="fas fa-bolt text-amber-500"></i> Quick Actions</p>
            <div class="grid grid-cols-2 gap-3">
                @can('view training sessions')
                <a href="{{ route('training.sessions.index') }}" class="qa-btn">
                    <i class="fas fa-calendar-check text-xl text-indigo-500"></i>
                    <span class="text-xs text-slate-600 font-medium">Schedule</span>
                </a>
                @endcan
                @can('view training registrations')
                <a href="{{ route('training.registrations.index') }}" class="qa-btn">
                    <i class="fas fa-users text-xl text-blue-500"></i>
                    <span class="text-xs text-slate-600 font-medium">Trainees</span>
                </a>
                @endcan
                @can('view training certificates')
                <a href="{{ route('training.certificates.index') }}" class="qa-btn">
                    <i class="fas fa-award text-xl text-amber-500"></i>
                    <span class="text-xs text-slate-600 font-medium">Certificates</span>
                </a>
                @endcan
                <a href="{{ route('tickets.index') }}" class="qa-btn">
                    <i class="fas fa-comments text-xl text-teal-500"></i>
                    <span class="text-xs text-slate-600 font-medium">Messages</span>
                </a>
            </div>
        </div>
    </div>
</div>

{{-- ═══════════════════════════════════════════════════════════════
     SELF-PACED PORTAL BANNER
═══════════════════════════════════════════════════════════════ --}}
@can('view self-paced courses')
<div class="portal-banner">
    <div class="flex items-center gap-4">
        <div class="w-14 h-14 bg-white/20 rounded-2xl flex items-center justify-center flex-shrink-0">
            <i class="fas fa-graduation-cap text-white text-2xl"></i>
        </div>
        <div>
            <h3 class="text-lg font-bold text-white">Self-Paced Learning Portal</h3>
            <p class="text-indigo-200 text-sm">Create and manage self-paced courses and exams</p>
        </div>
    </div>
    <a href="{{ route('self-paced.dashboard.index') }}"
       class="flex items-center gap-2 px-5 py-2.5 bg-white text-indigo-700 font-semibold rounded-xl hover:bg-indigo-50 transition text-sm flex-shrink-0">
        <i class="fas fa-arrow-right"></i> Open Portal
    </a>
</div>
@endcan

</div>{{-- end px-6 --}}
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Enrollment Trend
    const enrollCanvas = document.getElementById('enrollTrendChart');
    if (enrollCanvas) {
        const labels = JSON.parse(enrollCanvas.dataset.labels || '[]');
        const values = JSON.parse(enrollCanvas.dataset.values || '[]');
        new Chart(enrollCanvas, {
            type: 'line',
            data: {
                labels,
                datasets: [{
                    label: 'Enrollments',
                    data: values,
                    borderColor: '#4f46e5',
                    backgroundColor: 'rgba(79,70,229,0.1)',
                    borderWidth: 2.5,
                    pointRadius: 4,
                    pointBackgroundColor: '#4f46e5',
                    tension: 0.4,
                    fill: true,
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { grid: { display: false }, ticks: { font: { size: 10 }, color: '#94a3b8' } },
                    y: { grid: { color: '#f1f5f9' }, ticks: { font: { size: 10 }, color: '#94a3b8' }, beginAtZero: true }
                }
            }
        });
    }

    // Score Distribution
    const scoreCanvas = document.getElementById('scoreDistChart');
    if (scoreCanvas) {
        const labels = JSON.parse(scoreCanvas.dataset.labels || '[]');
        const values = JSON.parse(scoreCanvas.dataset.values || '[]');
        new Chart(scoreCanvas, {
            type: 'bar',
            data: {
                labels,
                datasets: [{
                    data: values,
                    backgroundColor: ['#ef4444','#f59e0b','#3b82f6','#10b981'],
                    borderRadius: 8,
                    borderSkipped: false,
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { grid: { display: false }, ticks: { font: { size: 11 }, color: '#94a3b8' } },
                    y: { grid: { color: '#f1f5f9' }, ticks: { font: { size: 10 }, color: '#94a3b8' }, beginAtZero: true }
                }
            }
        });
    }

    // Pass Rate Gauge
    const gaugeCanvas = document.getElementById('passRateGauge');
    if (gaugeCanvas) {
        const score = parseInt(gaugeCanvas.dataset.score || 0);
        const color = score >= 70 ? '#10b981' : (score >= 50 ? '#f59e0b' : '#ef4444');
        new Chart(gaugeCanvas, {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: [score, 100 - score],
                    backgroundColor: [color, '#f1f5f9'],
                    borderWidth: 0,
                    circumference: 270,
                    rotation: 225,
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false, cutout: '78%',
                plugins: { legend: { display: false }, tooltip: { enabled: false } }
            }
        });
    }

    // Enrollment Status Pie
    const pieCanvas = document.getElementById('enrollStatusPie');
    if (pieCanvas) {
        const active    = parseInt(pieCanvas.dataset.active || 0);
        const completed = parseInt(pieCanvas.dataset.completed || 0);
        const pending   = parseInt(pieCanvas.dataset.pending || 0);
        new Chart(pieCanvas, {
            type: 'doughnut',
            data: {
                labels: ['Active', 'Completed', 'Pending'],
                datasets: [{
                    data: [active, completed, pending],
                    backgroundColor: ['#4f46e5', '#10b981', '#f59e0b'],
                    borderWidth: 2,
                    borderColor: '#fff',
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false, cutout: '60%',
                plugins: { legend: { display: false } }
            }
        });
    }
});
</script>
@endpush
