<script lang="ts">
	import type { Media } from '$lib/Data/AniList/media';
	import Error from '$lib/Error/RateLimited.svelte';
	import { volumeCount } from '$lib/Media/Manga/volumes';
	import settings from '$stores/settings';
	import ListTitle from '../ListTitle.svelte';
	import { onMount } from 'svelte';
	import root from '$lib/Utility/root';
	import locale from '$stores/locale';
	import Skeleton from '$lib/Loading/Skeleton.svelte';
	import { browser } from '$app/environment';
	import proxy from '$lib/Utility/proxy';
	import '../covers.css';
	import CleanGrid from '../CleanGrid.svelte';
	import CleanList from '../CleanList.svelte';

	export let media: Media[];
	export let cleanCache: () => void;
	export let endTime: number;
	export let lastUpdatedMedia: number;
	export let updateMedia: (
		id: number,
		progress: number | undefined,
		media: Media[]
	) => Promise<void>;
	export let pendingUpdate: number | null;
	export let due: boolean;
	export let rateLimited: boolean;
	export let authorised: boolean;
	export let dummy = false;

	let serviceStatusResponse: Promise<Response>;

	onMount(() => {
		serviceStatusResponse = fetch(proxy('https://api.mangadex.org/ping'));

		if (browser)
			localStorage.setItem(`last${due ? '' : 'Completed'}MangaListLength`, media.length.toString());
	});

	const increment = (manga: Media) => {
		if (!(pendingUpdate === manga.id || dummy))
			updateMedia(manga.id, manga.mediaListEntry?.progress, media);
	};
</script>

{#if authorised}
	<ListTitle
		count={media.length}
		time={endTime / 1000}
		title={due
			? $locale().lists.due.mangaAndLightNovels
			: $locale().lists.completed.mangaAndLightNovels}
		hideTime={dummy}
		hideCount={dummy}
	>
		{#if !dummy}
			<button
				class="small-button"
				title="Force a full refresh"
				on:click={cleanCache}
				data-umami-event="Force Refresh Manga">Refresh</button
			>
		{/if}
	</ListTitle>
{/if}

{#if rateLimited}
	{#await serviceStatusResponse}
		<Skeleton card={false} count={1} height="0.9rem" list />
	{:then status}
		{#if status}
			{#if status.status === 503}
				<a href="https://due.moe">due.moe</a>'s manga data source is currently down for maintenance.
				Please check back later.
			{:else if status.status !== 200}
				<a href="https://due.moe">due.moe</a>'s manga data source is currently unavailable. Please
				check back later.
			{:else}
				<Error />
			{/if}
		{:else}
			<Skeleton card={false} count={1} height="0.9rem" list />
		{/if}
	{:catch}
		<a href="https://due.moe">due.moe</a>'s manga data source is currently unreachable. Please check
		back later.
	{/await}
{/if}

{#if media.length === 0 && !rateLimited}
	{#if rateLimited}
		<p />
	{/if}

	<p>
		No manga to display. <button on:click={cleanCache} data-umami-event="Force Refresh No Manga"
			>Force refresh</button
		>
	</p>

	<span>
		Don't read manga? <button
			on:click={() => ($settings.disableManga = true)}
			data-umami-event="Disable No Manga">Hide the manga panel</button
		>
		You can re-enable it later in the <a href={root('/settings')}>Settings</a>.
	</span>
{/if}

{#if $settings.displayCoverModeManga || dummy}
	<CleanGrid {media} {dummy} type="manga">
		<div slot="title" let:title={manga} let:progress>
			{pendingUpdate === manga.id ? progress + 1 : progress}{#if !due}
				<span class="opaque">/{manga.chapters || '?'}</span>
			{/if}
			<button
				class={`button-square button-action ${pendingUpdate === manga.id ? 'opaque' : ''}`}
				style={pendingUpdate === manga.id ? 'pointer-events: none;' : ''}
				on:click={() => increment(manga)}
			>
				+
			</button>
			{#if due || Math.floor(manga.episodes) < manga.chapters}
				[{manga.episodes || '?'}]
				{#await volumeCount(manga) then volumes}
					{@const volumeProgress = manga.mediaListEntry?.progressVolumes}

					{#if volumes !== null && (volumeProgress || 0) < volumes}
						<span style="color: lightcoral;">
							Vol. {volumeProgress} &#8594; {volumes}
						</span>
					{/if}
				{/await}
			{/if}
		</div>
	</CleanGrid>
{:else}
	<CleanList {media} type="manga" {lastUpdatedMedia}>
		<span slot="information" let:title={manga} let:progress>
			<span class="opaque">|</span>
			{pendingUpdate === manga.id ? progress + 1 : progress}{#if !due}
				<span class="opaque">/{manga.chapters || '?'}</span>
			{/if}
			<button
				class={`button-square button-action ${pendingUpdate === manga.id ? 'opaque' : ''}`}
				style={pendingUpdate === manga.id ? 'pointer-events: none;' : ''}
				on:click={() => increment(manga)}
			>
				+
			</button>
			{#if due || Math.floor(manga.episodes) < manga.chapters}
				[{manga.episodes || '?'}]
				{#await volumeCount(manga) then volumes}
					{@const volumeProgress = manga.mediaListEntry?.progressVolumes}

					{#if volumes !== null && (volumeProgress || 0) < volumes}
						<span style="color: lightcoral;">
							Vol. {volumeProgress} &#8594; {volumes}
						</span>
					{/if}
				{/await}
			{/if}
		</span>
	</CleanList>
{/if}
