<script lang="ts">
	import { ACDBBirthdays, type ACDBBirthday } from '$lib/ACDB';
	import { aniSearchBirthdays, type aniSearchBirthday } from '$lib/Birthday/aniSearch';
	import Error from '$lib/Error.svelte';
	import { onMount } from 'svelte';

	interface Birthday {
		name: string;
		image: string;
		origin?: string;
	}

	let date = new Date();
	let month = date.getMonth() + 1;
	let day = date.getDate();
	let anisearchBirthdays: Promise<aniSearchBirthday[]>;

	onMount(async () => {
		anisearchBirthdays = aniSearchBirthdays(month, day);
	});

	const combineBirthdaySources = (
		acdbArray: ACDBBirthday[],
		aniSearchArray: aniSearchBirthday[]
	): Birthday[] =>
		Array.from(
			new Map(
				[
					...aniSearchArray.map((entry) => ({
						name: entry.name,
						image: entry.image
					})),
					...acdbArray.map((entry) => ({
						name: entry.name,
						image: entry.character_image,
						origin: entry.origin
					}))
				].map((entry) => [entry.name, entry])
			).values()
		);
</script>

{#await ACDBBirthdays(month, day)}
	<p>Loading set one ...</p>
{:then acdbBirthdays}
	{#await anisearchBirthdays}
		<p>Loading set two ...</p>
	{:then anisearch}
		{@const birthdays = combineBirthdaySources(acdbBirthdays, anisearch)}

		<div id="characters">
			{#each birthdays as birthday}
				<div>
					<a
						href={`https://anilist.co/search/characters?search=${encodeURIComponent(
							birthday.name
						).replace(/%20/g, '+')}`}
						target="_blank"
					>
						{birthday.name}
						<img src={birthday.image} alt="Character (Large)" class="character-image" />
					</a>
				</div>
			{/each}
		</div>
	{:catch}
		<Error type="Character" />
	{/await}
{:catch}
	<Error type="Character" />
{/await}

<style>
	#characters {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(8%, 1fr));
		grid-gap: 0.25%;
		grid-row-gap: 1rem;
	}
</style>
