<script lang="ts">
	import { filterRelations, type Media } from '$lib/Data/AniList/media';
	import MediaTitleDisplay from '$lib/List/MediaTitleDisplay.svelte';
	import { outboundLink } from '$lib/Media/links';
	import settings from '$stores/settings';

	export let mediaListUnchecked: Media[];

	let includeCurrent = false;
	let includeSideStories = false;

	const matchCheck = (media: Media | undefined, swap = false) =>
		(media &&
			media.mediaListEntry &&
			media.mediaListEntry?.status !== 'CURRENT' &&
			media.mediaListEntry?.status !== 'REPEATING' &&
			media.mediaListEntry?.status !== 'PAUSED') ||
		!media
			? swap
				? undefined
				: media
			: swap
			? media
			: undefined;
</script>

<input type="checkbox" bind:checked={includeCurrent} /> Include current (watching, rewatching,
paused)
<br />
<input type="checkbox" bind:checked={includeSideStories} /> Include side stories (e.g., OVAs,
specials, etc.)

<p />

<ol class="media-list">
	{#each filterRelations( mediaListUnchecked.filter((media) => media.mediaListEntry?.status === 'COMPLETED'), includeSideStories ) as { media, unwatchedRelations }}
		{#if unwatchedRelations.filter( (relation) => matchCheck(mediaListUnchecked.find((media) => media.id === relation.node.id)) ).length !== 0 || includeCurrent}
			<li>
				<a href={outboundLink(media, 'anime', $settings.displayOutboundLinksTo)} target="_blank">
					<MediaTitleDisplay title={media.title} />
				</a>

				<span class="opaque">
					({media.startDate.year})
				</span>

				<ol class="unwatched-relations-list">
					{#each unwatchedRelations as relation}
						{@const hit = matchCheck(
							mediaListUnchecked.find((media) => media.id === relation.node.id),
							true
						)}

						{#if matchCheck(mediaListUnchecked.find((media) => media.id === relation.node.id)) || includeCurrent}
							<li>
								<a
									href={outboundLink(relation.node, 'anime', $settings.displayOutboundLinksTo)}
									target="_blank"
								>
									<MediaTitleDisplay title={relation.node.title} />
								</a>

								{#if hit && hit.mediaListEntry && hit.mediaListEntry.progress > 0}
									<span class="opaque">|</span>

									{hit.mediaListEntry.progress}/{#if hit.episodes}{hit.episodes}{:else}?{/if}
								{/if}

								<span class="opaque">
									({relation.node.startDate.year})
								</span>
							</li>
						{/if}
					{/each}
				</ol>
			</li>
		{/if}
	{/each}
</ol>

<style>
	.media-list li {
		margin-bottom: 1rem;
	}

	.unwatched-relations-list li:not(:last-child) {
		margin-bottom: 0 !important;
	}
</style>
