<script>
	import { onMount } from 'svelte';
	import { PUBLIC_LEADERBOARD_API_BASE } from '$env/static/public';
	import Footer from '../../components/Footer.svelte';
	
	let selectedPeriod = 'alltime';
	let selectedMode = 'overall';
	let loading = true;
	let error = null;
	
	const periods = [
		{ id: 'monthly', label: 'Monthly', disabled: true },
		{ id: 'season', label: 'Season', disabled: true },
		{ id: 'alltime', label: 'All Time', disabled: false }
	];
	
	const modes = [
		{ id: 'overall', label: 'Cream of the Crop' },
		{ id: 'elytra', label: 'Elytra' },
		{ id: 'parkour', label: 'Parkour' }
	];
	
	// Cache configuration
	const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes in milliseconds
	//const res_origin = 'http://elytramc.net:8080/';

	const API_BASE_URL = PUBLIC_LEADERBOARD_API_BASE + 'api/leaderboards';
	
	// Cache storage
	let cache = {
		overall: { data: null, timestamp: null },
		elytra: { data: null, timestamp: null },
		parkour: { data: null, timestamp: null }
	};
	
	// Current leaderboard data
	let leaderboardData = [];
	
	// Check if cached data is still valid
	function isCacheValid(mode) {
		if (!cache[mode].data || !cache[mode].timestamp) return false;
		const age = Date.now() - cache[mode].timestamp;
		return age < CACHE_DURATION;
	}
	
	// Fetch leaderboard data from API
	async function fetchLeaderboard(mode) {
		// Check cache first
		if (isCacheValid(mode)) {
			console.log(`Using cached data for ${mode}`);
			return cache[mode].data;
		}
		
		console.log(`Fetching fresh data for ${mode}`);
		
		let url;
		if (mode === 'overall') {
			url = `${API_BASE_URL}?type=combined_aggregate`;
		} else if (mode === 'elytra') {
			url = `${API_BASE_URL}?type=aggregate&courseType=elytra`;
		} else if (mode === 'parkour') {
			url = `${API_BASE_URL}?type=aggregate&courseType=parkour`;
		}
		
		try {
			const response = await fetch(url);
			
			if (!response.ok) {
				const errorData = await response.json();
				throw new Error(errorData.error || `HTTP ${response.status}`);
			}
			
			const data = await response.json();
			
			// Cache the result
			cache[mode] = {
				data: data.entries || [],
				timestamp: Date.now()
			};
			
			return cache[mode].data;
		} catch (err) {
			console.error(`Failed to fetch ${mode} leaderboard:`, err);
			throw err;
		}
	}
	
	// Transform API data to match our display format
	function transformApiData(entries, mode) {
		return entries.map((entry, index) => {
			const baseData = {
				rank: index + 1,
				name: entry.playerName,
				uuid: entry.playerUUID,
				face: entry.face,
				texture: entry.texture
			};
			
			if (mode === 'overall') {
				// Combined aggregate - we need to fetch individual scores
				// For now, we'll use totalPoints as the overall score
				return {
					...baseData,
					xp: 0, // Not available in combined aggregate
					overallScore: entry.totalPoints || 0,
					elytraScore: 0, // Would need separate API call
					parkourScore: 0  // Would need separate API call
				};
			} else {
				// Aggregate leaderboard (elytra or parkour)
				return {
					...baseData,
					xp: 0, // Not available in aggregate
					overallScore: 0,
					elytraScore: mode === 'elytra' ? entry.totalPoints : 0,
					parkourScore: mode === 'parkour' ? entry.totalPoints : 0
				};
			}
		});
	}
	
	// Load data for current selection
	async function loadLeaderboard() {
		if (selectedPeriod !== 'alltime') {
			// Don't load if not on all-time (disabled periods)
			return;
		}
		
		loading = true;
		error = null;
		
		try {
			const entries = await fetchLeaderboard(selectedMode);
			leaderboardData = transformApiData(entries, selectedMode);
		} catch (err) {
			error = err.message;
			leaderboardData = [];
		} finally {
			loading = false;
		}
	}
	
	// Reactive statement to reload when selection changes
	$: if (selectedMode || selectedPeriod) {
		loadLeaderboard();
	}
	
	// Load data on mount
	onMount(() => {
		loadLeaderboard();
	});
