<script lang="ts">
  import type { Media } from '$lib/Data/AniList/media';
  import ParallaxImage from '$lib/Image/ParallaxImage.svelte';
  import { outboundLink } from '$lib/Media/links';
  import LinkedTooltip from '$lib/Tooltip/LinkedTooltip.svelte';
  import settings from '$stores/settings';
  import { mediaTitle } from './mediaTitle';
  import './covers.css';

  export let media: Media[];
  export let dummy = false;
  export let type: 'anime' | 'manga';
  export let upcoming = false;
  export let notYetReleased = false;
  export let reverseSort = false;
  export let limit: number | undefined = undefined;

  let uniqueID = new Date().getTime();

  $: sortedMedia = reverseSort ? media.reverse() : media;
  $: processedMedia = limit !== undefined ? sortedMedia.slice(0, limit) : sortedMedia;
</script>

<div
  class="covers"
  style={`grid-template-columns: repeat(auto-fill, minmax(${$settings.displayCoverWidth}px, 1fr))`}
>
  {#each processedMedia as title}
    {@const progress = (title.mediaListEntry || { progress: 0 }).progress}

    {#if type === 'anime' ? upcoming || notYetReleased || progress !== (title.nextAiringEpisode?.episode || 9999) - 1 : progress != title.episodes}
      <div class="cover-card" id={`${type}-${title.id}-${uniqueID}`}>
        <LinkedTooltip
          pin={`${type}-${title.id}-${uniqueID}`}
          content={title ? mediaTitle(title) : ''}
          relative={dummy}
        >
          <div class="cover-card-image">
            <a
              href={$settings.displayCopyMediaTitleNotLink
                ? '#'
                : outboundLink(title, type, $settings.displayOutboundLinksTo)}
              onclick={(e) => {
                if ($settings.displayCopyMediaTitleNotLink) {
                  e.preventDefault();

                  navigator.clipboard.writeText(title.title.romaji);
                }
              }}
              target="_blank"
            >
              <span class="cover-container">
                <ParallaxImage
                  source={$settings.displayDataSaver
                    ? title.coverImage.medium
                    : title.coverImage.extraLarge}
                  alternativeText="Cover"
                  limit={12.5}
                  classList={`cover${
                    title.isAdult && $settings.displayBlurAdultContent ? ' adult' : ''
                  }`}
                />
              </span>
            </a>
          </div>
        </LinkedTooltip>

        <div class="cover-title">
          <slot name="title" {progress} {title} />
        </div>
      </div>
    {/if}
  {/each}
</div>
