<script lang="ts">
	import { onMount } from 'svelte';

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

	let feed: Feed = undefined;
	let novelFeed: Feed = undefined;
	let startTime: number;
	let mangaEndTime: number;
	let novelEndTime: number;

	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 reformat = (title: string) => {
		return title
			.replace(/\[.*?\]\s/, '')
			.replace(/c\.Oneshot/, 'Oneshot')
			.replace(/c\.(\d+-\d+)/, 'Ch. $1')
			.replace(/v\.(\d+)\s/, 'Vol. $1 ')
			.replace(/c\.(\d+)/, 'Ch. $1');
	};

	function reformatChapters(title: string): string {
		return title
			.replace(/(Vol\. \d+ )?Ch\. \d+(-\d+(\.\d+)?)?$/, '')
			.replace(/\? ~.*$/, '')
			.trim();
	}
</script>

<div id="list-container">
	<div>
		<details open>
			<summary>
				Manga
				<small style="opacity: 50%">{(mangaEndTime || 0) / 1000}s</small>
			</summary>

			<ul>
				{#if feed === null}
					<li>Failed to load feed</li>
				{:else if feed !== undefined}
					{#each feed.items as item}
						<li>
							<a
								href={`https://anilist.co/search/manga?search=${reformatChapters(
									reformat(item.title)
								)}&sort=SEARCH_MATCH`}
							>
								{reformat(item.title)}
							</a>
						</li>
					{/each}
				{:else}
					<li>Loading ...</li>
				{/if}
			</ul>
		</details>
	</div>

	<div>
		<details open>
			<summary>
				Light Novels
				<small style="opacity: 50%">{(novelEndTime || 0) / 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}>
								{reformat(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>
