<script lang="ts">
	/* eslint svelte/no-at-html-tags: "off" */

	import type { AniListAuthorisation, UserIdentity } from '$lib/AniList/identity';
	import type { Media } from '$lib/AniList/media';
	import Error from '$lib/Error/RateLimited.svelte';
	import settings from '$stores/settings';
	import CleanAnimeList from './CleanAnimeList.svelte';
	import ListTitle from '../ListTitle.svelte';
	import type { SubsPlease } from '$lib/Media/Anime/Airing/Subtitled/subsPlease';
	import root from '$lib/Utility/root';
	import Skeleton from '$lib/Skeleton.svelte';

	export let endTime: number;
	export let cleanMedia: (
		media: Media[],
		displayUnresolved: boolean,
		subsPlease: SubsPlease | null,
		plannedOnly?: boolean
	) => Media[];
	export let animeLists: Promise<Media[]>;
	export let user: AniListAuthorisation;
	export let identity: UserIdentity;
	export let title: string;
	export let completed = false;
	export let plannedOnly = false;

	let lastUpdatedMedia = -1;
	let previousAnimeList: Media[];
	let pendingUpdate: number | null = null;
</script>

{#await fetch(root(`/api/subsplease?tz=${Intl.DateTimeFormat().resolvedOptions().timeZone}`)).then( (r) => r.json() )}
	<ListTitle custom={title} />

	<!-- <ul><li>Loading subtitle release data ... 33%</li></ul> -->

	<Skeleton
		card={false}
		count={5}
		pad
		height={$settings.displayCoverMode ? '5rem' : '0.9rem'}
		list={!$settings.displayCoverMode}
		grid={$settings.displayCoverMode}
	/>
{:then subsPlease}
	{#await animeLists}
		{#if previousAnimeList}
			<CleanAnimeList
				media={previousAnimeList}
				{title}
				bind:animeLists
				{user}
				{identity}
				{endTime}
				bind:lastUpdatedMedia
				{completed}
				bind:previousAnimeList
				bind:pendingUpdate
			/>
		{:else}
			<ListTitle custom={title} />

			<!-- <ul><li>Loading anime lists ... 66%</li></ul> -->

			<Skeleton
				card={false}
				count={5}
				pad
				height={$settings.displayCoverMode ? '5rem' : '0.9rem'}
				list={!$settings.displayCoverMode}
				grid={$settings.displayCoverMode}
			/>
		{/if}
	{:then media}
		<CleanAnimeList
			media={cleanMedia(media, $settings.displayUnresolved, subsPlease, plannedOnly)}
			{title}
			bind:animeLists
			{user}
			{identity}
			{endTime}
			bind:lastUpdatedMedia
			{completed}
			{subsPlease}
			bind:previousAnimeList
			bind:pendingUpdate
		/>
	{:catch}
		<ListTitle time={0} count={-1337} custom={title} />

		<Error />
	{/await}
{:catch}
	<Error type="Subtitle release data" />
{/await}
