<script lang="ts">
	import { deleteGame, listGames, saveGame, searchSmashGames } from '$lib/api/games';
	import { errorReporter } from '$lib/api/errors';
	import type { GameDTO } from '$lib/api/schema-helpers';
	import { requireSession } from '$lib/auth/guard.svelte';
	import { blankDraft, isDirty, nextOrder, toDraft, toDto, type Draft } from '$lib/games/draft';
	import {
		alertError,
		alertNotice,
		card,
		cardHeading,
		danger,
		field,
		ghost,
		label,
		listRow,
		listRowSelected,
		primary
	} from '$lib/ui/classes';

	let games = $state<GameDTO[]>([]);
	let draft = $state<Draft>({ ...blankDraft });
	/** The draft as it was last loaded or saved; `dirty` compares against it. */
	let pristine = $state<Draft>({ ...blankDraft });
	let smashMatches = $state<GameDTO[] | null>(null);

	let loading = $state(false);
	let saving = $state(false);
	let deleting = $state(false);
	let searching = $state(false);
	let notice = $state<string | null>(null);
	let error = $state<string | null>(null);

	const ordered = $derived([...games].sort((a, b) => (a.order ?? 0) - (b.order ?? 0)));
	const isNew = $derived(draft.id === 0);
	const dirty = $derived(isDirty(draft, pristine));
	const canSave = $derived(draft.name.trim() !== '' && !saving);
	/** The provider searches start.gg by name; the long name is the one that matches. */
	const searchTerm = $derived(draft.longName.trim() || draft.name.trim());

	const guard = requireSession(() => void refresh());

	const report = errorReporter((message) => (error = message));

	function load(game: GameDTO) {
		draft = toDraft(game);
		pristine = { ...draft };
		smashMatches = null;
	}

	async function refresh(keepId = draft.id) {
		loading = true;
		error = null;
		try {
			games = await listGames();
			// Re-read the edited game so the form shows what the server actually stored.
			const current = games.find((game) => game.id === keepId);
			if (current) load(current);
			else if (keepId !== 0) reset();
		} catch (cause) {
			report(cause, 'Could not load the game list.');
		} finally {
			loading = false;
		}
	}

	function reset() {
		draft = { ...blankDraft, order: nextOrder(games) };
		pristine = { ...draft };
		smashMatches = null;
	}

	function select(game: GameDTO) {
		if (game.id === draft.id) return;
		if (dirty && !confirm('Discard the unsaved changes to this game?')) return;
		load(game);
		notice = null;
		error = null;
	}

	function startNew() {
		if (dirty && !confirm('Discard the unsaved changes to this game?')) return;
		reset();
		notice = null;
		error = null;
	}

	async function save() {
		if (!canSave) return;

		saving = true;
		error = null;
		notice = null;
		const creating = isNew;
		try {
			const saved = await saveGame(toDto(draft));
			notice = creating ? `Created "${saved.name}".` : `Saved "${saved.name}".`;
			await refresh(saved.id ?? 0);
		} catch (cause) {
			report(cause, 'Could not save this game.');
		} finally {
			saving = false;
		}
	}

	async function remove() {
		if (isNew || deleting) return;
		if (!confirm(`Delete "${draft.name}"? This cannot be undone.`)) return;

		deleting = true;
		error = null;
		notice = null;
		try {
			await deleteGame(draft.id);
			notice = `Deleted "${draft.name}".`;
			reset();
			await refresh(0);
		} catch (cause) {
			// The service swallows DbUpdateException and answers 404, so an FK clash
			// and a missing row are indistinguishable from here.
			report(
				cause,
				'Delete failed — the game may already be gone, or still be attached to tournaments.'
			);
		} finally {
			deleting = false;
		}
	}

	async function findOnSmash() {
		if (searchTerm === '' || searching) return;

		searching = true;
		error = null;
		try {
			smashMatches = await searchSmashGames(searchTerm);
			if (smashMatches.length === 0) notice = `start.gg has no game matching "${searchTerm}".`;
		} catch (cause) {
			report(cause, `Could not search start.gg for "${searchTerm}".`);
		} finally {
			searching = false;
		}
	}
</script>

<svelte:head>
	<title>Games · LaDOSE</title>
</svelte:head>

