<script lang="ts">
	import { foodStore } from "$lib/store/Energy/foodStore";
	import { settingsStore } from "$lib/store/settingsStore";
	import { LerpColor } from "$lib/utils";
	import type { Color } from "$lib/utils";

	let remainingToday: number;
	let color: string;
	const green: Color = {
		h: 137,
		s: 100,
		l: 45,
	};
	const red: Color = {
		h: 0,
		s: 100,
		l: 45,
	};

	$: {
		remainingToday = $settingsStore.target;
		computeColor();
	}

	const formatter = new Intl.DateTimeFormat("en-GB", {
		year: "numeric",
		month: "2-digit",
		day: "2-digit",
		// Maybe add this to settings...
		timeZone: "Europe/Berlin",
	});

	$: {
		remainingToday = $settingsStore.target;
		let now = new Date();
		let todayDate = formatter.format(now);
		const [day, month, year] = todayDate.split("/");
		todayDate = `${year}-${month}-${day}`;

		if ($foodStore) {
			$foodStore.forEach((food) => {
				if (food.date.split("T")[0] == todayDate) {
					remainingToday -= food.energy;
				} else {
					return;
				}
			});
		}
		remainingToday = Math.round(remainingToday);
		computeColor();
	}

	function computeColor() {
		const newcolor = LerpColor(red, green, remainingToday / $settingsStore.target);
		color = `hsl(${newcolor.h}, ${newcolor.s}%, ${newcolor.l}%)`;
	}
</script>

<template>
	<div class="px-4 text-bold text-3xl" style="color: {color}">{remainingToday}</div>
</template>
