<script lang="ts">
	import Error from '$lib/Error.svelte';
	import type { SubsPlease } from '$lib/subsPlease';
	import { onMount } from 'svelte';
	import settings from '../../stores/settings';

	let subsPleasePromise: Promise<SubsPlease>;
	const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;

	onMount(async () => {
		subsPleasePromise = fetch(`/api/subsplease?tz=${timeZone}`).then((r) => r.json());
	});

	const entryKey = (entry: unknown, key: string) => (entry as any)[key];
</script>

{#await subsPleasePromise}
	Loading ...
{:then subsPlease}
	{#if subsPlease}
		<blockquote>
			{timeZone.split('/').reverse().join(', ').replace(/_/g, ' ')}
		</blockquote>

		<div id="list-container">
			{#each Object.entries(subsPlease.schedule) as [day, scheduleEntry]}
				<details
					open
					class="list"
					class:today={day === new Date().toLocaleString('en-us', { weekday: 'long' })}
				>
					<summary>{day}</summary>

					<ul>
						{#each Object.values(scheduleEntry) as entry}
							<li class="entry">
								<a
									href={`https://anilist.co/search?search=${entryKey(entry, 'title')}`}
									target="_blank"
								>
									{entryKey(entry, 'title')}
								</a>
								{#if !$settings.displayCountdownRightAligned}
									<span style="opacity: 50%;">|</span>
								{/if}
								<span class:countdown={$settings.displayCountdownRightAligned}>
									{entryKey(entry, 'time')}
								</span>
							</li>
						{/each}
					</ul>
				</details>
			{/each}
		</div>
	{:else}
		Loading ...
	{/if}
{:catch}
	<Error type="Schedule" loginSessionError={false} />
{/await}

<style>
	#list-container {
		display: flex;
		flex-wrap: wrap;
	}

	.list {
		overflow-y: auto;
		min-width: min-content;
		flex: 1 1;
	}

	.entry::after {
		content: '';
		display: table;
		clear: both;
	}

	.countdown {
		white-space: nowrap;
		float: right;
	}

	.today {
		font-weight: bold;
	}
</style>
