<script lang="ts">
	import userIdentity from '$stores/userIdentity';
	import { onMount } from 'svelte';
	import {
		userIdentity as getUserIdentity,
		type AniListAuthorisation
	} from '$lib/AniList/identity';
	import { lastActivityDate } from '../AniList/activity';
	import settings from '$stores/settings';

	export let user: AniListAuthorisation;

	let currentUserIdentity = {
		name: '',
		id: -1,
		avatar: 'https://s4.anilist.co/file/anilistcdn/user/avatar/large/default.png'
	};
	let lastActivityWasToday = true;

	onMount(async () => {
		if (user !== undefined) {
			if ($userIdentity === '') {
				userIdentity.set(JSON.stringify(await getUserIdentity(user)));
			}

			currentUserIdentity = JSON.parse($userIdentity);
			currentUserIdentity.name = currentUserIdentity.name;
			lastActivityWasToday =
				(await lastActivityDate(currentUserIdentity, user)).date.toDateString() >=
				new Date().toDateString();

			if (!lastActivityWasToday) {
				if ($settings.displayLimitListHeight) {
					document.querySelectorAll('.list').forEach((list) => {
						(list as HTMLElement).style.maxHeight = `calc((100vh - ${
							document.querySelector('#list-container')?.getBoundingClientRect().top
						}px) - 5rem)`;
					});
				}
			}
		}
	});

	const timeLeftToday = () => {
		const now = new Date();
		const currentHour = now.getHours();
		const currentMinute = now.getMinutes();
		const hoursLeft = 24 - currentHour;
		let minutesLeft = 0;
		let timeLeft = '';

		if (hoursLeft > 0) {
			minutesLeft = hoursLeft * 60 - currentMinute;
		} else {
			minutesLeft = 24 * 60 - (currentHour * 60 + currentMinute);
		}

		if (minutesLeft > 60) {
			timeLeft = `${Math.round(minutesLeft / 60)} hours`;
		} else {
			timeLeft = `${minutesLeft} minutes`;
		}

		return timeLeft;
	};
</script>

{#if !lastActivityWasToday}
	<blockquote>
		You don't have any new activity statuses from the past day! Create one within {timeLeftToday()}
		to keep your streak!
	</blockquote>
{/if}
