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

let groupsResponse: Promise<Response>;

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

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

{#await groupsResponse}
  <Message message="Loading groups ..." />
{:then groups}
  {#if groups}
    {#await groups.json()}
      <Message message="Parsing groups ..." />
    {: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>Error parsing groups.</Message>
    {/await}
  {:else}
    <Message message="Parsing groups ..." />
  {/if}
{:catch}
  <Message message="" loader="ripple" slot withReload>Error loading groups.</Message>
{/await}
