<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;

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

<input type="checkbox" bind:checked={includeCurrent} /> Include current (watching, rewatching,
paused)

<p />

<ol class="media-list">
	{#each filterRelations(mediaListUnchecked.filter((media) => media.mediaListEntry?.status === 'COMPLETED')) 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}
						{#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>

								<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>
