<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/Data/AniList/media';
  import { scheduleMediaListCollection } from '$lib/Data/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 Skeleton from '$lib/Loading/Skeleton.svelte';
  import Message from '$lib/Loading/Message.svelte';
  import subsPlease from '$stores/subsPlease';

  export let data;

  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></p>

	<Crunchyroll />
</details>

<p></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}
      <div class="schedule-container" id="schedule">
        <Days subsPlease={$subsPlease} {scheduledMedia} {forceListMode} user={data.user} />
      </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}

<style>
  .schedule-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(35%, 1fr));
    gap: 0.5em;
  }

  @media (max-width: 800px) {
    .schedule-container {
      grid-template-columns: 1fr !important;
    }
  }
</style>
