<script lang="ts">
import { onMount } from "svelte";
import type { Group as GroupType } from "$lib/Database/SB/groups";
import Group from "$lib/Events/Group.svelte";
import Spacer from "$lib/Layout/Spacer.svelte";
import Message from "$lib/Loading/Message.svelte";
import root from "$lib/Utility/root";
import locale from "$stores/locale";

let groupsResponse: Promise<Response>;

onMount(async () => {
	groupsResponse = fetch(root("/api/events/groups"));
});

const asGroup = (group: unknown) => group as GroupType;
</script>

{#await groupsResponse}
  <Message message={$locale().events?.loadingGroups} />
{:then groups}
  {#if groups}
    {#await groups.json()}
      <Message message={$locale().events?.parsingGroups} />
    {:then json}
      {#each json as rawGroup, i}
        {@const group = asGroup(rawGroup)}

        <a href={root(`/events/group/${group.anilist_username}`)}>
          <Group {group} />
        </a>

        {#if i < json.length - 1}
          <Spacer />
        {/if}
      {/each}
    {:catch}
      <Message message="" loader="ripple" slot withReload>{$locale().events?.errorParsingGroups}</Message>
    {/await}
  {:else}
    <Message message={$locale().events?.parsingGroups} />
  {/if}
{:catch}
  <Message message="" loader="ripple" slot withReload>{$locale().events?.errorLoadingGroups}</Message>
{/await}
