<script lang="ts">
	/**
	 * Shared container panel for workload detail pages (stack, site, and any
	 * future kind that doesn't shard containers by stage). Reads from the
	 * normalized containers index via /api/workloads/{id}/containers — the
	 * single source of truth maintained by the reconciler. Project detail
	 * pages keep their stage-grouped layout in [id]/+page.svelte and don't
	 * use this component.
	 */
	import type { Container } from '$lib/types';
	import * as api from '$lib/api';
	import StatusBadge from '$lib/components/StatusBadge.svelte';
	import EmptyState from '$lib/components/EmptyState.svelte';
	import { t } from '$lib/i18n';
	import { fmt } from '$lib/format/datetime';

	interface Props {
		workloadId: string;
		/** Optional title override; defaults to "Containers". */
		title?: string;
		/** Polling interval in ms; <=0 disables polling. Default 30s. */
		pollIntervalMs?: number;
	}

	const { workloadId, title, pollIntervalMs = 30_000 }: Props = $props();

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

	let abort: AbortController | null = null;
	async function load(): Promise<void> {
		abort?.abort();
		abort = new AbortController();
		try {
			containers = await api.listWorkloadContainers(workloadId, abort.signal);
			error = '';
		} catch (e) {
			if ((e as Error)?.name === 'AbortError') return;
			error = e instanceof Error ? e.message : $t('containers.errLoad');
		} finally {
			loading = false;
		}
	}

	$effect(() => {
		// Reactive on workloadId — re-fetch when the parent navigates between
		// detail pages without unmounting.
		void workloadId;
		loading = true;
		void load();

		if (pollIntervalMs > 0) {
			const tick = setInterval(() => void load(), pollIntervalMs);
			return () => {
				clearInterval(tick);
				abort?.abort();
			};
		}
		return () => abort?.abort();
	});
</script>

<section class="space-y-3">
	<header class="flex items-center justify-between">
		<h3 class="text-sm font-semibold uppercase tracking-wide text-[var(--text-tertiary)]">
			{title ?? $t('containers.col.workload')}
		</h3>
		{#if !loading && containers.length > 0}
			<span class="text-xs text-[var(--text-tertiary)]">
				{containers.length}
			</span>
		{/if}
	</header>

	{#if loading}
		<p class="text-sm text-[var(--text-tertiary)]">{$t('common.loading')}</p>
	{:else if error}
		<div class="rounded-lg border border-[var(--color-danger-light)] bg-[var(--color-danger-light)] p-3">
			<p class="text-sm text-[var(--color-danger)]">{error}</p>
		</div>
	{:else if containers.length === 0}
		<EmptyState
			title={$t('containers.emptyTitle')}
			description={$t('containers.emptyDesc')}
		/>
	{:else}
		<div class="overflow-x-auto rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] shadow-[var(--shadow-sm)]">
			<table class="min-w-full divide-y divide-[var(--border-primary)]">
				<thead class="bg-[var(--surface-card-hover)]">
					<tr>
						<th class="px-4 py-2 text-left text-xs font-medium text-[var(--text-tertiary)] uppercase">{$t('containers.col.role')}</th>
						<th class="px-4 py-2 text-left text-xs font-medium text-[var(--text-tertiary)] uppercase">{$t('containers.col.image')}</th>
						<th class="px-4 py-2 text-left text-xs font-medium text-[var(--text-tertiary)] uppercase">{$t('containers.col.state')}</th>
						<th class="px-4 py-2 text-left text-xs font-medium text-[var(--text-tertiary)] uppercase">{$t('containers.col.subdomain')}</th>
						<th class="px-4 py-2 text-left text-xs font-medium text-[var(--text-tertiary)] uppercase">{$t('containers.col.lastSeen')}</th>
					</tr>
				</thead>
				<tbody class="divide-y divide-[var(--border-secondary)]">
					{#each containers as c (c.id)}
						<tr>
							<td class="px-4 py-2 text-sm text-[var(--text-secondary)]">{c.role || '—'}</td>
							<td class="px-4 py-2 font-mono text-xs text-[var(--text-secondary)] truncate" style="max-width: 280px;">{c.image_ref || '—'}</td>
							<td class="px-4 py-2"><StatusBadge status={c.state} /></td>
							<td class="px-4 py-2 font-mono text-xs text-[var(--text-secondary)]">{c.subdomain || '—'}</td>
							<td class="px-4 py-2 text-xs text-[var(--text-tertiary)]">{c.last_seen_at ? $fmt.relative(c.last_seen_at) : '—'}</td>
						</tr>
					{/each}
				</tbody>
			</table>
		</div>
	{/if}
</section>
