<script lang="ts">
	import { base } from '$app/paths';
	import { page } from '$app/state';
	import { getContext } from 'svelte';
	import { api, ApiError, type QueueDetail } from '$lib/api';
	import { APP_CTX_KEY, type AppContext } from '../../+layout.svelte';

	let slug = $derived(page.params.slug ?? '');
	let name = $derived(page.params.name ?? '');
	const ctx = getContext<AppContext>(APP_CTX_KEY);
	const appStore = ctx?.app;
	let appName = $derived($appStore?.name ?? slug);
	let detail = $state<QueueDetail | null>(null);
	let loading = $state(false);
	let error = $state<string | null>(null);

	// The parent layout owns the historical-slug redirect — this page
	// just fetches its queue detail.
	async function load() {
		loading = true;
		error = null;
		try {
			detail = await api.queues.get(slug, name);
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		} finally {
			loading = false;
		}
	}

	$effect(() => {
		void slug;
		void name;
		void load();
	});

	function fmtTime(iso: string | null): string {
		return iso ? new Date(iso).toLocaleString() : 'never';
	}
</script>

<svelte:head>
	<title>{name} — Queues — {appName} — PiCloud</title>
</svelte:head>

<header class="panel-head">
	<a class="back" href="{base}/apps/{slug}/queues">← All queues</a>
	<h2>Queue: <code>{name}</code></h2>
</header>

{#if error}
	<p class="error">{error}</p>
{/if}

{#if loading && !detail}
	<p class="muted">Loading…</p>
{:else if detail}
	<section>
		<h2>Depth</h2>
		<dl class="kv">
			<dt>Total</dt>
			<dd>{detail.total}</dd>
			<dt>Pending</dt>
			<dd>{detail.pending}</dd>
			<dt>Claimed</dt>
			<dd>{detail.claimed}</dd>
		</dl>
	</section>

	<section>
		<h2>Consumer</h2>
		{#if detail.consumer}
			<dl class="kv">
				<dt>Script</dt>
				<dd>
					<a href="{base}/scripts/{detail.consumer.script_id}">
						{detail.consumer.script_name}
					</a>
				</dd>
				<dt>Visibility timeout</dt>
				<dd>{detail.consumer.visibility_timeout_secs}s</dd>
				<dt>Last fired</dt>
				<dd>{fmtTime(detail.consumer.last_fired_at)}</dd>
				<dt>Trigger ID</dt>
				<dd><code>{detail.consumer.trigger_id}</code></dd>
			</dl>
		{:else}
			<p class="muted">
				No <code>queue:receive</code> trigger registered for this queue. Messages
				enqueued here will accumulate without a consumer. Register one in the
				Triggers tab of the parent app page.
			</p>
		{/if}
	</section>
{/if}

<style>
	.panel-head {
		margin-bottom: 1rem;
	}
	.back {
		font-size: 0.875rem;
		color: var(--color-link);
		text-decoration: none;
	}
	.back:hover {
		text-decoration: underline;
	}
	h2 {
		margin: 0.25rem 0;
		font-size: 1.125rem;
	}
	section {
		margin: 1rem 0;
	}
	.kv {
		display: grid;
		grid-template-columns: max-content 1fr;
		gap: 0.25rem 1rem;
	}
	dt {
		color: var(--text-muted);
	}
	dd {
		margin: 0;
	}
	.error {
		color: var(--color-danger);
	}
	.muted {
		color: var(--color-muted);
	}
</style>
