<script lang="ts">
	import { browser } from "$app/environment";
	import { goto } from "$app/navigation";
	import { onMount } from "svelte";
	import { enhance } from '$app/forms';
	import AuthModal from "$lib/components/AuthModal.svelte";
	import { 
		getGradeColor, 
		formatDate, 
		getStreakMessage, 
		getPerformanceMessage,
		type UserStats 
	} from "$lib/utils/stats";

	interface PageData {
		stats: UserStats | null;
		error?: string;
		user?: any;
		session?: any;
		requiresAuth?: boolean;
	}

	let { data }: { data: PageData } = $props();
	let authModalOpen = $state(false);

	let loading = $state(true);

	function getOrCreateAnonymousId(): string {
		if (!browser) return "";
		const key = "bibdle-anonymous-id";
		let id = localStorage.getItem(key);
		if (!id) {
			id = crypto.randomUUID();
			localStorage.setItem(key, id);
		}
		return id;
	}

	onMount(async () => {
		loading = false;
	});

	function getGradePercentage(count: number, total: number): number {
		return total > 0 ? Math.round((count / total) * 100) : 0;
	}

	$inspect(data);
</script>

<svelte:head>
	<title>Stats | Bibdle</title>
	<meta name="description" content="View your Bibdle game statistics and performance" />
</svelte:head>

<div class="min-h-screen bg-gradient-to-br from-amber-50 to-orange-100 p-4">
	<div class="max-w-4xl mx-auto">
		<!-- Header -->
		<div class="text-center mb-8">
			<h1 class="text-4xl font-bold text-gray-800 mb-2">Your Stats</h1>
			<p class="text-gray-600">Track your Bibdle performance over time</p>
			<div class="mt-4">
				<a 
					href="/"
					class="inline-flex items-center px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors"
				>
					← Back to Game
				</a>
			</div>
		</div>

		{#if loading}
			<div class="text-center py-12">
				<div class="inline-block w-8 h-8 border-4 border-amber-600 border-t-transparent rounded-full animate-spin"></div>
				<p class="mt-4 text-gray-600">Loading your stats...</p>
			</div>
		{:else if data.requiresAuth}
			<div class="text-center py-12">
				<div class="bg-blue-100 border border-blue-300 rounded-lg p-8 max-w-md mx-auto">
					<h2 class="text-2xl font-bold text-blue-800 mb-4">Authentication Required</h2>
					<p class="text-blue-700 mb-6">You must be logged in to see your stats.</p>
					<div class="flex flex-col gap-3">
						<button
							onclick={() => authModalOpen = true}
							class="inline-flex items-center justify-center px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
						>
							🔐 Sign In / Sign Up
						</button>
						<a 
							href="/" 
							class="inline-flex items-center justify-center px-6 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors font-medium"
						>
							← Back to Game
						</a>
					</div>
				</div>
			</div>
		{:else if data.error}
			<div class="text-center py-12">
				<div class="bg-red-100 border border-red-300 rounded-lg p-6 max-w-md mx-auto">
					<p class="text-red-700">{data.error}</p>
					<a 
						href="/" 
						class="mt-4 inline-block px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition-colors"
					>
						Return to Game
					</a>
				</div>
			</div>
		{:else if !data.stats}
			<div class="text-center py-12">
				<div class="bg-yellow-100 border border-yellow-300 rounded-lg p-6 max-w-md mx-auto">
					<p class="text-yellow-700">No stats available.</p>
					<a 
						href="/" 
						class="mt-4 inline-block px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 transition-colors"
					>
						Start Playing
					</a>
				</div>
			</div>
		{:else}
			{@const stats = data.stats}
			
			<!-- Overview Cards -->
			<div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
				<!-- Total Solves -->
				<div class="bg-white rounded-lg shadow-md p-6">
					<div class="text-center">
						<div class="text-3xl font-bold text-amber-600 mb-2">{stats.totalSolves}</div>
						<div class="text-gray-600">Total Solves</div>
						{#if stats.totalSolves > 0}
							<div class="text-sm text-gray-500 mt-1">
								{getPerformanceMessage(stats.avgGuesses)}
							</div>
						{/if}
					</div>
				</div>

				<!-- Average Guesses -->
				<div class="bg-white rounded-lg shadow-md p-6">
					<div class="text-center">
						<div class="text-3xl font-bold text-blue-600 mb-2">{stats.avgGuesses}</div>
						<div class="text-gray-600">Avg. Guesses</div>
						<div class="text-sm text-gray-500 mt-1">per solve</div>
					</div>
				</div>

				<!-- Current Streak -->
				<div class="bg-white rounded-lg shadow-md p-6">
					<div class="text-center">
						<div class="text-3xl font-bold text-green-600 mb-2">{stats.currentStreak}</div>
						<div class="text-gray-600">Current Streak</div>
						<div class="text-sm text-gray-500 mt-1">
							{getStreakMessage(stats.currentStreak)}
						</div>
					</div>
				</div>
			</div>

			<!-- Grade Distribution -->
			{#if stats.totalSolves > 0}
				<div class="bg-white rounded-lg shadow-md p-6 mb-8">
					<h2 class="text-2xl font-bold text-gray-800 mb-4">Grade Distribution</h2>
					<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
						{#each Object.entries(stats.gradeDistribution) as [grade, count]}
							{@const percentage = getGradePercentage(count, stats.totalSolves)}
							<div class="text-center">
								<div class="mb-2">
									<span class="inline-block px-3 py-1 rounded-full text-sm font-semibold {getGradeColor(grade)}">
										{grade}
									</span>
								</div>
								<div class="text-2xl font-bold text-gray-800">{count}</div>
								<div class="text-sm text-gray-500">{percentage}%</div>
							</div>
						{/each}
					</div>
				</div>

				<!-- Streak Info -->
				<div class="bg-white rounded-lg shadow-md p-6 mb-8">
					<h2 class="text-2xl font-bold text-gray-800 mb-4">Streak Information</h2>
					<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
						<div class="text-center">
							<div class="text-3xl font-bold text-green-600 mb-2">{stats.currentStreak}</div>
							<div class="text-gray-600">Current Streak</div>
						</div>
						<div class="text-center">
							<div class="text-3xl font-bold text-purple-600 mb-2">{stats.bestStreak}</div>
							<div class="text-gray-600">Best Streak</div>
						</div>
					</div>
				</div>

				<!-- Recent Performance -->
				{#if stats.recentCompletions.length > 0}
					<div class="bg-white rounded-lg shadow-md p-6">
						<h2 class="text-2xl font-bold text-gray-800 mb-4">Recent Performance</h2>
						<div class="space-y-3">
							{#each stats.recentCompletions as completion}
								<div class="flex justify-between items-center py-2 border-b border-gray-100 last:border-b-0">
									<div>
										<span class="font-medium">{formatDate(completion.date)}</span>
									</div>
									<div class="flex items-center gap-3">
										<span class="text-gray-600">{completion.guessCount} guess{completion.guessCount === 1 ? '' : 'es'}</span>
										<span class="px-2 py-1 rounded text-sm font-semibold {getGradeColor(completion.grade)}">
											{completion.grade}
										</span>
									</div>
								</div>
							{/each}
						</div>
					</div>
				{/if}
			{/if}
		{/if}
	</div>
</div>

<AuthModal bind:isOpen={authModalOpen} anonymousId={""} />