<script lang="ts">
	import { threads } from '$lib/AniList/forum';
	import { onMount } from 'svelte';
	import { clearAllParameters } from '../Utility/parameters';

	let searchInput = '';
	let searchInputFinal = '';

	onMount(clearAllParameters);
</script>

<p>
	<!-- svelte-ignore missing-declaration -->
	<input
		type="text"
		placeholder="Username"
		bind:value={searchInput}
		on:keypress={(e) => {
			if (e.key === 'Enter') {
				searchInputFinal = searchInput;

				// eslint-disable-next-line no-undef
				umami.track('Collect Episode Discussions');
			}
		}}
	/>
	<a
		href={`#`}
		on:click={() => (searchInputFinal = searchInput)}
		title="Or click your Enter key"
		data-umami-event="Collect Episode Discussions"
	>
		Search
	</a>
</p>

{#if searchInputFinal !== ''}
	{#await threads(searchInputFinal)}
		Loading forum threads ... 50%
	{:then threads}
		<ul>
			{#each threads
				.filter((thread) => thread.title.includes('[Spoilers]') && thread.title.includes('Episode'))
				.sort((a, b) => b.createdAt - a.createdAt) as thread}
				<li>
					<a href={`https://anilist.co/forum/thread/${thread.id}`} target="_blank">
						{thread.title.replace('[Spoilers]', '')}
					</a>
				</li>
			{/each}
		</ul>
	{:catch}
		<p>
			Threads could not be loaded. You might have been <a
				href="https://en.wikipedia.org/wiki/Rate_limiting"
				target="_blank">rate limited</a
			>.
		</p>
		<p>
			Try again in a few minutes. If the problem persists, please contact <a
				href="https://anilist.co/user/fuwn"
				target="_blank">@fuwn</a
			> on AniList.
		</p>
	{/await}
{:else}
	<p>Enter a username to search for to continue.</p>
{/if}
