<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 PlaceholderList from './PlaceholderList.svelte';
	import { browser } from '$app/environment';
	import { onMount } from '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: any;
	export let completed = false;
	export let plannedOnly = false;
	export let upcoming = false;
	export let notYetReleased = false;

	let lastUpdatedMedia = -1;
	let previousAnimeList: Media[];
	let pendingUpdate: number | null = null;
	let lastListSize = 8;

	onMount(() => {
		if (browser) {
			const lastStoredList = localStorage.getItem(
				`last${
					notYetReleased ? 'NotYetReleased' : upcoming ? 'Upcoming' : completed ? 'Completed' : ''
				}AnimeListLength`
			);
			if (lastStoredList) lastListSize = parseInt(lastStoredList);
		}
	});
</script>

{#await fetch(root(`/api/subsplease?tz=${Intl.DateTimeFormat().resolvedOptions().timeZone}`)).then( (r) => r.json() )}
	<PlaceholderList count={lastListSize} {title} />
{:then subsPlease}
	{#await animeLists}
		{#if previousAnimeList}
			<CleanAnimeList
				media={previousAnimeList}
				{title}
				bind:animeLists
				{user}
				{identity}
				{endTime}
				bind:lastUpdatedMedia
				{completed}
				{notYetReleased}
				{upcoming}
				bind:previousAnimeList
				bind:pendingUpdate
			/>
		{:else}
			<PlaceholderList count={lastListSize} {title} />
		{/if}
	{:then media}
		<CleanAnimeList
			media={cleanMedia(media, $settings.displayUnresolved, subsPlease, plannedOnly)}
			{title}
			bind:animeLists
			{user}
			{identity}
			{endTime}
			bind:lastUpdatedMedia
			{completed}
			{notYetReleased}
			{upcoming}
			{subsPlease}
			bind:previousAnimeList
			bind:pendingUpdate
		/>
	{:catch}
		<ListTitle time={0} count={-1337} {title} />

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