<script lang="ts">
	import crunchyroll from '$lib/crunchyroll.json';

	interface CrunchyrollMedia<T = number | 'soon' | 'continuing'> {
		year: number;
		month: number;
		day: T;
		title: string;
	}

	type KnownMedia = { [key: string]: CrunchyrollMedia<number>[] };

	const days: KnownMedia = crunchyroll
		.filter((media) => media.day !== 'soon' && media.day !== 'continuing')
		.reduce((acc: KnownMedia, media) => {
			const date = new Date(media.year, media.month - 1, media.day as number).toLocaleDateString();

			if (!acc[date]) acc[date] = [];

			acc[date].push(media as CrunchyrollMedia<number>);

			return acc;
		}, {});
	const continuing: CrunchyrollMedia<number | string>[] = crunchyroll.filter(
		(media) => media.day === 'continuing'
	);
	const soon: CrunchyrollMedia<number | string>[] = crunchyroll.filter(
		(media) => media.day === 'soon'
	);

	$: columnCount = Math.ceil(Object.keys(days).length / 2);

	const ordinalSuffix = (i: number) => {
		const j = i % 10;
		const k = i % 100;

		if (j === 1 && k !== 11) return i + 'st';
		if (j === 2 && k !== 12) return i + 'nd';
		if (j === 3 && k !== 13) return i + 'rd';

		return i + 'th';
	};
</script>

<p />

<p>Crunchyroll Releases Calender</p>

<div id="list-container" style={`column-count: ${columnCount};`}>
	{#each Object.values(days) as day}
		{@const date = new Date(day[0].year, day[0].month - 1, day[0].day)}

		<div class="card day">
			{date.toLocaleString('default', { month: 'long' })}
			{ordinalSuffix(day[0].day)}, {day[0].year}
			<ol>
				{#each day as media}
					<li>{media.title}</li>
				{/each}
			</ol>
		</div>

		<p />
	{/each}

	<div class="card day">
		Coming soon
		<ol>
			{#each soon as media}
				<li>{media.title}</li>
			{/each}
		</ol>
	</div>

	<div class="card day">
		Continuing from previous season
		<ol>
			{#each continuing as media}
				<li>{media.title}</li>
			{/each}
		</ol>
	</div>
</div>

<style>
	#list-container {
		column-width: 250px;
		/* break-inside: avoid-column; */
	}

	.day {
		overflow-y: auto;
		break-inside: avoid-column;
	}
</style>
