<script lang="ts">
	import type { Media } from '$lib/AniList/media';
	import ListTitle from './ListTitle.svelte';

	export let media: Media[];
	export let cleanCache: () => Promise<void>;
	export let endTime: number;
	export let lastUpdatedMedia: number;
	export let updateMedia: (
		id: number,
		progress: number | undefined,
		media: Media[]
	) => Promise<void>;
	export let disableIncrement = false;
	export let pendingUpdate: number | null;
	export let due: boolean;
</script>

<ListTitle count={media.length} time={endTime / 1000}>
	<a href={'#'} title="Force a refresh" on:click={cleanCache}>Force</a>
</ListTitle>

{#if media.length === 0}
	<ul>
		<li>No manga to display. <a href={'#'} on:click={cleanCache}>Force refresh</a></li>
	</ul>
{/if}

<ul>
	{#each media as manga}
		{@const progress = (manga.mediaListEntry || { progress: 0 }).progress}

		<li>
			<a href={`https://anilist.co/manga/${manga.id}`} target="_blank">
				{#if lastUpdatedMedia === manga.id}
					<span style="color: lightcoral">
						{manga.title.english || manga.title.romaji || manga.title.native}
					</span>
				{:else}
					{manga.title.english || manga.title.romaji || manga.title.native}
				{/if}
			</a>
			<span style="opacity: 50%;">|</span>
			{pendingUpdate === manga.id ? progress + 1 : progress}{#if !due}
				<span style="opacity: 50%;">/{manga.chapters || '?'}</span>
			{/if}
			<a
				href={'#'}
				style={disableIncrement ? 'pointer-events: none; opacity: 50%;' : ''}
				on:click={() =>
					disableIncrement ? null : updateMedia(manga.id, manga.mediaListEntry?.progress, media)}
			>
				+
			</a>
			{#if due || manga.episodes !== manga.chapters}
				[{manga.episodes || '?'}]
			{/if}
		</li>
	{/each}
</ul>
