<script lang="ts">
	import { onMount } from 'svelte';
	import { api } from '$lib/api/client';
	import { t } from '$lib/i18n';
	import { calculateLevel } from '$lib/utils/level';
	import type { LeaderboardMode } from '$lib/constants/config';

	type TabType = 'player' | 'alliance' | 'country';

	let activeTab: TabType = 'player';
	let activeMode: LeaderboardMode = 'all-time';
	let loading = true;
	let error = '';
	let playerData: any[] = [];
	let allianceData: any[] = [];
	let countryData: any[] = [];

	const modes: LeaderboardMode[] = ['today', 'week', 'month', 'all-time'];

	onMount(() => {
		loadLeaderboard();
	});

	$: {
		activeTab;
		activeMode;
		loadLeaderboard();
	}

	async function loadLeaderboard() {
		loading = true;
		error = '';

		try {
			if (activeTab === 'player') {
				const result = await api.getPlayerLeaderboard(activeMode);
				playerData = result?.players || [];
			} else if (activeTab === 'alliance') {
				const result = await api.getAllianceLeaderboardGlobal(activeMode);
				allianceData = result?.alliances || [];
			} else if (activeTab === 'country') {
				const result = await api.getCountryLeaderboard(activeMode);
				countryData = result?.countries || [];
			}
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to load leaderboard';
		} finally {
			loading = false;
		}
	}

	function getModeLabel(mode: LeaderboardMode): string {
		const labels: Record<LeaderboardMode, string> = {
			'today': 'Today',
			'week': 'This Week',
			'month': 'This Month',
			'all-time': 'All Time'
		};
		return labels[mode];
	}
</script>

<svelte:head>
	<title>Leaderboard - FurryPlace</title>
</svelte:head>

<div class="mx-auto max-w-6xl px-4 py-6">
	<h1 class="text-3xl font-bold mb-6">Leaderboard</h1>

	<!-- Tabs -->
	<div class="tabs tabs-boxed mb-6">
		<button class="tab" class:tab-active={activeTab === 'player'} on:click={() => (activeTab = 'player')}>
			Players
		</button>
		<button class="tab" class:tab-active={activeTab === 'alliance'} on:click={() => (activeTab = 'alliance')}>
			Alliances
		</button>
		<button class="tab" class:tab-active={activeTab === 'country'} on:click={() => (activeTab = 'country')}>
			Countries
		</button>
	</div>

	<!-- Mode Selection -->
	<div class="flex gap-2 mb-6 flex-wrap">
		{#each modes as mode}
			<button
				class="btn btn-sm"
				class:btn-primary={activeMode === mode}
				class:btn-ghost={activeMode !== mode}
				on:click={() => (activeMode = mode)}
			>
				{getModeLabel(mode)}
			</button>
		{/each}
	</div>

	{#if error}
		<div class="alert alert-error">
			<span>{error}</span>
		</div>
	{:else if loading}
		<div class="flex justify-center py-12">
			<span class="loading loading-spinner loading-lg"></span>
		</div>
	{:else}
		<div class="card bg-base-100 shadow-xl">
			<div class="card-body p-0">
				{#if activeTab === 'player'}
					<div class="overflow-x-auto">
						<table class="table table-zebra">
							<thead>
								<tr>
									<th>Rank</th>
									<th>Player</th>
									<th>Level</th>
									<th>Pixels</th>
									{#if playerData[0]?.alliance}
										<th>Alliance</th>
									{/if}
								</tr>
							</thead>
							<tbody>
								{#each playerData as player, i}
									<tr>
										<td>
											<span class="font-bold">#{i + 1}</span>
										</td>
										<td>
											<div class="flex items-center gap-2">
												<div class="avatar placeholder">
													<div class="bg-primary text-primary-content rounded-full w-8">
														<span class="text-xs">{player.name[0].toUpperCase()}</span>
													</div>
												</div>
												<span>{player.name}</span>
											</div>
										</td>
										<td>{calculateLevel(player.pixelsPainted)}</td>
										<td>{player.pixelsPainted.toLocaleString()}</td>
										{#if player.alliance}
											<td>{player.alliance.name || '-'}</td>
										{/if}
									</tr>
								{:else}
									<tr>
										<td colspan="5" class="text-center text-base-content/60">No data available</td>
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				{:else if activeTab === 'alliance'}
					<div class="overflow-x-auto">
						<table class="table table-zebra">
							<thead>
								<tr>
									<th>Rank</th>
									<th>Alliance</th>
									<th>Members</th>
									<th>Pixels</th>
								</tr>
							</thead>
							<tbody>
								{#each allianceData as alliance, i}
									<tr>
										<td>
											<span class="font-bold">#{i + 1}</span>
										</td>
										<td>
											<span class="font-semibold">{alliance.name}</span>
										</td>
										<td>{alliance.memberCount || alliance._count?.members || '-'}</td>
										<td>{alliance.pixelsPainted.toLocaleString()}</td>
									</tr>
								{:else}
									<tr>
										<td colspan="4" class="text-center text-base-content/60">No data available</td>
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				{:else if activeTab === 'country'}
					<div class="overflow-x-auto">
						<table class="table table-zebra">
							<thead>
								<tr>
									<th>Rank</th>
									<th>Country</th>
									<th>Pixels</th>
								</tr>
							</thead>
							<tbody>
								{#each countryData as country, i}
									<tr>
										<td>
											<span class="font-bold">#{i + 1}</span>
										</td>
										<td>
											<span class="font-semibold">{country.country}</span>
										</td>
										<td>{country.pixelsPainted.toLocaleString()}</td>
									</tr>
								{:else}
									<tr>
										<td colspan="3" class="text-center text-base-content/60">No data available</td>
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				{/if}
			</div>
		</div>
	{/if}
</div>
