<script lang="ts">
import { onDestroy, onMount } from "svelte";
import { browser } from "$app/environment";
import HeadTitle from "$lib/Home/HeadTitle.svelte";
import Skeleton from "$lib/Loading/Skeleton.svelte";
import { createHeightObserver } from "$lib/Utility/html";
import root from "$lib/Utility/root";
import { sanitizeFeedHtml } from "$lib/Utility/sanitizeHtml";
import locale from "$stores/locale";

let feed:
	| { items: { title: string; link: string; content: string }[] }
	| null
	| undefined;
let novelFeed:
	| {
			data: {
				items: {
					srcurl: string;
					postfix?: string;
					chapter: number;
					series: { name: string };
				}[];
			};
	  }
	| null
	| undefined;
let startTime: number;
let mangaEndTime: number;
let novelEndTime: number;
let directLink = browser
	? new URLSearchParams(window.location.search).has("d")
	: false;
let removeHeightObserver: (() => void) | undefined;

const fetchJson = async (path: string) => {
	try {
		const response = await fetch(root(path));

		return response.ok ? await response.json() : null;
	} catch {
		return null;
	}
};

onMount(async () => {
	removeHeightObserver = createHeightObserver(false);

	startTime = performance.now();

	const allNovels = await fetchJson("/api/updates/all-novels");

	if (allNovels?.data?.items)
		for (const item of allNovels.data.items) {
			if (item.postfix) item.postfix = sanitizeFeedHtml(item.postfix);
			if (item.series) item.series.name = sanitizeFeedHtml(item.series.name);
		}

	novelFeed = allNovels?.data?.items ? allNovels : null;
	novelEndTime = performance.now() - startTime;
	startTime = performance.now();

	const mangaFeed = await fetchJson("/api/updates/manga");

	if (mangaFeed?.items)
		for (const item of mangaFeed.items) {
			item.title = sanitizeFeedHtml(item.title);
			item.content = sanitizeFeedHtml(item.content);
		}

	feed = mangaFeed?.items ? mangaFeed : null;
	mangaEndTime = performance.now() - startTime;
});

onDestroy(() => removeHeightObserver?.());

const reformatChapter = (title: string) =>
	title
		.replace(/\[.*?\]\s/, "")
		.replace(/c\.Oneshot/, "Oneshot")
		.replace(/c\.(\d+-\d+)/, "Ch. $1")
		.replace(/v\.(\d+)\s/, "Vol. $1 ")
		.replace(/c\.(\d+)/, "Ch. $1");

const clipTitle = (title: string) =>
	title
		.replace(/(Vol\. \d+ )?Ch\. \d+(-\d+(\.\d+)?)?$/, "")
		.replace(/\? ~.*$/, "")
		.trim();

// const italicTitle = (title: string) =>
// 	title.replace(/^(.*?) (Vol\.|Ch\.|\bOneshot\b)/, '<i>$1</i> $2');

const chapterTitle = (title: string) =>
	title.replace(/^(.*?) (Vol\.|Ch\.|\bOneshot\b)/, "$2");
</script>

<HeadTitle routeKey="updates" path="/updates" />

<div class="list-container">
  <details open class="list">
    <summary>
      {$locale().routes?.updatesManga}
      <small class="opaque">{mangaEndTime ? mangaEndTime / 1000 : '...'}s</small>
    </summary>

    {#if feed === null}
      {$locale().routes?.updatesFailedToLoad}
    {:else if feed !== undefined}
      <ul>
        {#each feed.items as item}
          <li>
            {#if directLink}
              <i>{reformatChapter(item.title)}</i>

              {@html item.content}
            {:else}
              <a
                href={`https://anilist.co/search/manga?search=${clipTitle(
                  reformatChapter(item.title)
                )}&sort=SEARCH_MATCH`}
              >
                <i>{@html clipTitle(reformatChapter(item.title))}</i>
              </a>
              {@html chapterTitle(reformatChapter(item.title))}
            {/if}
          </li>
        {/each}
      </ul>
    {:else}
      <Skeleton card={false} count={5} height="0.9rem" list />
    {/if}
  </details>

  <details open class="list">
    <summary>
      {$locale().routes?.updatesNovels}
      <small class="opaque">{novelEndTime ? novelEndTime / 1000 : '...'}s</small>
    </summary>

    {#if novelFeed === null}
      {$locale().routes?.updatesFailedToLoad}
    {:else if novelFeed !== undefined}
      <ul>
        {#each novelFeed.data.items as item}
          <li>
            {#if directLink}
              <a href={item.srcurl}>
                <i>{@html item.series.name}</i>
                {@html item.postfix || `Ch. ${item.chapter}`}
              </a>
            {:else}
              <a
                href={`https://anilist.co/search/manga?search=${item.series.name}&sort=SEARCH_MATCH`}
              >
                <i>{@html item.series.name}</i>
              </a>
              {@html item.postfix || `Ch. ${item.chapter}`}
            {/if}
          </li>
        {/each}
      </ul>
    {:else}
      <Skeleton card={false} count={5} height="0.9rem" list />
    {/if}
  </details>
</div>

<style>
  .list-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    align-items: start;
    gap: 1em;
    flex-wrap: wrap;
  }

  .list {
    overflow-y: auto;
    min-width: 300px;
    flex: 1 1 300px;
  }
</style>
