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

	import { mediaListCollection, Type, flattenLists, type Media } from '$lib/AniList/media';
	import type { UserIdentity, AniListAuthorisation } from '$lib/AniList/identity';
	import { onMount } from 'svelte';
	import anime from '../../stores/anime';
	import animeLastPrune from '../../stores/mangaLastPrune';

	export let user: AniListAuthorisation;
	export let identity: UserIdentity;
	export let displayUnresolved: boolean;

	let animeLists: Promise<{ entries: { media: Media }[] }[]>;
	let startTime: number;
	let endTime: number;

	onMount(async () => {
		startTime = performance.now();
		animeLists = mediaListCollection(user, identity, Type.Anime, $anime, $animeLastPrune);
	});

	const cleanMedia = (media: { entries: { media: Media }[] }[], displayUnresolved: boolean) => {
		if (media === undefined) {
			return [];
		}

		const flattenedLists = flattenLists(media);
		const releasingMedia = flattenedLists.filter(
			(media: Media) => media.status == 'RELEASING' && media.nextAiringEpisode !== null
			/* &&
				(media['mediaListEntry'] || { progress: 0 })['progress'] >=
					($displayNotStarted === 'true' ? 0 : 1) */
		);
		const outdatedMedia = releasingMedia.filter((media: Media) => {
			return (
				(media.nextAiringEpisode || { episode: 0 }).episode - 1 <=
				(media.mediaListEntry || { progress: 0 }).progress
			);
		});
		let finalMedia = outdatedMedia.map((media: Media) => {
			if ((media.nextAiringEpisode || { episode: 0 }).episode - 1 <= 0) {
				media.nextAiringEpisode = { episode: -1 };
			}

			return media;
		});

		if (!displayUnresolved) {
			finalMedia = finalMedia.filter((media: Media) => media.nextAiringEpisode?.episode !== -1);
		}

		finalMedia.sort((a: Media, b: Media) => {
			return (
				(a.nextAiringEpisode?.timeUntilAiring || 9999) -
				(b.nextAiringEpisode?.timeUntilAiring || 9999)
			);
		});

		finalMedia = finalMedia.filter((item, index, array) => {
			return (
				array.findIndex((i) => {
					return i.id === item.id;
				}) === index
			);
		});

		if (!endTime) {
			endTime = performance.now() - startTime;
		}

		return finalMedia;
	};

	const airingTime = (anime: Media) => {
		const untilAiring = anime.nextAiringEpisode?.timeUntilAiring;
		let timeFrame;

		if (untilAiring !== undefined) {
			let hours = untilAiring / 3600;

			if (hours >= 24) {
				let weeks = Math.floor(Math.floor(hours / 24) / 7);

				if (weeks >= 1) {
					weeks = Math.round(weeks);

					timeFrame = `${weeks} week${weeks === 1 ? '' : 's'}`;
				} else {
					const days = Math.round(Math.floor(hours / 24));

					timeFrame = `${days} day${days === 1 ? '' : 's'}`;
				}
			} else {
				hours = Math.round(hours);

				timeFrame = `${hours} hour${hours === 1 ? '' : 's'}`;
			}

			return `${anime.nextAiringEpisode?.episode}${totalEpisodes(anime)} in ${timeFrame}`;
		}

		return '';
	};

	const totalEpisodes = (anime: Media) => {
		return anime.episodes === null ? '' : `<span style="opacity: 50%">/${anime.episodes}</span>`;
	};
</script>

{#await animeLists}
	<summary>Upcoming Episodes [...] <small style="opacity: 50%">...s</small></summary>

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

	<summary
		>Upcoming Episodes [{cleanedMedia.length}]
		<small style="opacity: 50%">{endTime / 1000}s</small></summary
	>

	<ul>
		{#each cleanedMedia as anime}
			<li>
				<a href={`https://anilist.co/anime/${anime.id}`} target="_blank">
					{anime.title.english || anime.title.romaji}
				</a>
				<span style="opacity: 50%;">|</span>
				{@html airingTime(anime)}
			</li>
		{/each}
	</ul>
{:catch}
	<summary>Upcoming Episodes [?] <small style="opacity: 50%">0s</small></summary>

	<ul>
		<li>
			<p>
				Media 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>
		</li>
	</ul>
{/await}
