<script lang="ts">
	/* eslint svelte/no-at-html-tags: "off" */

	import { browser } from '$app/environment';
	import { onMount } from 'svelte';

	type Feed = { items: { title: string; link: string; content: string }[] } | null | undefined;

	let feed: Feed = undefined;
	let novelFeed: Feed = undefined;
	let startTime: number;
	let mangaEndTime: number;
	let novelEndTime: number;
	let directLink = browser ? new URLSearchParams(window.location.search).has('d') : false;

	onMount(async () => {
		startTime = performance.now();
		novelFeed = await (await fetch('/api/novel-updates')).json();
		novelEndTime = performance.now() - startTime;
		startTime = performance.now();
		feed = await (await fetch('/api/manga-updates')).json();
		mangaEndTime = performance.now() - startTime;
	});

	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): string =>
		title
			.replace(/(Vol\. \d+ )?Ch\. \d+(-\d+(\.\d+)?)?$/, '')
			.replace(/\? ~.*$/, '')
			.trim();

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

<div id="list-container">
	<div>
		<details open>
			<summary>
				Manga
				<small style="opacity: 50%">{mangaEndTime ? mangaEndTime / 1000 : '...'}s</small>
			</summary>

			<ul>
				{#if feed === null}
					<li>Failed to load feed</li>
				{:else if feed !== undefined}
					{#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`}
								>
									{@html italicTitle(reformatChapter(item.title))}
								</a>
							{/if}
						</li>
					{/each}
				{:else}
					<li>Loading ...</li>
				{/if}
			</ul>
		</details>
	</div>

	<div>
		<details open>
			<summary>
				Light Novels
				<small style="opacity: 50%">{novelEndTime ? novelEndTime / 1000 : '...'}s</small>
			</summary>

			<ul>
				{#if novelFeed === null}
					<li>Failed to load feed</li>
				{:else if novelFeed !== undefined}
					{#each novelFeed.items as item}
						<li>
							<a href={item.link}>
								{reformatChapter(item.title)}
							</a>
						</li>
					{/each}
				{:else}
					<li>Loading ...</li>
				{/if}
			</ul>
		</details>
	</div>
</div>

<style>
	#list-container {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
	}
</style>
