<script>
	import Notice from '$lib/Error/Notice.svelte';
	import Message from '$lib/Loading/Message.svelte';
	import Chapters from '$lib/Reader/Chapters.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`)}
			<Message message="Loading chapters ..." />
		{:then response}
			{#if response.ok}
				{#await response.json() then data}
					{#if data.data}
						<Chapters {data} />
					{: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>
