<script lang="ts">
	import { TrendingUp, TrendingDown, Minus } from 'lucide-svelte';
	import type { KPIMetric } from '$lib/api/dashboard/types';
	import { cn } from '$lib/utils';

	interface Props {
		metric: KPIMetric;
		icon?: any;
		iconColor?: string;
	}

	let { metric, icon: Icon, iconColor = 'text-primary' }: Props = $props();

	const iconBgMap: Record<string, string> = {
		'text-blue-600':   'bg-blue-50   dark:bg-blue-950/40',
		'text-green-600':  'bg-green-50  dark:bg-green-950/40',
		'text-purple-600': 'bg-purple-50 dark:bg-purple-950/40',
		'text-orange-600': 'bg-orange-50 dark:bg-orange-950/40',
		'text-cyan-600':   'bg-cyan-50   dark:bg-cyan-950/40',
		'text-yellow-600': 'bg-yellow-50 dark:bg-yellow-950/40'
	};

	const trendColors = {
		up:     'text-emerald-600',
		down:   'text-red-500',
		stable: 'text-slate-400'
	};

	const TrendIcon = metric.trend ? { up: TrendingUp, down: TrendingDown, stable: Minus }[metric.trend] : null;
	let iconBg = $derived(iconBgMap[iconColor] ?? 'bg-primary/10');
</script>

<div class="flex items-center gap-4 rounded-xl border bg-card px-4 py-3.5 hover:shadow-sm transition-shadow">
	{#if Icon}
		<div class={cn('flex h-9 w-9 shrink-0 items-center justify-center rounded-lg', iconBg)}>
			<Icon class={cn('h-4 w-4', iconColor)} />
		</div>
	{/if}

	<div class="flex-1 min-w-0">
		<p class="text-xs text-muted-foreground truncate">{metric.label}</p>
		<div class="flex items-baseline gap-2 mt-0.5">
			<span class="text-xl font-bold tabular-nums leading-none">
				{metric.value.toLocaleString()}{#if metric.unit}<span class="text-sm font-normal text-muted-foreground ml-0.5">{metric.unit}</span>{/if}
			</span>
			{#if metric.percentage_change !== undefined && TrendIcon && metric.trend}
				<span class={cn('flex items-center gap-0.5 text-xs font-medium', trendColors[metric.trend])}>
					<TrendIcon class="h-3 w-3" />
					{Math.abs(metric.percentage_change).toFixed(1)}%
				</span>
			{/if}
		</div>
	</div>
</div>
