<script lang="ts">
import Spacer from "$lib/Layout/Spacer.svelte";
import { threads } from "$lib/Data/AniList/forum";
import { onMount } from "svelte";
import { clearAllParameters } from "../Utility/parameters";
import Skeleton from "$lib/Loading/Skeleton.svelte";
import InputTemplate from "./InputTemplate.svelte";
import tooltip from "$lib/Tooltip/tooltip";
import locale from "$stores/locale";

let submission = "";

onMount(clearAllParameters);
</script>

<InputTemplate
  field="Username"
  bind:submission
  event="Collect Episode Discussions"
  submitText="Search"
>
  {#if submission !== ''}
    {#await threads(submission)}
      <Skeleton card={false} count={5} height="0.9rem" list />
    {:then threads}
      <ol reversed>
        {#each threads
          .filter( (thread) => thread.categories.some( (category) => category.name.includes('Release Discussion') ) )
          .sort((a, b) => b.createdAt - a.createdAt) as thread}
          <li>
            <span class="opaque" style="white-space: pre;">
              {new Date(thread.createdAt * 1000).toLocaleDateString('en-US', {
                month: 'short',
                day: 'numeric',
                year: 'numeric'
              })}
            </span>
            <a
              href={`https://anilist.co/forum/thread/${thread.id}`}
              target="_blank"
              title={`<img src="${thread.mediaCategories[0].coverImage.extraLarge}" style="width: 250px; object-fit: cover; border-radius: 8px;" />`}
              use:tooltip
            >
              {thread.title.replace('[Spoilers]', '')}
            </a>
          </li>
        {/each}
      </ol>
    {:catch}
      <p>{$locale().tools.episodeDiscussion?.rateLimit}</p>
      <p>
        {$locale().tools.episodeDiscussion?.contactSupport?.split('@fuwn')[0]}<a
          href="https://anilist.co/user/fuwn"
          target="_blank">@fuwn</a
        >{$locale().tools.episodeDiscussion?.contactSupport?.split('@fuwn')[1]}
      </p>
    {/await}
  {:else}
    <Spacer />

    {$locale().tools.episodeDiscussion?.enterUsername}
  {/if}
</InputTemplate>
