<script lang="ts">
	import Error from '$lib/Error/RateLimited.svelte';
	import type { SubsPlease } from '$lib/Media/Anime/Airing/Subtitled/subsPlease';
	import { onMount } from 'svelte';
	import { parseOrDefault } from '$lib/Utility/parameters';
	import { browser } from '$app/environment';
	import type { Media } from '$lib/AniList/media';
	import { scheduleMediaListCollection } from '$lib/AniList/schedule';
	import { season } from '$lib/Media/Anime/season';
	import HeadTitle from '$lib/Home/HeadTitle.svelte';
	import Crunchyroll from '$lib/Tools/Schedule/Crunchyroll.svelte';
	import Loading from '$lib/Utility/Loading.svelte';
	import './container.css';
	import Days from './Days.svelte';
	import settings from '$stores/settings';

	let subsPleasePromise: Promise<SubsPlease>;
	let scheduledMediaPromise: Promise<Partial<Media[]>>;
	const urlParameters = browser ? new URLSearchParams(window.location.search) : null;
	let timeZone = parseOrDefault(
		urlParameters,
		'tz',
		Intl.DateTimeFormat().resolvedOptions().timeZone
	);
	let crunchyrollExpanded = false;
	let forceListMode = parseOrDefault(urlParameters, 'list', false);

	onMount(async () => {
		subsPleasePromise = fetch(`/api/subsplease?tz=${timeZone}`).then((r) => r.json());
		scheduledMediaPromise = scheduleMediaListCollection(new Date().getFullYear(), season(), true);
	});
</script>

<HeadTitle route="Schedule" path="/schedule" />

<blockquote>
	<select
		bind:value={timeZone}
		on:change={() =>
			(subsPleasePromise = fetch(`/api/subsplease?tz=${timeZone}`).then((r) => r.json()))}
	>
		{#each Intl.supportedValuesOf('timeZone') as zone}
			<option value={zone}>
				{zone.split('/').reverse().join(', ').replace(/_/g, ' ')}
			</option>
		{/each}
	</select>
</blockquote>

<details bind:open={crunchyrollExpanded}>
	<summary
		>Crunchyroll Release Calender (Click to {crunchyrollExpanded ? 'collapse' : 'expand'})</summary
	>

	<p />

	<Crunchyroll />
</details>

<p />

{#await subsPleasePromise}
	<Loading type="subtitle release data" percent={49.5} />
{:then subsPlease}
	{#if subsPlease}
		{#await scheduledMediaPromise}
			<Loading type="anime schedule" percent={82.5} />
		{:then scheduledMedia}
			{#if scheduledMedia}
				{@const columnCount = Math.ceil(Object.keys(subsPlease.schedule).length / 2)}

				<div
					class="list-container"
					id="schedule"
					style={`column-count: ${
						columnCount / ($settings.displayScheduleListMode || forceListMode ? 1 : 2)
					}`}
				>
					<Days {subsPlease} {scheduledMedia} {forceListMode} />
				</div>
			{:else}
				<Loading type="anime schedule" percent={66} />
			{/if}
		{:catch}
			<Error type="Media" loginSessionError={false} card />
		{/await}
	{:else}
		<Loading type="subtitle release data" percent={33} />
	{/if}
{:catch}
	<Error type="Schedule" loginSessionError={false} card />
{/await}
