<!--
  Event log entry — timeline style.
  Left severity color bar, compact inline layout, expandable metadata.
-->
<script lang="ts">
	import type { EventLogEntry } from '$lib/types';
	import { t } from '$lib/i18n';

	interface Props {
		entry: EventLogEntry;
		isNew?: boolean;
	}

	const { entry, isNew = false }: Props = $props();

	let expanded = $state(false);

	function timeAgo(dateStr: string): string {
		const now = Date.now();
		const then = new Date(dateStr).getTime();
		const diffSec = Math.floor((now - then) / 1000);
		if (diffSec < 60) return `${diffSec}s ago`;
		const diffMin = Math.floor(diffSec / 60);
		if (diffMin < 60) return `${diffMin}m ago`;
		const diffHour = Math.floor(diffMin / 60);
		if (diffHour < 24) return `${diffHour}h ago`;
		const diffDay = Math.floor(diffHour / 24);
		if (diffDay < 30) return `${diffDay}d ago`;
		return `${Math.floor(diffDay / 30)}mo ago`;
	}

	function formatFull(dateStr: string): string {
		return new Date(dateStr).toLocaleString();
	}

	const severityBar: Record<string, string> = {
		info: 'bg-blue-400 dark:bg-blue-500',
		warn: 'bg-amber-400 dark:bg-amber-500',
		error: 'bg-red-400 dark:bg-red-500'
	};

	const severityBadge: Record<string, string> = {
		info: 'text-blue-600 dark:text-blue-400',
		warn: 'text-amber-600 dark:text-amber-400',
		error: 'text-red-600 dark:text-red-400'
	};

	const parsedMetadata = $derived.by<Record<string, unknown> | null>(() => {
		if (!entry.metadata || entry.metadata === '{}' || entry.metadata === 'null') return null;
		try {
			const parsed = JSON.parse(entry.metadata);
			if (typeof parsed === 'object' && parsed !== null && Object.keys(parsed).length > 0) {
				return parsed as Record<string, unknown>;
			}
			return null;
		} catch {
			return null;
		}
	});

	const hasMetadata = $derived(parsedMetadata !== null);
</script>

<div
	class="group relative flex gap-3 py-2.5 px-3 rounded-lg transition-colors duration-150 hover:bg-[var(--surface-card-hover)]
		{isNew ? 'animate-fade-in bg-[var(--color-brand-50)] dark:bg-[var(--color-brand-900)]/10' : ''}"
>
	<!-- Severity color bar -->
	<div class="shrink-0 pt-0.5">
		<div class="w-0.5 h-full min-h-[1.5rem] rounded-full {severityBar[entry.severity] ?? severityBar.info} opacity-70"></div>
	</div>

	<!-- Content -->
	<div class="min-w-0 flex-1">
		<!-- Header: source + severity + timestamp -->
		<div class="flex items-center gap-1.5 text-xs leading-none">
			<span class="text-[var(--text-tertiary)]">{$t(`events.source.${entry.source}`)}</span>
			<span class="text-[var(--text-tertiary)]">&middot;</span>
			<span class="font-medium {severityBadge[entry.severity] ?? severityBadge.info}">
				{$t(`events.severity.${entry.severity}`)}
			</span>
			<span class="ml-auto shrink-0 text-[var(--text-tertiary)] tabular-nums" title={formatFull(entry.created_at)}>
				{timeAgo(entry.created_at)}
			</span>
		</div>

		<!-- Message -->
		<p class="mt-1 text-sm text-[var(--text-primary)] leading-relaxed">
			{entry.message}
		</p>

		<!-- Expandable metadata -->
		{#if hasMetadata}
			<button
				type="button"
				class="mt-1 inline-flex items-center gap-1 text-[11px] font-medium text-[var(--text-tertiary)] hover:text-[var(--color-brand-600)] transition-colors"
				onclick={() => { expanded = !expanded; }}
			>
				<svg class="h-2.5 w-2.5 transition-transform duration-150 {expanded ? 'rotate-90' : ''}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
					<path d="m9 18 6-6-6-6" />
				</svg>
				{$t('events.metadata')}
			</button>

			{#if expanded}
				<div class="mt-1.5 rounded-md bg-[var(--surface-page)] border border-[var(--border-primary)] p-2.5 animate-fade-in">
					<dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs">
						{#each Object.entries(parsedMetadata ?? {}) as [key, value]}
							<dt class="font-medium text-[var(--text-tertiary)] whitespace-nowrap">{key}</dt>
							<dd class="text-[var(--text-secondary)] break-all font-mono text-[11px]">{typeof value === 'object' ? JSON.stringify(value) : String(value)}</dd>
						{/each}
					</dl>
				</div>
			{/if}
		{/if}
	</div>
</div>
