<script lang="ts">
	import Error from '$lib/Error/RateLimited.svelte';
	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/Schedule/Crunchyroll.svelte';
	import '$lib/Schedule/container.css';
	import Days from '$lib/Schedule/Days.svelte';
	import settings from '$stores/settings';
	import Skeleton from '$lib/Loading/Skeleton.svelte';
	import Message from '$lib/Loading/Message.svelte';
	import subsPlease from '$stores/subsPlease';

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

	onMount(async () => {
		scheduledMediaPromise = scheduleMediaListCollection(new Date().getFullYear(), season(), true);
	});
</script>

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

<!-- <blockquote>
	<select
		bind:value={timeZone}
		on:change={() =>
			(subsPleasePromise = fetch(root(`/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 />

{#if !$subsPlease}
	<Message message="Loading subtitle schedule ..." />

	<Skeleton grid={true} count={7} height="15em" width="49.5%" />
{:else}
	{#await scheduledMediaPromise}
		<Message message="Loading schedule ..." />

		<Skeleton grid={true} count={7} height="15em" width="49.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={$subsPlease} {scheduledMedia} {forceListMode} />
			</div>
		{:else}
			<Message message="Loading schedule ..." />

			<Skeleton grid={true} count={7} height="15em" width="49.5%" />
		{/if}
	{:catch}
		<Error type="Media" loginSessionError={false} card list={false} />
	{/await}
{/if}
