<script lang="ts">
	import ActivityHistory from '$lib/Tools/ActivityHistory/Tool.svelte';
	import Wrapped from '$lib/Tools/Wrapped.svelte';
	import { browser } from '$app/environment';
	import EpisodeDiscussionCollector from '$lib/Tools/EpisodeDiscussionCollector.svelte';
	import CharacterBirthdays from '$lib/Tools/Birthdays.svelte';
	import { page } from '$app/stores';
	import SequelSpy from '$lib/Tools/SequelSpy.svelte';
	import { closest } from '$lib/Error/path';
	import HeadTitle from '$lib/HeadTitle.svelte';

	export let data;

	let tool =
		browser && $page.url.searchParams.size !== 0
			? $page.url.searchParams.get('tool') || 'default'
			: 'default';
	const tools: { [key: string]: string } = {
		default: 'Tools',
		birthdays: "Today's Character Birthdays",
		activity_history: 'Activity History Analyser',
		wrapped: 'AniList Wrapped',
		discussions: 'Episode Discussion Collector',
		sequel_spy: 'Sequel Spy (Missing Prequel Finder)'
	};

	$: {
		if (browser) {
			$page.url.searchParams.set('tool', tool);
			history.replaceState(null, '', `?${$page.url.searchParams.toString()}`);
		}
	}
	$: suggestion = closest(browser ? tool : '...', Object.keys(tools));
</script>

<blockquote>
	<select bind:value={tool}>
		<option value="default" selected disabled hidden>Tool</option>
		<option value="birthdays">Today's Character Birthdays</option>
		<option value="activity_history">Activity History Analyser</option>
		<option value="wrapped">AniList Wrapped</option>
		<option value="discussions">Episode Discussion Collector</option>
		<option value="sequel_spy">Sequel Spy (Missing Prequel Finder)</option>
	</select>
</blockquote>

{#if !Object.keys(tools).includes(tool)}
	<HeadTitle route="Tools" path="/tools" />

	<p>Tool not found.</p>

	<blockquote>
		Did you mean "<a
			href={`?tool=${suggestion}`}
			style={suggestion === '...' ? 'pointer-events: none; color: inherit;' : ''}
		>
			{suggestion === '...' ? '...' : tools[suggestion]}</a
		>"?
	</blockquote>
{:else}
	<HeadTitle route={tools[tool]} path={`/tools?tool=${tool}`} />

	{#if tool === 'default'}
		Select a tool to continue.
	{:else if tool === 'activity_history'}
		<ActivityHistory user={data.user} />
	{:else if tool === 'wrapped'}
		<Wrapped user={data.user} />
	{:else if tool === 'discussions'}
		<EpisodeDiscussionCollector />
	{:else if tool === 'birthdays'}
		<CharacterBirthdays />
	{:else if tool === 'sequel_spy'}
		<SequelSpy user={data.user} />
	{/if}
{/if}
