@props([
    'leaderboard'  => collect(),
    'refreshUrl'   => null,
])

@php
    $rows = $leaderboard->map(fn($r) => [
        'id'         => $r->id,
        'name'       => $r->user?->name ?? 'Unknown',
        'package'    => $r->trainingPackage?->name ?? 'Unknown Package',
        'attendance' => (float) ($r->attendance_percentage ?? 0),
        'score'      => $r->score !== null ? (float) $r->score : null,
        'passed'     => $r->passed,
        'cert'       => (bool) $r->certificate_issued,
    ])->values()->toArray();
@endphp

<div class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden"
     x-data="{
         sort: 'attendance',
         dir: 'desc',
         rows: {{ Js::from($rows) }},
         get sorted() {
             return [...this.rows].sort((a, b) => {
                 let av = a[this.sort] ?? -1;
                 let bv = b[this.sort] ?? -1;
                 if (typeof av === 'string') av = av.toLowerCase();
                 if (typeof bv === 'string') bv = bv.toLowerCase();
                 if (av < bv) return this.dir === 'desc' ? 1 : -1;
                 if (av > bv) return this.dir === 'desc' ? -1 : 1;
                 return 0;
             });
         },
         toggle(col) {
             if (this.sort === col) {
                 this.dir = this.dir === 'desc' ? 'asc' : 'desc';
             } else {
                 this.sort = col;
                 this.dir = 'desc';
             }
         }
     }">

    <div class="flex items-center justify-between px-6 py-4 border-b border-gray-100">
        <div class="flex items-center gap-2">
            <div class="w-8 h-8 bg-emerald-100 rounded-lg flex items-center justify-center">
                <i class="fas fa-trophy text-emerald-600 text-sm"></i>
            </div>
            <h3 class="text-lg font-semibold text-gray-800">Live Trainee Leaderboard</h3>
        </div>
        @if($refreshUrl)
            <button onclick="window.location.reload()"
                    class="text-xs text-emerald-600 hover:text-emerald-800 flex items-center gap-1 transition">
                <i class="fas fa-sync-alt"></i> Refresh
            </button>
        @endif
    </div>

    @if($leaderboard->isEmpty())
        <div class="flex flex-col items-center justify-center py-12 text-center px-6">
            <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-3">
                <i class="fas fa-users text-gray-400 text-2xl"></i>
            </div>
            <p class="text-gray-500 text-sm">No trainees enrolled in your sessions yet.</p>
            @can('view training registrations')
                <a href="{{ route('training.registrations.index') }}"
                   class="mt-2 text-emerald-600 hover:text-emerald-800 text-sm font-medium transition">
                    View all registrations →
                </a>
            @endcan
        </div>
    @else
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead>
                    <tr class="text-left text-gray-500 bg-gray-50 border-b border-gray-100">
                        <th class="px-4 py-3 font-medium text-xs uppercase tracking-wide w-10">#</th>
                        <th class="px-4 py-3 font-medium text-xs uppercase tracking-wide cursor-pointer hover:text-gray-800 select-none"
                            @click="toggle('name')">
                            <span class="flex items-center gap-1">
                                Trainee
                                <span x-show="sort === 'name'" x-text="dir === 'desc' ? '↓' : '↑'" class="text-emerald-500"></span>
                            </span>
                        </th>
                        <th class="px-4 py-3 font-medium text-xs uppercase tracking-wide">Package</th>
                        <th class="px-4 py-3 font-medium text-xs uppercase tracking-wide cursor-pointer hover:text-gray-800 select-none"
                            @click="toggle('attendance')">
                            <span class="flex items-center gap-1">
                                Attendance
                                <span x-show="sort === 'attendance'" x-text="dir === 'desc' ? '↓' : '↑'" class="text-emerald-500"></span>
                            </span>
                        </th>
                        <th class="px-4 py-3 font-medium text-xs uppercase tracking-wide cursor-pointer hover:text-gray-800 select-none"
                            @click="toggle('score')">
                            <span class="flex items-center gap-1">
                                Score
                                <span x-show="sort === 'score'" x-text="dir === 'desc' ? '↓' : '↑'" class="text-emerald-500"></span>
                            </span>
                        </th>
                        <th class="px-4 py-3 font-medium text-xs uppercase tracking-wide">Status</th>
                        @can('view training certificates')
                        <th class="px-4 py-3 font-medium text-xs uppercase tracking-wide">Certificate</th>
                        @endcan
                    </tr>
                </thead>
                <tbody>
                    <template x-for="(row, i) in sorted" :key="row.id">
                        <tr class="odd:bg-white even:bg-gray-50 hover:bg-gray-100 transition-colors border-b border-gray-100 last:border-0">
                            <td class="px-4 py-3">
                                <span class="text-gray-400 font-medium" x-text="i + 1"></span>
                            </td>
                            <td class="px-4 py-3">
                                <div class="flex items-center gap-2">
                                    <div class="w-7 h-7 bg-emerald-100 rounded-full flex items-center justify-center flex-shrink-0">
                                        <span class="text-emerald-700 text-xs font-bold"
                                              x-text="row.name.charAt(0).toUpperCase()"></span>
                                    </div>
                                    <span class="font-medium text-gray-800 truncate max-w-[120px]" x-text="row.name"></span>
                                </div>
                            </td>
                            <td class="px-4 py-3">
                                <span class="text-gray-500 text-xs truncate max-w-[140px] block" x-text="row.package"></span>
                            </td>
                            <td class="px-4 py-3">
                                <div class="flex items-center gap-2 min-w-[100px]">
                                    <div class="flex-1 bg-gray-200 rounded-full h-1.5">
                                        <div class="bg-emerald-500 h-1.5 rounded-full transition-all"
                                             :style="`width: ${Math.min(row.attendance, 100)}%`"></div>
                                    </div>
                                    <span class="text-xs text-gray-600 w-9 text-right flex-shrink-0"
                                          x-text="row.attendance.toFixed(0) + '%'"></span>
                                </div>
                            </td>
                            <td class="px-4 py-3">
                                <span class="text-gray-700 text-sm"
                                      x-text="row.score !== null ? row.score.toFixed(1) : '—'"></span>
                            </td>
                            <td class="px-4 py-3">
                                <span x-show="row.passed === true"
                                      class="px-2 py-0.5 bg-green-100 text-green-700 rounded-full text-xs font-medium">Pass</span>
                                <span x-show="row.passed === false"
                                      class="px-2 py-0.5 bg-red-100 text-red-700 rounded-full text-xs font-medium">Fail</span>
                                <span x-show="row.passed === null"
                                      class="px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full text-xs font-medium">In Progress</span>
                            </td>
                            @can('view training certificates')
                            <td class="px-4 py-3">
                                <span x-show="row.cert"
                                      class="px-2 py-0.5 bg-purple-100 text-purple-700 rounded-full text-xs font-medium">Issued</span>
                                <span x-show="!row.cert"
                                      class="text-gray-400 text-xs">—</span>
                            </td>
                            @endcan
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>

        <div class="px-6 py-3 bg-gray-50 border-t border-gray-100 flex items-center justify-between">
            <span class="text-xs text-gray-400">
                Showing <span class="font-medium text-gray-600" x-text="sorted.length"></span> trainees
            </span>
            @can('view training registrations')
                <a href="{{ route('training.registrations.index') }}"
                   class="text-xs text-emerald-600 hover:text-emerald-800 font-medium transition">
                    View all →
                </a>
            @endcan
        </div>
    @endif
</div>
