<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.svelte';
	import settings from '../../../stores/settings';
	import CleanAnimeList from '../Anime/CleanAnimeList.svelte';
	import ListTitle from '../ListTitle.svelte';

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

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

{#await animeLists}
	{#if previousAnimeList}
		<CleanAnimeList
			media={previousAnimeList}
			{title}
			bind:animeLists
			{user}
			{identity}
			{endTime}
			bind:lastUpdatedMedia
			{completed}
			bind:previousAnimeList
			disableIncrement
			bind:pendingUpdate
		/>
	{:else}
		<ListTitle custom={title} />

		<ul><li>Loading ...</li></ul>
	{/if}
{:then media}
	{@const cleanedMedia = cleanMedia(media, $settings.displayUnresolved)}

	<CleanAnimeList
		media={cleanedMedia}
		{title}
		bind:animeLists
		{user}
		{identity}
		{endTime}
		bind:lastUpdatedMedia
		{completed}
		bind:previousAnimeList
		bind:pendingUpdate
	/>
{:catch}
	<ListTitle time={0} count={-1337} custom={title} />

	<Error />
{/await}
