<script lang="ts">
	/**
	 * Admin — Podcast-statistikk (oppgave 30.4)
	 *
	 * Dashboard for nedlastingsstatistikk: per episode, trend over tid,
	 * topp-episoder, klientfordeling (Apple/Spotify/andre).
	 * Data fra podcast_download_stats (skrevet av synops-stats CLI).
	 */
	import { page } from '$app/stores';
	import {
		fetchPodcastStats,
		type PodcastStatsResponse,
		type EpisodeTotal,
		type DailyDownloads
	} from '$lib/api';

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

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

	// Filtre
	let days = $state(30);
	let selectedEpisode = $state<string>('');

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

	async function loadData() {
		if (!accessToken) return;
		loading = true;
		error = null;
		try {
			data = await fetchPodcastStats(accessToken, {
				days,
				episode_id: selectedEpisode || undefined
			});
		} catch (e) {
			error = String(e);
		} finally {
			loading = false;
		}
	}

	// Formatering
	function formatNumber(n: number): string {
		return n.toLocaleString('nb-NO');
	}

	function formatDate(d: string): string {
		return new Date(d).toLocaleDateString('nb-NO', { day: 'numeric', month: 'short' });
	}

	// Enkel bar chart: beregn bredde relativt til maks
	function barWidth(value: number, max: number): number {
		if (max === 0) return 0;
		return Math.max(2, (value / max) * 100);
	}

	// Maks nedlastinger for daglig tidsserie (for bar chart)
	const maxDaily = $derived((): number => {
		if (!data || data.daily.length === 0) return 0;
		return Math.max(...data.daily.map((d) => d.downloads));
	});

	// Maks nedlastinger for episode-liste
	const maxEpisode = $derived((): number => {
		if (!data || data.episodes.length === 0) return 0;
		return Math.max(...data.episodes.map((e) => e.total_downloads));
	});

	// Maks klient-antall
	const maxClient = $derived((): number => {
		if (!data || data.clients.length === 0) return 0;
		return Math.max(...data.clients.map((c) => c.count));
	});

	// Totalt klienter for prosentregning
	const totalClientCount = $derived((): number => {
		if (!data) return 0;
		return data.clients.reduce((sum, c) => sum + c.count, 0);
	});

	// Klientfarger
	function clientColor(client: string): string {
		const colors: Record<string, string> = {
			'Apple Podcasts': 'bg-purple-500',
			Spotify: 'bg-green-500',
			Overcast: 'bg-orange-500',
			'Pocket Casts': 'bg-red-500',
			'Podcast Addict': 'bg-blue-500',
			Castro: 'bg-lime-500',
			Castbox: 'bg-amber-500',
			Chrome: 'bg-sky-500',
			Safari: 'bg-cyan-500',
			Firefox: 'bg-rose-500'
		};
		return colors[client] || 'bg-neutral-500';
	}

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

