<script lang="ts">
	import { page } from '$app/stores';
	import type { PageData } from './$types';

	import Code from 'lucide-svelte/icons/code';

	import { cn } from '$lib/utils';

	import Button from '$lib/components/ui/button/button.svelte';

	export let data: PageData;

	const SCORE_COLORS = ['text-yellow-400', 'text-gray-400', 'text-orange-400'];
</script>

<section class="flex h-full w-full flex-col gap-4">
	<header class="flex flex-col justify-between gap-2 lg:flex-row lg:items-center">
		<div class="flex flex-col">
			<h2 class="text-xl font-semibold">Tableau des scores</h2>
			<p class="text-muted-foreground">Suivez la progression des élèves en direct</p>
		</div>
		<div class="flex gap-2">
			<Button href="/chapters/{$page.params.chapterId}">
				<Code class="mr-2 h-4 w-4" />
				Retourner au chapitre
			</Button>
		</div>
	</header>
	<main class="pb-4">
		<div class="overflow-x-auto">
			<table class="w-full min-w-max table">
				<thead
					class="border-x border-b border-t border-border bg-card/50 text-sm text-muted-foreground"
				>
					<tr>
						<th scope="col" class="text-left">#</th>
						<th scope="col" class="text-left">Equipe</th>
						<th scope="col" class="text-left">Joueurs</th>
						<th scope="col" class="text-right">Score</th>
						<th scope="col" class="text-right">Essais</th>
					</tr>
				</thead>
				<tbody class="border-x border-b border-border bg-card align-middle">
					{#if !data.leaderboard.groups.length}
						<tr>
							<td colspan="5" class="text-center text-muted-foreground">
								Aucun groupe n'a encore de score
							</td>
						</tr>
					{:else}
						{#each data.leaderboard.groups.filter( (g) => g.players.reduce((a, b) => a + b.score, 0) ) as group (group)}
							<tr class={cn(SCORE_COLORS[group.rank - 1])}>
								<td>{group.rank}</td>
								<td>{group.name}</td>
								<td class="text-lg">
									{#if group.players?.length}
										<span>{group.players.map((player) => player?.pseudo).join(', ')} </span>
									{:else}
										<span class="text-muted">Aucun joueur</span>
									{/if}
								</td>
								<td class="text-right">{group.players.reduce((a, b) => a + b.score, 0)}</td>
								<td class="text-right">{group.players.reduce((a, b) => a + b.tries, 0)}</td>
							</tr>
						{/each}
					{/if}
				</tbody>
			</table>
		</div>
	</main>
</section>

<style>
	table > :not(caption) > * > * {
		padding: 0.5rem;
	}
</style>