<main id="main" class="mx-auto max-w-5xl px-4 py-10">
	{#if guard.ready}
	<header class="mb-8">
		<h1 class="text-3xl font-semibold tracking-tight">Games</h1>
		<p class="mt-1 text-sm text-muted">
			The catalogue behind rankings, WordPress tags and start.gg bracket matching.
		</p>
	</header>

	{#if error}
		<p role="alert" class="{alertError} mb-4">
			{error}
		</p>
	{/if}
	{#if notice}
		<p class="{alertNotice} mb-4">{notice}</p>
	{/if}

	<div class="grid gap-6 md:grid-cols-[18rem_1fr] md:items-start">
		<section class={card}>
			<div class="flex items-baseline justify-between gap-3">
				<h2 class={cardHeading}>
					Catalogue
					<span class="ml-1 font-normal text-muted normal-case">({games.length})</span>
				</h2>
				<button class={ghost} onclick={() => refresh()} disabled={loading}>
					{loading ? '…' : 'Reload'}
				</button>
			</div>

			<ul class="mt-4 max-h-[26rem] space-y-1 overflow-y-auto pr-1 text-sm">
				{#each ordered as game (game.id)}
					<li>
						<button
							onclick={() => select(game)}
							class="{draft.id === game.id ? listRowSelected : listRow} flex items-center gap-3"
						>
							<span class="w-6 shrink-0 text-right text-xs text-subtle">{game.order}</span>
							<span class="truncate">{game.name}</span>
						</button>
					</li>
				{:else}
					<li class="px-2 py-6 text-center text-subtle">
						{loading ? 'Loading…' : 'No game yet.'}
					</li>
				{/each}
			</ul>

			<button class="{primary} mt-4 w-full" onclick={startNew}>New game</button>
		</section>

		<section class={card}>
			<div class="flex flex-wrap items-baseline justify-between gap-3">
				<h2 class={cardHeading}>
					{isNew ? 'New game' : `Editing #${draft.id}`}
				</h2>
				{#if dirty}
					<span class="rounded-full bg-warning-soft px-2 py-0.5 text-xs text-warning">
						Unsaved changes
					</span>
				{/if}
			</div>

			<form
				class="mt-5 grid gap-4 sm:grid-cols-2"
				onsubmit={(event) => {
					event.preventDefault();
					void save();
				}}
			>
				<div class="space-y-1.5">
					<label class={label} for="game-name">Name</label>
					<input id="game-name" bind:value={draft.name} class={field} placeholder="SF6" required />
					<p class="text-xs text-subtle">Short label shown in ranking columns.</p>
				</div>

				<div class="space-y-1.5">
					<label class={label} for="game-order">Order</label>
					<input id="game-order" type="number" bind:value={draft.order} class={field} />
					<p class="text-xs text-subtle">Sorts lists and the HTML recap.</p>
				</div>

				<div class="space-y-1.5 sm:col-span-2">
					<label class={label} for="game-longname">Long name</label>
					<input
						id="game-longname"
						bind:value={draft.longName}
						class={field}
						placeholder="Street Fighter 6"
					/>
					<p class="text-xs text-subtle">
						Used as the podium heading, and as the start.gg search term below.
					</p>
				</div>

				<div class="space-y-1.5">
					<label class={label} for="game-wptag">WordPress tag</label>
					<input id="game-wptag" bind:value={draft.wordPressTag} class={field} />
				</div>

				<div class="space-y-1.5">
					<label class={label} for="game-wptagos">WordPress tag (OS)</label>
					<input id="game-wptagos" bind:value={draft.wordPressTagOs} class={field} />
				</div>

				<div class="space-y-1.5 sm:col-span-2">
					<label class={label} for="game-img">Image URL</label>
					<input
						id="game-img"
						bind:value={draft.imgUrl}
						class={field}
						placeholder="https://ladose.net/…"
					/>
				</div>

				<div class="space-y-1.5 sm:col-span-2">
					<label class={label} for="game-smashid">start.gg videogame id</label>
					<div class="flex gap-2">
						<input
							id="game-smashid"
							type="number"
							bind:value={draft.smashId}
							class={field}
							placeholder="none"
						/>
						<button
							type="button"
							class="{ghost} shrink-0"
							onclick={findOnSmash}
							disabled={searching || searchTerm === ''}
						>
							{searching ? 'Searching…' : 'Find on start.gg'}
						</button>
					</div>
					<p class="text-xs text-subtle">
						Imports match brackets on this id — without it, results land under "GAME NOT FOUND".
					</p>

					{#if smashMatches?.length}
						<ul class="mt-2 max-h-40 space-y-1 overflow-y-auto rounded-lg bg-inset p-1">
							{#each smashMatches as match (match.id)}
								<li>
									<button
										type="button"
										onclick={() => (draft.smashId = match.id ?? null)}
										class="flex w-full items-center gap-3 rounded px-2 py-1.5 text-left text-sm transition hover:bg-ink/5 {draft.smashId ===
										match.id
											? 'text-accent'
											: 'text-ink'}"
									>
										<span class="w-14 shrink-0 text-right text-xs text-subtle">
											{match.id}
										</span>
										<span class="truncate">{match.name}</span>
									</button>
								</li>
							{/each}
						</ul>
					{/if}
				</div>

				<div
					class="flex flex-wrap items-center gap-3 border-t border-line pt-4 sm:col-span-2"
				>
					<button type="submit" class={primary} disabled={!canSave}>
						{saving ? 'Saving…' : isNew ? 'Create game' : 'Save'}
					</button>
					<button
						type="button"
						class={ghost}
						onclick={() => {
							const current = games.find((game) => game.id === draft.id);
							if (current) load(current);
							else reset();
						}}
						disabled={!dirty}
					>
						Revert
					</button>
					<button
						type="button"
						class="{danger} ml-auto"
						onclick={remove}
						disabled={isNew || deleting}
					>
						{deleting ? 'Deleting…' : 'Delete'}
					</button>
				</div>
			</form>
		</section>
	</div>
	{/if}
</main>
