<!--
  Task 5: Instance card with inline status badges, icon action buttons, improved layout.
-->
<script lang="ts">
	import type { Instance } from '$lib/types';
	import StatusBadge from './StatusBadge.svelte';
	import ContainerStats from './ContainerStats.svelte';
	import ContainerLogs from './ContainerLogs.svelte';
	import ConfirmDialog from './ConfirmDialog.svelte';
	import { IconPlay, IconStop, IconRestart, IconTrash, IconExternalLink, IconEvents } from '$lib/components/icons';
	import { t } from '$lib/i18n';
	import { fmt } from '$lib/format/datetime';
	import * as api from '$lib/api';

	interface Props {
		instance: Instance;
		projectId: string;
		domain?: string;
		onchange?: () => void;
	}

	const { instance, projectId, domain = '', onchange }: Props = $props();

	let loading = $state(false);
	let error = $state('');
	let confirmAction = $state<'stop' | 'restart' | 'remove' | null>(null);
	let showLogs = $state(false);

	const subdomainUrl = $derived(
		instance.subdomain && domain
			? `https://${instance.subdomain}.${domain}`
			: instance.subdomain ? `https://${instance.subdomain}` : ''
	);

	const timeSinceCreated = $derived($fmt.relative(instance.created_at));

	async function handleAction(action: 'stop' | 'start' | 'restart' | 'remove') {
		loading = true;
		error = '';
		confirmAction = null;
		try {
			switch (action) {
				case 'stop':
					await api.stopInstance(projectId, instance.stage_id, instance.id);
					break;
				case 'start':
					await api.startInstance(projectId, instance.stage_id, instance.id);
					break;
				case 'restart':
					await api.restartInstance(projectId, instance.stage_id, instance.id);
					break;
				case 'remove':
					await api.removeInstance(projectId, instance.stage_id, instance.id);
					break;
			}
			onchange?.();
		} catch (e) {
			error = e instanceof Error ? e.message : $t('instance.actionFailed');
		} finally {
			loading = false;
		}
	}

	function requestConfirm(action: 'stop' | 'restart' | 'remove') {
		confirmAction = action;
	}
</script>

<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-4 shadow-[var(--shadow-sm)] transition-all duration-200 hover:shadow-[var(--shadow-md)]">
	<div class="flex items-start justify-between">
		<div class="min-w-0 flex-1">
			<div class="flex items-center gap-2">
				<span class="truncate font-mono text-sm font-medium text-[var(--text-primary)]">
					{instance.image_tag}
				</span>
				<StatusBadge status={instance.status} size="sm" />
			</div>

			{#if subdomainUrl}
				<a
					href={subdomainUrl}
					target="_blank"
					rel="noopener noreferrer"
					class="mt-1.5 inline-flex items-center gap-1 text-xs text-[var(--text-link)] hover:text-[var(--text-link-hover)] transition-colors"
				>
					{instance.subdomain}
					<IconExternalLink size={12} />
				</a>
			{/if}

			<div class="mt-1.5 flex items-center gap-3 text-xs text-[var(--text-tertiary)]">
				<span class="rounded bg-[var(--surface-card-hover)] px-1.5 py-0.5 font-mono">:{instance.port}</span>
				<span>{timeSinceCreated}</span>
			</div>
		</div>

		<!-- Action buttons -->
		<div class="ml-3 flex items-center gap-1">
			{#if instance.status === 'running'}
				<button
					type="button"
					class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-amber-50 hover:text-amber-600 disabled:opacity-50 transition-all duration-150 active:animate-press"
					title={$t('common.stop')}
					disabled={loading}
					onclick={() => requestConfirm('stop')}
				>
					<IconStop size={16} />
				</button>
				<button
					type="button"
					class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-blue-50 hover:text-blue-600 disabled:opacity-50 transition-all duration-150 active:animate-press"
					title={$t('common.restart')}
					disabled={loading}
					onclick={() => requestConfirm('restart')}
				>
					<IconRestart size={16} />
				</button>
			{:else if instance.status === 'stopped'}
				<button
					type="button"
					class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-emerald-50 hover:text-emerald-600 disabled:opacity-50 transition-all duration-150 active:animate-press"
					title={$t('common.start')}
					disabled={loading}
					onclick={() => handleAction('start')}
				>
					<IconPlay size={16} />
				</button>
			{/if}
			<button
				type="button"
				class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300 transition-all duration-150"
				title={$t('logs.title')}
				onclick={() => { showLogs = !showLogs; }}
			>
				<IconEvents size={16} />
			</button>
			<button
				type="button"
				class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-red-50 hover:text-red-600 disabled:opacity-50 transition-all duration-150 active:animate-press"
				title={$t('common.remove')}
				disabled={loading}
				onclick={() => requestConfirm('remove')}
			>
				<IconTrash size={16} />
			</button>
		</div>
	</div>

	{#if instance.status === 'running'}
		<ContainerStats source={{ kind: 'instance', projectId, stageId: instance.stage_id, instanceId: instance.id }} />
	{/if}

	{#if showLogs}
		<div class="mt-2">
			<ContainerLogs
				source={{ kind: 'instance', projectId, stageId: instance.stage_id, instanceId: instance.id }}
				onclose={() => { showLogs = false; }}
			/>
		</div>
	{/if}

	{#if error}
		<p class="mt-2 text-xs text-[var(--color-danger)]">{error}</p>
	{/if}
</div>

<ConfirmDialog
	open={confirmAction !== null}
	title={confirmAction ? $t(`confirm.${confirmAction}Instance`) : ''}
	message={confirmAction ? $t(`instance.${confirmAction}Confirm`) : ''}
	confirmLabel={confirmAction ? $t(`confirm.${confirmAction}Action`) : ''}
	confirmVariant={confirmAction === 'remove' ? 'danger' : 'primary'}
	onconfirm={() => { if (confirmAction) handleAction(confirmAction); }}
	oncancel={() => { confirmAction = null; }}
/>
