<script lang="ts">
	import { threads } from '$lib/AniList/forum';
	import { onMount } from 'svelte';
	import { clearAllParameters } from '../Utility/parameters';
	import HoverCover from '$lib/Media/Cover/HoverCover.svelte';
	import {
		onMouseEnter,
		onMouseLeave,
		onMouseMove,
		type HoverCoverResponse
	} from '$lib/Media/Cover/hoverCover';
	import Skeleton from '$lib/Loading/Skeleton.svelte';
	import InputTemplate from './InputTemplate.svelte';

	let hoverCoverState: HoverCoverResponse = {};
	let submission = '';

	onMount(clearAllParameters);
</script>

<InputTemplate
	field="Username"
	bind:submission
	event="Collect Episode Discussions"
	submitText="Search"
>
	{#if submission !== ''}
		{#await threads(submission)}
			<Skeleton card={false} count={5} height="0.9rem" list />
		{: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>
						<span class="opaque" style="white-space: pre;">
							{new Date(thread.createdAt * 1000).toLocaleDateString('en-US', {
								month: 'short',
								day: 'numeric',
								year: 'numeric'
							})}
						</span>
						<a
							href={`https://anilist.co/forum/thread/${thread.id}`}
							target="_blank"
							on:mouseenter={() => {
								if (thread.mediaCategories.length === 0) return;

								const response = onMouseEnter(thread.mediaCategories[0]);

								hoverCoverState.hovering = response.hovering;
								hoverCoverState.item = response.item;
								hoverCoverState.media = response.media;
							}}
							on:mouseleave={() => {
								const response = onMouseLeave();

								hoverCoverState.hovering = response.hovering;
								hoverCoverState.item = response.item;
								hoverCoverState.media = response.media;
							}}
							on:mousemove={(e) => {
								const response = onMouseMove(e, 300);

								hoverCoverState.style = response.style;
							}}
						>
							{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.
	{/if}
</InputTemplate>

<HoverCover options={hoverCoverState} width={300} />
