<script lang="ts">
	import { onMount } from 'svelte';

	let loading = $state(true);
	let error = $state(false);
	let notConnected = $state(false);

	let eaten = $state(0);
	let remaining = $state(0);
	let percent = $state(0);
	let calorieGoal = $state(0);

	let proteinCurrent = $state(0);
	let proteinGoal = $state(0);
	let carbsCurrent = $state(0);
	let carbsGoal = $state(0);
	let fatCurrent = $state(0);
	let fatGoal = $state(0);

	function fmt(n: number): string {
		return Math.round(n).toLocaleString();
	}

	onMount(async () => {
		const n = new Date();
		const today = `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`;

		try {
			const [totalsRes, goalsRes] = await Promise.all([
				fetch(`/api/fitness/entries/totals?date=${today}`),
				fetch(`/api/fitness/goals/for-date?date=${today}`)
			]);

			if (totalsRes.status === 401 || goalsRes.status === 401) {
				notConnected = true;
				loading = false;
				return;
			}

			if (!totalsRes.ok || (!goalsRes.ok && goalsRes.status !== 404)) {
				error = true;
				loading = false;
				return;
			}

			const totals = await totalsRes.json();

			eaten = totals.total_calories ?? 0;
			proteinCurrent = totals.total_protein ?? 0;
			carbsCurrent = totals.total_carbs ?? 0;
			fatCurrent = totals.total_fat ?? 0;

			if (goalsRes.ok) {
				const goals = await goalsRes.json();
				calorieGoal = goals.calories ?? 0;
				proteinGoal = goals.protein ?? 0;
				carbsGoal = goals.carbs ?? 0;
				fatGoal = goals.fat ?? 0;
			}

			remaining = Math.max(0, calorieGoal - eaten);
			percent = calorieGoal > 0 ? Math.min(100, Math.round((eaten / calorieGoal) * 100)) : 0;

			loading = false;
		} catch {
			error = true;
			loading = false;
		}
	});
</script>

<div class="module">
	<div class="module-header">
		<div class="module-title">Fitness &middot; Today</div>
		<a href="/fitness" class="module-action">Details &rarr;</a>
	</div>

	{#if notConnected}
		<div class="fitness-top">
			<div class="fitness-avatar">Y</div>
			<div>
				<div class="fitness-name">Yusuf</div>
				<div class="fitness-sub">Connect fitness to get started</div>
			</div>
		</div>
	{:else}
		<div class="fitness-top">
			<div class="fitness-avatar">Y</div>
			<div>
				<div class="fitness-name">Yusuf</div>
				<div class="fitness-sub">
					{#if loading}...{:else if error}&mdash;{:else}{fmt(eaten)} cal &middot; {fmt(remaining)} remaining{/if}
				</div>
			</div>
		</div>

		<div class="fitness-bar">
			<div class="fitness-bar-fill" style="width: {loading || error ? 0 : percent}%"></div>
		</div>

		<div class="fitness-macros">
			<div class="fitness-macro">
				<div class="fitness-macro-val">
					{#if loading}...{:else if error}&mdash;{:else}{Math.round(proteinCurrent)}<span class="fitness-macro-unit">/{Math.round(proteinGoal)}g</span>{/if}
				</div>
				<div class="fitness-macro-label">protein</div>
			</div>
			<div class="fitness-macro">
				<div class="fitness-macro-val">
					{#if loading}...{:else if error}&mdash;{:else}{Math.round(carbsCurrent)}<span class="fitness-macro-unit">/{Math.round(carbsGoal)}g</span>{/if}
				</div>
				<div class="fitness-macro-label">carbs</div>
			</div>
			<div class="fitness-macro">
				<div class="fitness-macro-val">
					{#if loading}...{:else if error}&mdash;{:else}{Math.round(fatCurrent)}<span class="fitness-macro-unit">/{Math.round(fatGoal)}g</span>{/if}
				</div>
				<div class="fitness-macro-label">fat</div>
			</div>
		</div>
	{/if}
</div>

<style>
	/* No .module/.module-header/.module-title/.module-action — using globals from app.css */

	.fitness-top {
		display: flex;
		align-items: center;
		gap: var(--sp-3);
		margin-bottom: var(--sp-4);
	}

	.fitness-avatar {
		width: var(--sp-10);
		height: var(--sp-10);
		border-radius: var(--radius-full);
		background: var(--accent-dim);
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: var(--text-base);
		font-weight: 600;
		color: var(--accent);
		flex-shrink: 0;
	}

	.fitness-name {
		font-size: var(--text-md);
		font-weight: 500;
		color: var(--text-1);
	}

	.fitness-sub {
		font-size: var(--text-sm);
		color: var(--text-3);
		margin-top: 1px;
	}

	.fitness-bar {
		height: var(--sp-1.5);
		background: var(--border);
		border-radius: 3px;
		overflow: hidden;
		margin-bottom: var(--sp-4);
	}

	.fitness-bar-fill {
		height: 100%;
		background: var(--accent);
		border-radius: 3px;
		transition: width 0.5s ease;
	}

	.fitness-macros {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
		gap: var(--row-gap);
	}

	.fitness-macro-val {
		font-size: var(--text-md);
		font-weight: 500;
		font-family: var(--mono);
		color: var(--text-1);
	}

	.fitness-macro-unit {
		font-size: var(--text-sm);
		font-weight: 400;
		color: var(--text-3);
	}

	.fitness-macro-label {
		font-size: var(--text-sm);
		color: var(--text-3);
		margin-top: var(--sp-0.5);
	}
</style>
