<!--
  Dashboard summary card: container counts and recent errors.

  Workload-first: pulls running/total counts straight from the global
  containers index instead of fanning out project → stage → instance
  queries the way the legacy implementation did.
-->
<script lang="ts">
	import type { EventLogStats } from '$lib/types';
	import * as api from '$lib/api';
	import { IconServer, IconAlert } from '$lib/components/icons';
	import { t } from '$lib/i18n';

	let runningCount = $state(0);
	let stoppedCount = $state(0);
	let recentErrors = $state(0);
	let loading = $state(true);

	$effect(() => {
		const ac = new AbortController();

		async function load() {
			try {
				const [containers, eventStats] = await Promise.all([
					api.listContainers({}, ac.signal).catch(() => []),
					api.fetchEventLogStats(ac.signal).catch(
						() => ({ info: 0, warn: 0, error: 0, total: 0 }) as EventLogStats
					)
				]);

				if (ac.signal.aborted) return;
				runningCount = containers.filter((c) => c.state === 'running').length;
				stoppedCount = containers.filter((c) => c.state !== 'running').length;
				recentErrors = eventStats.error;
				loading = false;
			} catch {
				if (!ac.signal.aborted) {
					loading = false;
				}
			}
		}

		load();

		return () => ac.abort();
	});
</script>

{#if !loading}
	<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-5 shadow-[var(--shadow-sm)]">
		<h3 class="mb-4 text-sm font-semibold text-[var(--text-primary)]">{$t('systemHealth.title')}</h3>
		<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
			<!-- Containers -->
			<a href="/containers" class="flex items-center gap-3 rounded-lg p-3 transition-colors hover:bg-[var(--surface-card-hover)]">
				<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-50 dark:bg-emerald-950/30 text-emerald-600">
					<IconServer size={18} />
				</div>
				<div>
					<p class="text-xs text-[var(--text-secondary)]">{$t('systemHealth.containers')}</p>
					<p class="text-sm font-semibold text-[var(--text-primary)]">
						<span class="text-emerald-600">{runningCount}</span>
						<span class="text-[var(--text-tertiary)]"> / </span>
						<span class="text-[var(--text-tertiary)]">{stoppedCount}</span>
					</p>
				</div>
			</a>

			<!-- Recent errors -->
			<a href="/events" class="flex items-center gap-3 rounded-lg p-3 transition-colors hover:bg-[var(--surface-card-hover)]">
				<div class="flex h-9 w-9 items-center justify-center rounded-lg {recentErrors > 0 ? 'bg-red-50 dark:bg-red-950/30 text-red-600' : 'bg-gray-50 dark:bg-gray-900/30 text-gray-400'}">
					<IconAlert size={18} />
				</div>
				<div>
					<p class="text-xs text-[var(--text-secondary)]">{$t('systemHealth.recentErrors')}</p>
					<p class="text-sm font-semibold {recentErrors > 0 ? 'text-red-600' : 'text-[var(--text-primary)]'}">{recentErrors}</p>
				</div>
			</a>
		</div>
	</div>
{/if}
