<script lang="ts">
	import {
		fillMissingDays,
		type ActivityHistoryEntry,
		activityHistory
	} from '$lib/Data/AniList/activity';
	import { onMount } from 'svelte';
	import userIdentity from '$stores/identity';
	import type { AniListAuthorisation } from '$lib/Data/AniList/identity';
	import { clearAllParameters } from '../../Utility/parameters';
	import Skeleton from '$lib/Loading/Skeleton.svelte';
	import tooltip from '$lib/Tooltip/tooltip';
	import LogInRestricted from '$lib/Error/LogInRestricted.svelte';

	export let user: AniListAuthorisation;
	export let activityData: ActivityHistoryEntry[] | null = null;
	export let currentYear = new Date().getFullYear();

	let activityHistoryData: ActivityHistoryEntry[];
	let baseHue = Math.floor(Math.random() * 360);

	onMount(async () => {
		clearAllParameters();

		activityHistoryData = activityData || (await activityHistory($userIdentity));
	});

	const gradientColour = (amount: number, maxAmount: number, baseHue: number) => {
		const lightness = 100 - Math.round((amount / maxAmount) * 50);

		return `hsl(${baseHue}, 100%, ${lightness}%)`;
	};
</script>

{#if user === undefined}
	<LogInRestricted />
{:else if activityHistoryData === undefined}
	<Skeleton card={false} count={1} height="150px" />
{:else}
	{@const filledActivities = fillMissingDays(activityHistoryData, false, currentYear)}
	{@const highestActivity = Math.max(...filledActivities.map((activity) => activity.amount))}

	<div class="grid">
		{#each filledActivities as activity}
			<div
				class="grid-item"
				style="background-color: {gradientColour(activity.amount, highestActivity, baseHue)}"
				on:click={() => (baseHue = Math.floor(Math.random() * 360))}
				on:keydown={() => {
					return;
				}}
				role="button"
				tabindex="0"
				use:tooltip
				title={`Date: ${new Date(activity.date * 1000).toLocaleDateString()}\nAmount: ${
					activity.amount
				}`}
			/>
		{/each}
	</div>
{/if}

<style>
	.grid {
		display: grid;
		grid-template-columns: repeat(52, 1fr);
		grid-template-rows: repeat(7, 1fr);
		/* gap: 2px; */
		grid-auto-flow: column;
		width: min-content;
		background-color: white;
		border-radius: 3px;
		overflow: hidden;
	}
	.grid-item {
		width: 20px;
		height: 20px;
		/* width: 3.25vw; */
		/* height: 3.25vw; */
		/* border: 1px solid #ccc; */
	}
</style>
