<script lang="ts">
	/**
	 * Profil — Mitt forbruk (oppgave 15.9)
	 *
	 * Viser innlogget brukers eget ressursforbruk med
	 * totalkort, daglig tidsserie og grafstatistikk.
	 */
	import { page } from '$app/stores';
	import {
		fetchMyUsage,
		type UserUsageResponse
	} from '$lib/api';

	const session = $derived($page.data.session as Record<string, unknown> | undefined);
	const accessToken = $derived(session?.accessToken as string | undefined);
	const user = $derived(session?.user as Record<string, unknown> | undefined);

	let data = $state<UserUsageResponse | null>(null);
	let error = $state<string | null>(null);
	let loading = $state(false);
	let days = $state(30);

	$effect(() => {
		if (!accessToken) return;
		loadData();
	});

	async function loadData() {
		if (!accessToken) return;
		loading = true;
		error = null;
		try {
			data = await fetchMyUsage(accessToken, { days });
		} catch (e) {
			error = String(e);
		} finally {
			loading = false;
		}
	}

	// Formateringshjelper (samme som admin/usage)
	function formatResourceValue(type: string, value: number, secondary?: number): string {
		switch (type) {
			case 'ai': {
				const tokIn = formatNumber(value);
				const tokOut = secondary ? formatNumber(secondary) : '0';
				return `${tokIn} inn / ${tokOut} ut tokens`;
			}
			case 'whisper': {
				const hours = value / 3600;
				if (hours >= 1) return `${hours.toFixed(1)} timer`;
				const mins = value / 60;
				return `${mins.toFixed(0)} min`;
			}
			case 'tts':
				return `${formatNumber(value)} tegn`;
			case 'cas':
			case 'bandwidth':
				return formatBytes(value);
			case 'livekit': {
				const hours = value / 60;
				if (hours >= 1) return `${hours.toFixed(1)} timer`;
				return `${value.toFixed(0)} min`;
			}
			default:
				return formatNumber(value);
		}
	}

	function formatNumber(n: number): string {
		if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
		if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
		return n.toFixed(0);
	}

	function formatBytes(bytes: number): string {
		if (bytes === 0) return '0 B';
		const units = ['B', 'KB', 'MB', 'GB', 'TB'];
		const i = Math.floor(Math.log(bytes) / Math.log(1024));
		return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
	}

	function resourceTypeLabel(type: string): string {
		const labels: Record<string, string> = {
			ai: 'AI (LLM)',
			whisper: 'Whisper (transkripsjon)',
			tts: 'TTS (tekst-til-tale)',
			cas: 'CAS (lagring)',
			bandwidth: 'Bandbredde',
			livekit: 'LiveKit (sanntid)'
		};
		return labels[type] || type;
	}

	function resourceTypeIcon(type: string): string {
		const icons: Record<string, string> = {
			ai: 'AI',
			whisper: 'STT',
			tts: 'TTS',
			cas: 'CAS',
			bandwidth: 'BW',
			livekit: 'LK'
		};
		return icons[type] || type.slice(0, 3).toUpperCase();
	}

	function resourceTypeColor(type: string): string {
		const colors: Record<string, string> = {
			ai: 'bg-purple-500/20 text-purple-300 border-purple-500/30',
			whisper: 'bg-blue-500/20 text-blue-300 border-blue-500/30',
			tts: 'bg-green-500/20 text-green-300 border-green-500/30',
			cas: 'bg-amber-500/20 text-amber-300 border-amber-500/30',
			bandwidth: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30',
			livekit: 'bg-pink-500/20 text-pink-300 border-pink-500/30'
		};
		return colors[type] || 'bg-neutral-500/20 text-neutral-300 border-neutral-500/30';
	}

	const daysOptions = [
		{ value: 7, label: '7 dager' },
		{ value: 30, label: '30 dager' },
		{ value: 90, label: '90 dager' },
		{ value: 365, label: '1 ar' }
	];
</script>

