<script lang="ts">
import { onMount } from "svelte";
import { get } from "svelte/store";
import type { AniListAuthorisation } from "$lib/Data/AniList/identity";
import userIdentity from "$stores/identity";
import locale from "$stores/locale";
import settings from "$stores/settings";
import { lastActivityDate } from "../Data/AniList/lastActivity";

let { user }: { user: AniListAuthorisation } = $props();
let lastActivityWasToday = $state(true);

onMount(async () => {
	if (!$settings.displayDisableLastActivityWarning && user !== undefined) {
		lastActivityWasToday =
			(await lastActivityDate($userIdentity, 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 = "";
	const l = get(locale)();

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

	if (minutesLeft > 60) {
		timeLeft = `${Math.round(minutesLeft / 60)} ${l.home?.lastActivity?.hoursUnit ?? "hours"}`;
	} else {
		timeLeft = `${minutesLeft} ${l.home?.lastActivity?.minutesUnit ?? "minutes"}`;
	}

	return timeLeft;
};
</script>

{#if !$settings.displayDisableLastActivityWarning && !lastActivityWasToday}
  <blockquote>
    {$locale({ values: { timeLeft: timeLeftToday() } }).home?.lastActivity?.warning}
  </blockquote>
{/if}
