<script>
	import Notice from '$lib/Error/Notice.svelte';
	import InputTemplate from '$lib/Tools/InputTemplate.svelte';

	let submission = '';

	$: mangaDexID = submission.match(/mangadex\.org\/title\/([a-f0-9-]+)\/?/)?.[1];
</script>

<InputTemplate field="MangaDex URL" bind:submission submitText="Read" preserveCase>
	{#if mangaDexID}
		{#await fetch(`https://api.mangadex.org/manga/${mangaDexID}/feed?order[chapter]=desc&translatedLanguage[]=en`)}
			<!--  -->
		{:then response}
			{#if response.ok}
				{#await response.json() then data}
					{#if data.data}
						<ul>
							{#each data.data as chapter}
								<li>
									{#if chapter.attributes.volume}
										Vol. {chapter.attributes.volume}
									{/if}
									Ch. {chapter.attributes.chapter}
									<span class="opaque">|</span>
									<a
										href={`https://mangadex.org/chapter/${chapter.id}`}
										target="_blank"
										rel="noopener noreferrer"
									>
										{chapter.attributes.title}
									</a>
								</li>
							{/each}
						</ul>
					{:else}
						<p class="opaque">(⌣_⌣”)</p>
					{/if}
				{:catch error}
					<Notice>{error}</Notice>
				{/await}
			{:else}
				<Notice>Failed to fetch data from MangaDex</Notice>
			{/if}
		{:catch error}
			{error}
		{/await}
	{:else}
		<Notice>Invalid URL</Notice>
	{/if}
</InputTemplate>
