<script lang="ts">
  import type { AWCBadgesGroup } from '$lib/Data/awc';
  import { cdn, thumbnail } from '$lib/Utility/image';
  import type { Preferences } from '../../../graphql/$types';
  import FallbackBadge from './FallbackBadge.svelte';
  import './badges.css';

  export let awcPromise: Promise<Response>;
  export let categoryFilter: string | null;
  export let isOwner: boolean;
  export let preferences: Preferences;

  const awcBadgesGrouped = (awcResponse: string): AWCBadgesGroup[] => {
    return Array.from(
      new DOMParser().parseFromString(awcResponse, 'text/html').querySelectorAll('.container')
    )
      .map((c) => {
        const container = c as HTMLDivElement;
        const header = container.querySelector('.container-header') as HTMLDivElement;

        if (!header) return;

        if (!['Anime', 'Manga', 'Special'].includes(header.innerText)) return;

        if (header.innerText === 'Special') {
          return {
            group: header.innerText,
            badges: Array.from(container.querySelectorAll('.badge-display img')).map((b) => {
              const badge = b as HTMLImageElement;

              return {
                link: '#',
                description: badge.alt,
                image: badge.src.includes('placeholder')
                  ? cdn('https://awc.moe/static/images/badge-placeholder.png')
                  : badge.src
              };
            })
          };
        }

        return {
          group: header.innerText,
          badges: Array.from(container.querySelectorAll('.badge-display a')).map((b) => {
            const badge = b as HTMLAnchorElement;
            const image = badge.querySelector('img') as HTMLImageElement;

            return {
              link: badge.href,
              description: image.alt,
              image: image.src.includes('placeholder')
                ? cdn('https://awc.moe/static/images/badge-placeholder.png')
                : image.src
            };
          })
        };
      })
      .filter((b) => b !== undefined) as AWCBadgesGroup[];
  };
</script>

{#await awcPromise then badges}
  {#if badges}
    {#await badges.clone().text() then text}
      {@const parsedBadges = awcBadgesGrouped(text)}

      {#if parsedBadges.length > 0}
        {#each parsedBadges as group}
          <details open={categoryFilter || isOwner ? false : true}>
            <summary>
              Anime Watching Club <span class="opaque">|</span>
              {group.group}
            </summary>

            <p />

            <div class="badges">
              {#each group.badges as badge, index}
                <div id={`badge-${index}`}>
                  <FallbackBadge
                    {badge}
                    source={cdn(thumbnail(badge.image))}
                    alternative={badge.description}
                    fallback={thumbnail(badge.image)}
                    hideOnError={preferences.hide_missing_badges}
                    awc
                    {index}
                    {preferences}
                  />
                </div>
              {/each}
            </div>
          </details>

          <p />
        {/each}
      {/if}
    {/await}
  {/if}
{/await}