<div class="min-h-screen bg-neutral-950 text-neutral-100 p-4 sm:p-8">
	<div class="max-w-4xl mx-auto space-y-6">
		<!-- Header -->
		<div class="flex items-center justify-between flex-wrap gap-3">
			<div>
				<h1 class="text-2xl font-bold">Min profil</h1>
				{#if user?.name}
					<p class="text-neutral-400 text-sm mt-1">{user.name}</p>
				{/if}
			</div>
			<a href="/" class="text-sm text-neutral-400 hover:text-white">Tilbake</a>
		</div>

		{#if error}
			<div class="bg-red-900/30 border border-red-700 rounded-lg p-4 text-red-300 text-sm">
				{error}
			</div>
		{/if}

		<!-- Tidsperiode-velger -->
		<div class="flex flex-wrap gap-3 items-center">
			<select
				bind:value={days}
				class="bg-neutral-800 border border-neutral-700 rounded px-3 py-1.5 text-sm"
				onchange={() => loadData()}
			>
				{#each daysOptions as opt}
					<option value={opt.value}>{opt.label}</option>
				{/each}
			</select>

			<button
				class="bg-neutral-800 hover:bg-neutral-700 px-3 py-1.5 rounded text-sm"
				onclick={() => loadData()}
				disabled={loading}
			>
				{loading ? 'Laster...' : 'Oppdater'}
			</button>
		</div>

		{#if !data && !error}
			<p class="text-neutral-500">Laster...</p>
		{:else if data}
			<!-- Grafstatistikk -->
			<section>
				<h2 class="text-lg font-semibold mb-3">Graf</h2>
				<div class="grid grid-cols-2 gap-3">
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400 mb-1">Noder opprettet</div>
						<div class="text-2xl font-mono">{data.graph.nodes_created.toLocaleString('nb-NO')}</div>
					</div>
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400 mb-1">Edges opprettet</div>
						<div class="text-2xl font-mono">{data.graph.edges_created.toLocaleString('nb-NO')}</div>
					</div>
				</div>
			</section>

			<!-- Totaler per ressurstype -->
			<section>
				<h2 class="text-lg font-semibold mb-3">Mitt forbruk ({days} dager)</h2>
				<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
					{#each data.by_type as row}
						<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
							<div class="flex items-center gap-2 mb-2">
								<span
									class="text-xs font-bold px-2 py-0.5 rounded border {resourceTypeColor(row.resource_type)}"
								>
									{resourceTypeIcon(row.resource_type)}
								</span>
								<span class="text-sm text-neutral-400">{resourceTypeLabel(row.resource_type)}</span>
							</div>
							<div class="text-xl font-mono">
								{formatResourceValue(row.resource_type, row.total_value, row.secondary_value)}
							</div>
							<div class="text-xs text-neutral-500 mt-1">
								{row.event_count.toLocaleString('nb-NO')} hendelser
							</div>
						</div>
					{/each}
					{#if data.by_type.length === 0}
						<div class="col-span-full text-neutral-500 text-sm">
							Ingen ressursforbruk registrert i perioden.
						</div>
					{/if}
				</div>
			</section>

			<!-- Daglig tidsserie -->
			{#if data.daily.length > 0}
				<section>
					<h2 class="text-lg font-semibold mb-3">Daglig aktivitet</h2>
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg overflow-hidden">
						<div class="overflow-x-auto">
							<table class="w-full text-sm">
								<thead>
									<tr class="border-b border-neutral-800 text-left text-neutral-400">
										<th class="px-4 py-3 font-medium">Dato</th>
										<th class="px-4 py-3 font-medium">Ressurstype</th>
										<th class="px-4 py-3 font-medium text-right">Forbruk</th>
										<th class="px-4 py-3 font-medium text-right">Hendelser</th>
									</tr>
								</thead>
								<tbody>
									{#each data.daily as row}
										<tr class="border-b border-neutral-800/50 hover:bg-neutral-800/30">
											<td class="px-4 py-2.5 font-mono text-xs">
												{new Date(row.day).toLocaleDateString('nb-NO')}
											</td>
											<td class="px-4 py-2.5">
												<span
													class="text-xs font-bold px-2 py-0.5 rounded border {resourceTypeColor(row.resource_type)}"
												>
													{resourceTypeIcon(row.resource_type)}
												</span>
												<span class="ml-2 text-neutral-300">{resourceTypeLabel(row.resource_type)}</span>
											</td>
											<td class="px-4 py-2.5 text-right font-mono text-neutral-200">
												{formatResourceValue(row.resource_type, row.total_value)}
											</td>
											<td class="px-4 py-2.5 text-right text-neutral-400">
												{row.event_count.toLocaleString('nb-NO')}
											</td>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</div>
				</section>
			{/if}
		{/if}
	</div>
</div>
