<script lang="ts">
import Spacer from "$lib/Layout/Spacer.svelte";
import List from "./List.svelte";
import type { AniListAuthorisation } from "$lib/Data/AniList/identity";
import userIdentity from "$stores/identity";
import { type Media, mediaListCollection, Type } from "$lib/Data/AniList/media";
import LogInRestricted from "$lib/Error/LogInRestricted.svelte";
import anime from "$stores/anime";
import identity from "$stores/identity";
import { onMount } from "svelte";
import lastPruneTimes from "$stores/lastPruneTimes";
import Message from "$lib/Loading/Message.svelte";
import Skeleton from "$lib/Loading/Skeleton.svelte";
import Username from "$lib/Layout/Username.svelte";
import locale from "$stores/locale";

export let user: AniListAuthorisation;

let mediaList: Promise<Media[]>;

onMount(async () => {
	if (user === undefined || $identity.id === -2) return;

	mediaList = mediaListCollection(
		user,
		$userIdentity,
		Type.Anime,
		$anime,
		$lastPruneTimes.anime,
		{
			forcePrune: true,
			includeCompleted: true,
			all: true,
			includeRelations: true,
		},
	);
});
</script>

{#if user === undefined || $identity.id === -2}
  <LogInRestricted />
{:else}
  <div class="card">
    {#await mediaList}
      <Message message="Cross-checking media ..." />

      <Skeleton
        card={false}
        count={8}
        pad={false}
        height={'0.9rem'}
        width={'100%'}
        list
        grid={false}
      />
    {:then mediaListUnchecked}
      {#if mediaListUnchecked}
        <List {mediaListUnchecked} />
      {:else}
        <Message message="Cross-checking media ..." />

        <Skeleton
          card={false}
          count={8}
          pad={false}
          height={'0.9rem'}
          width={'100%'}
          list
          grid={false}
        />
      {/if}
    {:catch}
      <Message message="" loader="ripple" slot withReload fullscreen
        >{$locale().tools.wrapped?.errorFetchingMedia ?? 'Error fetching media.'}</Message
      >
    {/await}

    <Spacer />

    <blockquote style="margin: 0 0 0 1.5rem;">
      {$locale().tools.sequelCatcher?.credit?.split('@sevengirl')[0]}<Username
        username="sevengirl"
      />{$locale().tools.sequelCatcher?.credit?.split('@sevengirl')[1]?.split('@esthereae')[0]}<Username
        username="esthereae"
      />{$locale().tools.sequelCatcher?.credit?.split('@esthereae')[1]}
    </blockquote>
  </div>
{/if}
