<script lang="ts">
	import { Card, Badge, Spinner } from '$lib/components';
	import { getAgentContainers } from '$lib/api/admin';
	import { Bot } from 'lucide-svelte';
	import { onMount } from 'svelte';

	type Container = { id: string; name: string; status: string; tenant: string; agent_status: string };

	let containers = $state<Container[]>([]);
	let loading = $state(true);
	let error = $state<string | null>(null);

	async function load() {
		try {
			const res = await getAgentContainers();
			containers = res;
		} catch (e: any) {
			error = e.message || 'Failed to load agents';
		} finally {
			loading = false;
		}
	}

	onMount(load);
</script>

<div class="page">
	<Card title="Active Agents">
		{#if loading}
			<div class="center"><Spinner /></div>
		{:else if error}
			<p class="error">{error}</p>
		{:else if containers.length === 0}
			<div class="empty">
				<Bot size={32} strokeWidth={1.5} />
				<p>No agent containers running</p>
			</div>
		{:else}
			<div class="table-wrap">
				<table>
					<thead>
						<tr>
							<th>TENANT</th>
							<th>CONTAINER</th>
							<th>CONTAINER STATUS</th>
							<th>AGENT</th>
						</tr>
					</thead>
					<tbody>
						{#each containers as c (c.id)}
							<tr>
								<td class="mono dim">{c.tenant}</td>
								<td class="mono">{c.name}</td>
								<td class="mono dim">{c.status}</td>
								<td>
									{#if c.agent_status === 'WORKING'}
										<Badge color="emerald">WORKING</Badge>
									{:else if c.agent_status === 'IDLE'}
										<Badge color="dim">IDLE</Badge>
									{:else}
										<Badge color="amber">{c.agent_status}</Badge>
									{/if}
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		{/if}
	</Card>
</div>

<style>
	.page { display: flex; flex-direction: column; gap: 20px; }
	.center { display: flex; justify-content: center; padding: 60px 0; }
	.empty {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 12px;
		padding: 48px 0;
		color: var(--text-muted);
		font-size: var(--font-size-sm);
	}
	.error { color: var(--rose); font-size: var(--font-size-sm); padding: 16px; }
	.table-wrap { overflow-x: auto; }
	table { width: 100%; border-collapse: collapse; }
	th {
		text-align: left;
		padding: 8px 12px;
		font-size: var(--font-size-xs);
		font-weight: 600;
		color: var(--text-dim);
		text-transform: uppercase;
		letter-spacing: 0.05em;
		border-bottom: 1px solid var(--border);
		white-space: nowrap;
	}
	td {
		padding: 10px 12px;
		border-bottom: 1px solid var(--border-subtle);
		font-size: var(--font-size-sm);
	}
	tr:hover td { background: var(--surface-hover); }
	.mono { font-family: var(--font-mono); }
	.dim { color: var(--text-dim); }
</style>