</script>

<div class="page">
	<div class="container">
		<div class="leaderboard-header">
			<h1>Leaderboards</h1>
			<p>Compete with the best players on our server!</p>
		</div>
		
		<div class="tabs-container">
			<div class="tabs tabs--period">
				{#each periods as period}
					<button 
						class="tab" 
						class:tab--active={selectedPeriod === period.id}
						class:tab--disabled={period.disabled}
						on:click={() => !period.disabled && (selectedPeriod = period.id)}
						disabled={period.disabled}
					>
						{period.label}
					</button>
				{/each}
			</div>
			
			<div class="tabs tabs--mode">
				{#each modes as mode}
					<button 
						class="tab" 
						class:tab--active={selectedMode === mode.id}
						on:click={() => selectedMode = mode.id}
					>
						{mode.label}
					</button>
				{/each}
			</div>
		</div>
		
		<div class="leaderboard-table-wrapper">
			{#if loading}
				<div class="loading-state">
					<div class="spinner"></div>
					<p>Loading leaderboard...</p>
				</div>
			{:else if error}
				<div class="error-state">
					<p>Failed to load leaderboard</p>
					<p class="error-message">{error}</p>
					<button class="retry-button" on:click={() => loadLeaderboard()}>
						Retry
					</button>
				</div>
			{:else if leaderboardData.length === 0}
				<div class="empty-state">
					<p>No leaderboard data available</p>
				</div>
			{:else}
				<table class="leaderboard-table">
					<thead>
						<tr>
							<th class="col-rank">Rank</th>
							<th class="col-player">Player</th>
							<th class="col-stat" style="text-align: center;">Score</th>
						</tr>
					</thead>
					<tbody>
						{#each leaderboardData as player}
							<tr class="leaderboard-row" class:leaderboard-row--top3={player.rank <= 3}>
								<td class="col-rank">
									<span class="rank-badge" class:rank-badge--gold={player.rank === 1} 
										class:rank-badge--silver={player.rank === 2}
										class:rank-badge--bronze={player.rank === 3}>
										{player.rank}
									</span>
								</td>
								<td class="col-player">
									<div class="player-info">
										{#if player.face}
											<img src={player.face} alt={player.name} class="player-avatar" />
										{:else}
											<div class="player-avatar player-avatar--fallback">
												{player.name.charAt(0)}
											</div>
										{/if}
										<span class="player-name">{player.name}</span>
									</div>
								</td>
								<td class="col-stat" style="text-align: center;">
									{#if selectedMode === 'overall'}
										{player.overallScore.toLocaleString()}
									{:else if selectedMode === 'elytra'}
										{player.elytraScore.toLocaleString()}
									{:else if selectedMode === 'parkour'}
										{player.parkourScore.toLocaleString()}
									{/if}
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			{/if}
		</div>
	</div>
</div>

<Footer />

<style lang="scss">
	.page {
		padding: 150px 0 50px;
		min-height: calc(100vh - 400px);
	}
	
	.leaderboard-header {
		text-align: center;
		margin-bottom: 40px;
		
		h1 {
			margin: 0 0 10px 0;
			color: #2c3e50;
			font-size: 36px;
		}
		
		p {
			margin: 0;
			color: #666;
			font-size: 16px;
		}
	}
	
	.tabs-container {
		margin-bottom: 30px;
	}
	
	.tabs {
		display: flex;
		justify-content: center;
		gap: 10px;
		margin-bottom: 15px;
		flex-wrap: wrap;
		
		&--period {
			margin-bottom: 20px;
		}
	}
	
	.tab {
		padding: 12px 30px;
		background: white;
		border: 2px solid #ddd;
		border-radius: 8px;
		cursor: pointer;
		font-weight: 600;
		font-size: 15px;
		color: #555;
		transition: all 0.2s;
		
		&:hover {
			border-color: #3498db;
			color: #3498db;
		}
		
		&--active {
			background: #3498db;
			color: white;
			border-color: #3498db;
			
			&:hover {
				background: #2980b9;
				border-color: #2980b9;
			}
		}
		
		&--disabled {
			opacity: 0.5;
			cursor: not-allowed;
			
			&:hover {
				border-color: #ddd;
				color: #555;
			}
		}
	}
	
	.leaderboard-table-wrapper {
		background: white;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		overflow: hidden;
		min-height: 400px;
	}
	
	.loading-state, .error-state, .empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 20px;
		min-height: 400px;
		
		p {
			font-size: 18px;
			color: #666;
			margin: 10px 0;
		}
	}
	
	.spinner {
		width: 50px;
		height: 50px;
		border: 4px solid #f3f3f3;
		border-top: 4px solid #3498db;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	
	.error-message {
		font-size: 14px !important;
		color: #e74c3c;
		font-family: monospace;
	}
	
	.retry-button {
		margin-top: 20px;
		padding: 10px 24px;
		background: #3498db;
		color: white;
		border: none;
		border-radius: 6px;
		font-size: 16px;
		font-weight: 600;
		cursor: pointer;
		transition: background 0.2s;
		
		&:hover {
			background: #2980b9;
		}
	}
	
	.leaderboard-table {
		width: 100%;
		border-collapse: collapse;
		
		thead {
			background: #f8f9fa;
			
			tr {
				border-bottom: 2px solid #dee2e6;
			}
			
			th {
				padding: 18px 15px;
				text-align: left;
				font-weight: 700;
				color: #2c3e50;
				font-size: 14px;
				text-transform: uppercase;
				letter-spacing: 0.5px;
			}
		}
		
		tbody {
			tr {
				border-bottom: 1px solid #f0f0f0;
				transition: background 0.2s;
				
				&:hover {
					background: #f8f9fa;
				}
				
				&:last-child {
					border-bottom: none;
				}
			}
		}
		
		td {
			padding: 18px 15px;
			color: #555;
			font-size: 15px;
		}
	}
	
	.col-rank {
		width: 80px;
		text-align: center;
	}
	
	.col-player {
		min-width: 200px;
	}
	
	.col-stat {
		text-align: center;
		font-weight: 600;
		color: #2c3e50;
	}
	
	.rank-badge {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 36px;
		height: 36px;
		border-radius: 50%;
		font-weight: 700;
		font-size: 16px;
		background: #ecf0f1;
		color: #7f8c8d;
		
		&--gold {
			background: linear-gradient(135deg, #ffd700, #ffed4e);
			color: #8b6914;
			box-shadow: 0 2px 8px rgba(255, 215, 0, 0.4);
		}
		
		&--silver {
			background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
			color: #5a5a5a;
			box-shadow: 0 2px 8px rgba(192, 192, 192, 0.4);
		}
		
		&--bronze {
			background: linear-gradient(135deg, #cd7f32, #e8a87c);
			color: #5c3317;
			box-shadow: 0 2px 8px rgba(205, 127, 50, 0.4);
		}
	}
	
	.leaderboard-row--top3 {
		background: #fafbfc;
	}
	
	.player-info {
		display: flex;
		align-items: center;
		gap: 12px;
	}
	
	.player-avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		flex-shrink: 0;
		
		&--fallback {
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			color: white;
			display: flex;
			align-items: center;
			justify-content: center;
			font-weight: 700;
			font-size: 18px;
		}
	}
	
	.player-name {
		font-weight: 600;
		color: #2c3e50;
		font-size: 16px;
	}
	
	@media (max-width: 1024px) {
		.leaderboard-table {
			font-size: 14px;
			
			td, th {
				padding: 12px 10px;
			}
		}
		
		.col-stat {
			font-size: 13px;
		}
		
		.player-name {
			font-size: 14px;
		}
	}
	
	@media (max-width: 768px) {
		.page {
			padding: 30px 0;
		}
		
		.leaderboard-header {
			h1 {
				font-size: 28px;
			}
		}
		
		.tabs {
			gap: 5px;
		}
		
		.tab {
			padding: 10px 20px;
			font-size: 14px;
		}
		
		.leaderboard-table-wrapper {
			overflow-x: auto;
		}
		
		.leaderboard-table {
			min-width: 600px;
		}
		
		.player-avatar {
			width: 32px;
			height: 32px;
			font-size: 14px;
		}
		
		.rank-badge {
			width: 32px;
			height: 32px;
			font-size: 14px;
		}
	}
</style>
