<script lang="ts">
	import { today } from '$lib/db/helpers';

	interface Props {
		selectedDate: string;
		onchange: (date: string) => void;
	}
	let { selectedDate, onchange }: Props = $props();

	const isToday = $derived(selectedDate === today());

	function shiftDate(days: number) {
		const d = new Date(selectedDate + 'T00:00:00');
		d.setDate(d.getDate() + days);
		const y = d.getFullYear();
		const m = String(d.getMonth() + 1).padStart(2, '0');
		const day = String(d.getDate()).padStart(2, '0');
		onchange(`${y}-${m}-${day}`);
	}

	function handleInput(e: Event) {
		const val = (e.target as HTMLInputElement).value;
		if (val) onchange(val);
	}
</script>

<div class="mb-4 flex items-center gap-2">
	<button
		class="rounded bg-sidebar px-2.5 py-1.5 text-sm text-white hover:bg-[#444]"
		onclick={() => shiftDate(-1)}
		title="Vortag"
	>&larr;</button>

	<input
		type="date"
		class="rounded border border-[#444] bg-bg px-2 py-1.5 text-sm text-white"
		value={selectedDate}
		oninput={handleInput}
	/>

	<button
		class="rounded bg-sidebar px-2.5 py-1.5 text-sm text-white hover:bg-[#444]"
		onclick={() => shiftDate(1)}
		title="Nächster Tag"
	>&rarr;</button>

	{#if !isToday}
		<button
			class="rounded bg-accent px-3 py-1.5 text-sm font-bold text-white hover:brightness-110"
			onclick={() => onchange(today())}
		>Heute</button>
	{/if}
</div>
