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

	let spending = $state('...');
	let month = $state('');
	let topCats = $state<{ name: string; amount: string; isIncome: boolean }[]>([]);

	onMount(async () => {
		try {
			const res = await fetch('/api/budget/summary', { credentials: 'include' });
			if (res.ok) {
				const data = await res.json();
				spending = '$' + Math.abs(data.spendingDollars || 0).toLocaleString('en-US');
				const m = data.month || '';
				if (m) {
					const d = new Date(m + '-01');
					month = d.toLocaleDateString('en-US', { month: 'long' });
				}
				const income = data.incomeDollars || 0;
				const cats = (data.topCategories || []).map((c: any) => ({
					name: c.name,
					amount: '$' + Math.abs(c.amountDollars || 0).toLocaleString('en-US'),
					isIncome: false
				}));
				if (income > 0) {
					topCats = [{ name: 'Income', amount: '+$' + Math.abs(income).toLocaleString('en-US'), isIncome: true }, ...cats];
				} else {
					topCats = cats;
				}
			}
		} catch { /* silent */ }
	});
</script>

<div class="module primary">
	<div class="module-header">
		<div class="module-title">Budget{month ? ' · ' + month : ''}</div>
		<a href="/budget" class="module-action">View all &rarr;</a>
	</div>

	<div class="budget-hero">
		<div class="budget-amount">{spending}</div>
		<div class="budget-label">spent this month</div>
	</div>

	<div class="budget-rows">
		{#each topCats as cat}
			<div class="budget-row">
				<span class="budget-row-name">{cat.name}</span>
				<span class="budget-row-amount" class:income={cat.isIncome}>{cat.amount}</span>
			</div>
		{/each}
	</div>
</div>

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

	.budget-hero {
		margin-bottom: var(--sp-5);
	}

	.budget-amount {
		font-size: 36px;
		font-weight: 800;
		font-family: var(--mono);
		letter-spacing: -0.04em;
		color: var(--text-1);
		line-height: 1;
	}

	.budget-label {
		font-size: 12px;
		color: var(--text-4);
		margin-top: 4px;
	}

	.budget-rows {
		display: flex;
		flex-direction: column;
	}

	.budget-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: var(--sp-3) 0;
		border-bottom: 1px solid var(--border);
	}

	.budget-row:last-child {
		border-bottom: none;
	}

	.budget-row-name {
		font-size: 13px;
		color: var(--text-3);
	}

	.budget-row-amount {
		font-size: 12px;
		font-family: var(--mono);
		font-weight: 500;
		color: var(--text-2);
	}

	.budget-row-amount.income {
		color: var(--accent);
	}

	@media (max-width: 768px) {
		.budget-amount {
			font-size: var(--text-2xl);
		}
	}
</style>
