<script lang="ts">
  import { activityLikes } from '$lib/Data/AniList/activity';
  import { threadLikes } from '$lib/Data/AniList/forum';
  import RateLimited from '$lib/Error/RateLimited.svelte';
  import Skeleton from '$lib/Loading/Skeleton.svelte';
  import tooltip from '$lib/Tooltip/tooltip';
  import settings from '$stores/settings';
  import InputTemplate from './InputTemplate.svelte';

  let submission = '';

  $: normalisedSubmission = submission.replace(/.*\/(activity|thread)\/(\d+).*/, '$2');
  $: submissionType = submission.replace(/.*\/(activity|thread)\/(\d+).*/, '$1');
  $: likesPromise =
    submissionType === 'activity'
      ? activityLikes(Number(normalisedSubmission))
      : submissionType === 'thread'
        ? threadLikes(Number(normalisedSubmission))
        : Promise.resolve(null);
</script>

<InputTemplate
  field="Activity or Thread URL"
  bind:submission
  event="Get All Likes"
  submitText="Get All Likes"
>
  {#if submission.length > 5 && submission.match(/https:\/\/anilist.co\/(activity|forum\/thread)\/\d+/)}
    {#await likesPromise}
      <Skeleton card={false} count={5} height="0.9rem" list />
    {:then likes}
      {#if likes && likes.length > 0}
        <ul>
          {#each likes as like}
            <li>
              <a
                href={`https://anilist.co/user/${like.name}`}
                target="_blank"
                title={`<img src="${
                  $settings.displayDataSaver ? like.avatar?.medium : like.avatar?.large
                }" style="width: 150px; object-fit: cover; border-radius: 8px;" />`}
                use:tooltip
              >
                {like.name}
              </a>
            </li>
          {/each}
        </ul>
      {:else}
        No likes were found for that {submissionType}.
      {/if}
    {:catch}
      <RateLimited type="Likes" list={false} />
    {/await}
  {:else}
    Please enter a valid Activity or Thread URL.
  {/if}
</InputTemplate>
