<script lang="ts">
	import type { WeeklySales } from '$lib/types/dashboard';
	import { formatRupiahShort } from '$lib/utils/format';

	interface Props {
		data: WeeklySales[];
	}

	let { data }: Props = $props();

	const maxValue = $derived(Math.max(...data.map((d) => d.total), 1));
	const totalMinggu = $derived(data.reduce((sum, d) => sum + d.total, 0));
	const rataRata = $derived(Math.round(totalMinggu / data.length));
</script>

<div class="card bg-base-100 shadow-md">
	<div class="card-body gap-4 p-4 lg:p-6">
		<div class="flex items-center justify-between">
			<div>
				<h3 class="text-base font-bold lg:text-lg">Penjualan Minggu Ini</h3>
				<p class="text-xs text-base-content/50 lg:text-sm">7 hari terakhir</p>
			</div>
			<div class="text-right">
				<p class="text-xs text-base-content/50">Total</p>
				<p class="text-sm font-bold text-primary lg:text-base">{formatRupiahShort(totalMinggu)}</p>
			</div>
		</div>

		<div class="flex h-40 items-end justify-between gap-1.5 sm:gap-2 lg:h-52 lg:gap-3">
			{#each data as day (day.date)}
				{@const height = Math.max((day.total / maxValue) * 100, day.total > 0 ? 8 : 4)}
				<div class="group flex flex-1 flex-col items-center gap-2">
					<div class="relative flex h-full w-full items-end justify-center">
						<div
							class="w-full max-w-10 rounded-t-lg transition-all duration-500 {day.isToday
								? 'bg-gradient-to-t from-emerald-600 to-teal-400 shadow-lg shadow-emerald-200'
								: 'bg-gradient-to-t from-emerald-200 to-emerald-400 group-hover:from-emerald-300 group-hover:to-emerald-500'}"
							style="height: {height}%"
							title="{day.label}: {formatRupiahShort(day.total)}"
						></div>
						{#if day.isToday}
							<div
								class="absolute -top-6 left-1/2 -translate-x-1/2 whitespace-nowrap rounded-full bg-emerald-600 px-2 py-0.5 text-[10px] font-semibold text-white"
							>
								Hari ini
							</div>
						{/if}
					</div>
					<div class="text-center">
						<p
							class="text-[10px] font-semibold sm:text-xs {day.isToday
								? 'text-emerald-600'
								: 'text-base-content/60'}"
						>
							{day.label}
						</p>
						<p class="hidden text-[10px] text-base-content/40 sm:block">
							{formatRupiahShort(day.total)}
						</p>
					</div>
				</div>
			{/each}
		</div>

		<div class="flex items-center justify-between rounded-xl bg-base-200/70 px-4 py-3">
			<div>
				<p class="text-xs text-base-content/50">Rata-rata / hari</p>
				<p class="text-sm font-bold">{formatRupiahShort(rataRata)}</p>
			</div>
			<div class="divider divider-horizontal mx-0"></div>
			<div class="text-right">
				<p class="text-xs text-base-content/50">Hari tercatat</p>
				<p class="text-sm font-bold">{data.filter((d) => d.total > 0).length} / 7</p>
			</div>
		</div>
	</div>
</div>
