/** Small component showing running instances for a workspace. */

import { useEffect, useState } from "react";
import { listWorkspaceInstances } from "../../../api/workspace-instances";
import type { ToolInstance } from "../../../api/sessions";

interface WorkspaceInstanceChipsProps {
	workspaceId: string;
}

export function WorkspaceInstanceChips({
	workspaceId,
}: WorkspaceInstanceChipsProps) {
	const [instances, setInstances] = useState<ToolInstance[]>([]);
	const [loading, setLoading] = useState(true);

	useEffect(() => {
		const load = async () => {
			try {
				const data = await listWorkspaceInstances(workspaceId);
				setInstances(data);
			} catch {
				// ignore
			} finally {
				setLoading(false);
			}
		};
		void load();
	}, [workspaceId]);

	if (loading) return <span className="muted">...</span>;
	if (instances.length === 0) return null;

	return (
		<div className="instance-chips">
			{instances.map((inst) => (
				<span
					key={inst.id}
					className={`instance-chip ${inst.status}`}
					title={inst.display_name}
				>
					{inst.display_name}
					{inst.status === "running" && inst.url && (
						<a
							href={inst.url}
							target={`instance-${inst.id}`}
							rel="noreferrer"
							onClick={(e) => e.stopPropagation()}
						>
							↗
						</a>
					)}
				</span>
			))}
		</div>
	);
}
