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

	let submission = '';

	$: mangaDexID = submission.match(/(?<=\/title\/)(.*?)(?=\/)/g);
</script>

<InputTemplate field="MangaDex URL" bind:submission submitText="Read">
	{#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}
					{error}
				{/await}
			{:else}
				Invalid URL
			{/if}
		{:catch error}
			{error}
		{/await}
	{:else}
		Invalid URL
	{/if}
</InputTemplate>
