<script lang="ts">
	import type { Media } from '$lib/AniList/media';
	import settings from '$stores/settings';
	import { onDestroy, onMount } from 'svelte';
	import type { SubsPlease } from './Subtitled/subsPlease';
	import type { MediaPrequel } from '$lib/AniList/prequels';
	import { injectAiringTime } from './Subtitled/match';
	import tooltip from '$lib/Tooltip/tooltip';

	export let originalAnime: Media;
	export let subsPlease: SubsPlease | null;
	export let upcoming = false;

	const anime = injectAiringTime(originalAnime, subsPlease);
	let opacity = 100;
	let timeFrame = '';
	let time = '';
	let nextEpisode = anime.nextAiringEpisode?.episode || 0;
	let few = true;
	let dateString = '';
	let updateInterval: NodeJS.Timeout;

	onMount(() => {
		const setAiringTime = () => {
			time = '';
			timeFrame = '';
			dateString = '';

			const airingAt = anime.nextAiringEpisode?.airingAt;
			const untilAiring = airingAt
				? Math.round((airingAt - Date.now() / 1000) * 100) / 100
				: undefined;
			let hours = null;
			const shortenCountdown = $settings.displayShortCountdown;

			time = new Date(airingAt ? airingAt * 1000 : 0).toLocaleTimeString([], {
				hour12: !$settings.display24HourTime,
				hour: 'numeric',
				minute: '2-digit'
			});

			if (
				(anime as unknown as MediaPrequel).startDate &&
				new Date(
					anime.startDate.year,
					(anime as unknown as MediaPrequel).startDate.month,
					(anime as unknown as MediaPrequel).startDate.day
				) < new Date()
			)
				return `<span class="opaque">on ${new Date(
					anime.startDate.year,
					(anime as unknown as MediaPrequel).startDate.month,
					(anime as unknown as MediaPrequel).startDate.day
				).toLocaleDateString()}</span>`;

			if (untilAiring !== undefined) {
				let minutes = untilAiring / 60;

				few = true;

				if (minutes > 60) {
					hours = minutes / 60;

					if (hours > 24) {
						let weeks = Math.floor(hours / 24) / 7;

						few = false;

						if (weeks >= 1.5) {
							weeks = Math.round(weeks);

							timeFrame = `${weeks}${shortenCountdown ? 'w' : ' week'}${
								weeks === 1 || shortenCountdown ? '' : 's'
							}`;
						} else {
							const days = Math.round(Math.floor(hours / 24));
							const residualHours = Math.floor(hours - days * 24);

							timeFrame += `${days.toFixed(0)}${shortenCountdown ? 'd' : ' day'}${
								days === 1 || shortenCountdown ? '' : 's'
							}`;

							if (residualHours > 0)
								timeFrame += `${shortenCountdown ? '' : ' '}${residualHours}${
									shortenCountdown ? 'h' : ' hour'
								}${residualHours === 1 || shortenCountdown ? '' : 's'}`;
						}
					} else {
						const residualMinutes = Math.round(minutes - Math.floor(hours) * 60);

						timeFrame += `${hours.toFixed(0)}${shortenCountdown ? 'h' : '  hour'}${
							hours === 1 || shortenCountdown ? '' : 's'
						}`;

						if (residualMinutes > 0)
							timeFrame += `${shortenCountdown ? '' : ' '}${residualMinutes}${
								shortenCountdown ? 'm' : ' minute'
							}${residualMinutes === 1 || shortenCountdown ? '' : 's'}`;
					}
				} else {
					minutes = Math.round(minutes);

					timeFrame += `${minutes}${shortenCountdown ? 'm' : '  minute'}${
						minutes === 1 || shortenCountdown ? '' : 's'
					}`;
				}

				opacity = Math.max(50, 100 - (untilAiring / 60 / 60 / 24 / 7) * 50);
				dateString =
					new Date(airingAt ? airingAt * 1000 : 0).toLocaleDateString([], {
						weekday: 'long',
						year: 'numeric',
						month: 'long',
						day: 'numeric'
					}) +
					' ' +
					time;
			}
		};

		setAiringTime();

		updateInterval = setInterval(setAiringTime, 30000);
	});

	onDestroy(() => clearInterval(updateInterval));
</script>

{#if upcoming}
	<span title={dateString} use:tooltip style={`opacity: ${opacity}%;`}>
		{nextEpisode}{#if anime.episodes !== null}<span class="opaque">/{anime.episodes}</span>
		{/if} in {timeFrame}
		<span class="opaque">
			{#if few && $settings.displayCoverMode}<br />{/if}{few ? `(${time})` : ''}
		</span>
	</span>
{:else}
	<span title={dateString} use:tooltip style={`opacity: ${opacity}%;`}>
		{nextEpisode} in {#if few && $settings.displayCoverMode}<br />{/if}{#if few}<b>
				{timeFrame}
			</b>{:else}{timeFrame}{/if}
		{few ? `(${time})` : ''}
	</span>
{/if}
