<script lang="ts">
import type { Media } from "$lib/Data/AniList/media";
import MediaTitleDisplay from "$lib/List/MediaTitleDisplay.svelte";
import { outboundLink } from "$lib/Media/links";
import LinkedTooltip from "$lib/Tooltip/LinkedTooltip.svelte";
import settings from "$stores/settings";

export let media: Media[];
export let type: "anime" | "manga";
export let upcoming = false;
export let notYetReleased = false;
export let lastUpdatedMedia: number;
export let reverseSort = false;
export let disableTitleTooltip = false;

$: processedMedia = reverseSort ? [...media].reverse() : media;
</script>

<ul>
  {#each processedMedia as title (title.id)}
    {@const progress = (title.mediaListEntry || { progress: 0 }).progress}

    {#if type === 'anime' ? upcoming || notYetReleased || progress !== (title.nextAiringEpisode?.episode || 9999) - 1 : progress !== title.episodes}
      <li class="entry">
        <span class="content">
          <LinkedTooltip
            id={`${type}-${title.id}`}
            content={`<img src="${
              $settings.displayDataSaver ? title.coverImage.medium : title.coverImage.extraLarge
            }" style="width: 250px; object-fit: cover; border-radius: 8px;" />`}
            pin={`${type}-${title.id}`}
            pinPosition={type === 'anime' ? 'right' : 'left'}
            disable={!$settings.displayHoverCover}
          >
            <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
                style={lastUpdatedMedia === title.id && title.chapters !== progress
                  ? 'color: lightcoral'
                  : ''}
              >
                <MediaTitleDisplay title={title.title} tooltip={disableTitleTooltip} />
              </span>
            </a>
          </LinkedTooltip>
          {#if $settings.displaySocialButton}
            [<a href={`https://anilist.co/${type}/${title.id}/social`} target="_blank">S</a>]
          {/if}

          <slot name="information" {progress} {title} />
        </span>
      </li>
    {/if}
  {/each}
</ul>
