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

	import settings from '../../../stores/settings';
	import type { Media } from '$lib/AniList/media';
	import { airingTime, cleanCache, totalEpisodes, updateMedia } from '$lib/Media/anime';
	import type { AniListAuthorisation, UserIdentity } from '$lib/AniList/identity';
	import ListTitle from '../ListTitle.svelte';
	import MediaTitle from '../MediaTitle.svelte';

	export let media: Media[];
	export let title: string;
	export let animeLists: Promise<Media[]>;
	export let user: AniListAuthorisation;
	export let identity: UserIdentity;
	export let endTime: number;
	export let lastUpdatedMedia: number;
	export let completed = false;
	export let previousAnimeList: Media[];
	export let disableIncrement = false;
	export let pendingUpdate: number | null;
</script>

<ListTitle time={endTime / 1000} count={media.length} custom={title} />

{#if media.length === 0}
	<ul>
		<li>
			No anime to display. <a href={'#'} on:click={() => (animeLists = cleanCache(user, identity))}>
				Force refresh
			</a>
		</li>
	</ul>
{/if}

<ul>
	{#each media as anime}
		{@const progress = (anime.mediaListEntry || { progress: 0 }).progress}
		<li>
			<a
				href={$settings.linkToLiveChart
					? `https://www.livechart.me/search?q=${
							anime.title.native || anime.title.english || anime.title.romaji
					  }`
					: `https://anilist.co/anime/${anime.id}`}
				target="_blank"
			>
				<span
					style={lastUpdatedMedia === anime.id && anime.episodes !== progress
						? 'color: lightcoral'
						: ''}
				>
					<MediaTitle media={anime} />
				</span>
			</a>
			{#if $settings.displaySocialButton}
				[<a href={`https://anilist.co/anime/${anime.id}/social`} target="_blank">S</a>]
			{/if}
			<span style="opacity: 50%;">|</span>
			{#if title !== 'Upcoming Episodes'}
				<!-- {anime.mediaListEntry?.progress || 0}{@html totalEpisodes(anime)} -->
				{pendingUpdate === anime.id ? progress + 1 : progress}{@html totalEpisodes(anime)}
				<a
					href={'#'}
					style={disableIncrement ? 'pointer-events: none; opacity: 50%;' : ''}
					on:click={() => {
						if (!disableIncrement) {
							lastUpdatedMedia = anime.id;
							pendingUpdate = anime.id;

							updateMedia(anime.id, anime.mediaListEntry?.progress, () => {
								const mediaListEntry = media.find((m) => m.id === anime.id)?.mediaListEntry;

								if (mediaListEntry) {
									mediaListEntry.progress = progress + 1;
								}

								previousAnimeList = media;
								animeLists = cleanCache(user, identity);
								pendingUpdate = null;
							});
						}
					}}>+</a
				>
				{#if !completed}
					[{anime.nextAiringEpisode?.episode === -1
						? '?'
						: (anime.nextAiringEpisode?.episode || 1) - 1}]
					{@html airingTime(anime)}
				{/if}
			{:else}
				{@html airingTime(anime, true)}
			{/if}
		</li>
	{/each}
</ul>