<div class="min-h-screen bg-neutral-950 text-neutral-100 p-4 sm:p-8">
	<div class="max-w-6xl mx-auto space-y-6">
		<!-- Header -->
		<div class="flex items-center justify-between flex-wrap gap-3">
			<h1 class="text-2xl font-bold">Podcast-statistikk</h1>
			<a href="/admin" class="text-sm text-neutral-400 hover:text-white">Tilbake til admin</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}

		<!-- Filtre -->
		<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>

			{#if data && data.episodes.length > 1}
				<select
					bind:value={selectedEpisode}
					class="bg-neutral-800 border border-neutral-700 rounded px-3 py-1.5 text-sm max-w-xs"
					onchange={() => loadData()}
				>
					<option value="">Alle episoder</option>
					{#each data.episodes as ep}
						<option value={ep.episode_id || ''}>
							{ep.episode_title || ep.episode_id?.slice(0, 8) || 'Ukjent'}
						</option>
					{/each}
				</select>
			{/if}

			<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}
			<!-- Nøkkeltall -->
			<section>
				<div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400 mb-1">Nedlastinger</div>
						<div class="text-3xl font-mono font-bold">{formatNumber(data.total_downloads)}</div>
						<div class="text-xs text-neutral-500 mt-1">siste {days} dager</div>
					</div>
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400 mb-1">Unike lyttere</div>
						<div class="text-3xl font-mono font-bold">
							{formatNumber(data.total_unique_listeners)}
						</div>
						<div class="text-xs text-neutral-500 mt-1">siste {days} dager</div>
					</div>
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="text-sm text-neutral-400 mb-1">Episoder</div>
						<div class="text-3xl font-mono font-bold">{data.episodes.length}</div>
						<div class="text-xs text-neutral-500 mt-1">med nedlastinger</div>
					</div>
				</div>
			</section>

			<!-- Daglig trend -->
			{#if data.daily.length > 0}
				<section>
					<h2 class="text-lg font-semibold mb-3">Daglig trend</h2>
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<div class="space-y-1">
							{#each data.daily as day}
								<div class="flex items-center gap-2 text-sm">
									<span class="w-16 text-xs text-neutral-400 font-mono shrink-0">
										{formatDate(day.date)}
									</span>
									<div class="flex-1 flex items-center gap-2">
										<div
											class="h-5 bg-blue-500/60 rounded-sm transition-all"
											style="width: {barWidth(day.downloads, maxDaily())}%"
										></div>
										<span class="text-xs text-neutral-300 shrink-0">
											{formatNumber(day.downloads)}
										</span>
									</div>
								</div>
							{/each}
						</div>
						<div class="mt-3 flex gap-4 text-xs text-neutral-500">
							<span>Nedlastinger per dag (unike IP per episode)</span>
						</div>
					</div>
				</section>
			{/if}

			<!-- Topp-episoder -->
			{#if data.episodes.length > 0}
				<section>
					<h2 class="text-lg font-semibold mb-3">Topp-episoder</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">#</th>
										<th class="px-4 py-3 font-medium">Episode</th>
										<th class="px-4 py-3 font-medium text-right">Nedlastinger</th>
										<th class="px-4 py-3 font-medium text-right hidden sm:table-cell"
											>Unike lyttere</th
										>
										<th class="px-4 py-3 font-medium w-1/4 hidden md:table-cell"></th>
									</tr>
								</thead>
								<tbody>
									{#each data.episodes as ep, i}
										<tr class="border-b border-neutral-800/50 hover:bg-neutral-800/30">
											<td class="px-4 py-2.5 text-neutral-500 font-mono text-xs"
												>{i + 1}</td
											>
											<td class="px-4 py-2.5">
												<div class="font-medium text-neutral-200">
													{ep.episode_title || 'Ukjent episode'}
												</div>
												{#if ep.first_date && ep.last_date}
													<div class="text-xs text-neutral-500 mt-0.5">
														{formatDate(ep.first_date)} – {formatDate(ep.last_date)}
														({ep.days_with_data} dager)
													</div>
												{/if}
											</td>
											<td class="px-4 py-2.5 text-right font-mono text-neutral-200">
												{formatNumber(ep.total_downloads)}
											</td>
											<td
												class="px-4 py-2.5 text-right font-mono text-neutral-400 hidden sm:table-cell"
											>
												{formatNumber(ep.total_unique_listeners)}
											</td>
											<td class="px-4 py-2.5 hidden md:table-cell">
												<div
													class="h-3 bg-blue-500/40 rounded-sm"
													style="width: {barWidth(ep.total_downloads, maxEpisode())}%"
												></div>
											</td>
										</tr>
									{/each}
								</tbody>
							</table>
						</div>
					</div>
				</section>
			{/if}

			<!-- Klientfordeling -->
			{#if data.clients.length > 0}
				<section>
					<h2 class="text-lg font-semibold mb-3">Klienter</h2>
					<div class="bg-neutral-900 border border-neutral-800 rounded-lg p-4">
						<!-- Stacked bar overview -->
						{#if totalClientCount() > 0}
							<div class="h-6 rounded-full overflow-hidden flex mb-4">
								{#each data.clients as client}
									{@const pct = (client.count / totalClientCount()) * 100}
									{#if pct >= 1}
										<div
											class="{clientColor(client.client)} opacity-80"
											style="width: {pct}%"
											title="{client.client}: {formatNumber(client.count)} ({pct.toFixed(1)}%)"
										></div>
									{/if}
								{/each}
							</div>
						{/if}

						<!-- Detaljert liste -->
						<div class="space-y-2">
							{#each data.clients as client}
								{@const pct =
									totalClientCount() > 0
										? (client.count / totalClientCount()) * 100
										: 0}
								<div class="flex items-center gap-3 text-sm">
									<div
										class="w-3 h-3 rounded-full shrink-0 {clientColor(client.client)}"
									></div>
									<span class="w-32 sm:w-40 truncate text-neutral-300">{client.client}</span>
									<div class="flex-1">
										<div
											class="h-4 {clientColor(client.client)} opacity-40 rounded-sm"
											style="width: {barWidth(client.count, maxClient())}%"
										></div>
									</div>
									<span class="font-mono text-xs text-neutral-300 w-14 text-right">
										{formatNumber(client.count)}
									</span>
									<span class="text-xs text-neutral-500 w-12 text-right">
										{pct.toFixed(1)}%
									</span>
								</div>
							{/each}
						</div>
					</div>
				</section>
			{/if}

			<!-- Tom tilstand -->
			{#if data.episodes.length === 0 && data.daily.length === 0}
				<div
					class="bg-neutral-900 border border-neutral-800 rounded-lg p-8 text-center text-neutral-500"
				>
					<p class="text-lg mb-2">Ingen nedlastingsdata</p>
					<p class="text-sm">
						Kjør <code class="bg-neutral-800 px-1.5 py-0.5 rounded text-neutral-400"
							>synops-stats --write</code
						> for å importere statistikk fra Caddy-loggene.
					</p>
				</div>
			{/if}
		{/if}
	</div>
</div>
