<script lang="ts">
import { onMount } from "svelte";
import { browser } from "$app/environment";
import { page } from "$app/stores";
import type { AniListAuthorisation } from "$lib/Data/AniList/identity";
import { type MediaPrequel, prequels } from "$lib/Data/AniList/prequels";
import LogInRestricted from "$lib/Error/LogInRestricted.svelte";
import Spacer from "$lib/Layout/Spacer.svelte";
import Skeleton from "$lib/Loading/Skeleton.svelte";
import { season as getSeason } from "$lib/Media/Anime/season";
import identity from "$stores/identity";
import locale from "$stores/locale";
import { clearAllParameters, parseOrDefault } from "../../Utility/parameters";
import Prequels from "./Prequels.svelte";

export let user: AniListAuthorisation;

let currentPrequels: Promise<MediaPrequel[]> = Promise.resolve([]) as Promise<
	MediaPrequel[]
>;
const urlParameters = browser
	? new URLSearchParams(window.location.search)
	: null;
let year = parseOrDefault(urlParameters, "year", new Date().getFullYear());
let season = parseOrDefault(urlParameters, "season", getSeason());

$: {
	if (year.toString().length === 4 && $identity.id !== -2 && user)
		currentPrequels = prequels(user, year, season);
}
$: {
	if (browser) {
		$page.url.searchParams.set("year", year.toString());
		$page.url.searchParams.set("season", season.toString());
		clearAllParameters(["year", "season"]);
		history.replaceState(null, "", `?${$page.url.searchParams.toString()}`);
	}
}

onMount(() => clearAllParameters(["year", "season"]));
</script>

{#if user === undefined || $identity.id === -2}
  <LogInRestricted />
{:else}
  <div class="card">
    <p>
      <select bind:value={season}>
        <option value="WINTER">{$locale().tools.sequelSpy?.winter}</option>
        <option value="SPRING">{$locale().tools.sequelSpy?.spring}</option>
        <option value="SUMMER">{$locale().tools.sequelSpy?.summer}</option>
        <option value="FALL">{$locale().tools.sequelSpy?.fall}</option>
      </select>
      <input type="number" bind:value={year} />
    </p>

    {#await currentPrequels}
      <Skeleton card={false} count={5} height="0.9rem" list />
    {:then currentPrequels}
      <Prequels {currentPrequels} />
    {/await}

    <Spacer />

    {$locale().tools.sequelSpy?.countRatio}
  </div>
{/if}
