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

	let slug = $derived(page.params.slug ?? '');
	// Read the layout's app store instead of re-fetching. The layout
	// already drives the historical-slug redirect, so we don't repeat
	// that here either.
	const ctx = getContext<AppContext>(APP_CTX_KEY);
	const appStore = ctx?.app;
	let appName = $derived($appStore?.name ?? slug);
	let queues = $state<QueueSummary[]>([]);
	let loading = $state(false);
	let error = $state<string | null>(null);
	/// F-U-013: queue depths change continuously. The page used to be a
	/// page-load snapshot with no way to update without a hard refresh.
	let autoRefresh = $state(false);
	let autoRefreshHandle: ReturnType<typeof setInterval> | null = null;

	async function loadQueues() {
		loading = true;
		error = null;
		try {
			queues = await api.queues.list(slug);
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		} finally {
			loading = false;
		}
	}

	function setAutoRefresh(on: boolean) {
		autoRefresh = on;
		if (autoRefreshHandle) {
			clearInterval(autoRefreshHandle);
			autoRefreshHandle = null;
		}
		if (on) {
			autoRefreshHandle = setInterval(() => {
				void loadQueues();
			}, 5000);
		}
	}

	onDestroy(() => {
		if (autoRefreshHandle) clearInterval(autoRefreshHandle);
	});

	$effect(() => {
		void slug;
		void loadQueues();
	});
</script>

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

<header class="panel-head">
	<h2>Queues</h2>
	<p class="subtle">
		Per-app durable queues. Producers call <code>queue::enqueue(name, msg)</code>;
		consumers register a <code>queue:receive</code> trigger. v1.1.9.
	</p>
	<!-- F-U-013: refresh + auto-refresh toggle. -->
	<div class="toolbar">
		<button type="button" class="secondary" onclick={() => loadQueues()} disabled={loading}>
			{loading ? 'Refreshing…' : 'Refresh'}
		</button>
		<label class="auto-refresh">
			<input
				type="checkbox"
				checked={autoRefresh}
				onchange={(e) => setAutoRefresh((e.currentTarget as HTMLInputElement).checked)}
			/>
			Auto-refresh every 5s
		</label>
	</div>
</header>

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

{#if loading && queues.length === 0}
	<p class="muted">Loading…</p>
{:else if queues.length === 0}
	<p class="muted" data-testid="queues-empty-state">
		No queues in this app yet. A queue is created implicitly the first time a
		message is enqueued. Register a <code>queue:receive</code> trigger from the
		Triggers tab to consume messages.
	</p>
{:else}
	<table class="queues">
		<thead>
			<tr>
				<th>Queue</th>
				<th class="num">Total</th>
				<th class="num">Pending</th>
				<th class="num">Claimed</th>
				<th></th>
			</tr>
		</thead>
		<tbody>
			{#each queues as q (q.queue_name)}
				<tr>
					<td><code>{q.queue_name}</code></td>
					<td class="num">{q.total}</td>
					<td class="num">{q.pending}</td>
					<td class="num">{q.claimed}</td>
					<td>
						<a href="{base}/apps/{slug}/queues/{encodeURIComponent(q.queue_name)}">
							drilldown →
						</a>
					</td>
				</tr>
			{/each}
		</tbody>
	</table>
{/if}

<style>
	.panel-head {
		margin-bottom: 1rem;
	}
	h2 {
		margin: 0.25rem 0;
		font-size: 1.125rem;
	}
	.subtle {
		color: var(--text-muted);
		font-size: 0.875rem;
	}
	.toolbar {
		display: flex;
		gap: 0.75rem;
		align-items: center;
		margin-top: 0.75rem;
	}
	.auto-refresh {
		display: inline-flex;
		gap: 0.4rem;
		align-items: center;
		font-size: 0.875rem;
		color: var(--text-muted);
	}
	button.secondary {
		background: transparent;
		color: var(--text-muted);
		border: 1px solid var(--border);
		padding: 0.4rem 0.85rem;
		border-radius: var(--radius-md);
		cursor: pointer;
		font-size: 0.85rem;
	}
	button.secondary:hover:not(:disabled) {
		background: var(--bg-elevated);
		color: var(--text-primary);
	}
	button.secondary:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}
	.error {
		color: var(--color-danger);
	}
	.muted {
		color: var(--text-muted);
	}
	table.queues {
		width: 100%;
		border-collapse: collapse;
	}
	table.queues th,
	table.queues td {
		text-align: left;
		padding: 0.5rem;
		border-bottom: 1px solid var(--border);
	}
	.num {
		text-align: right;
		font-variant-numeric: tabular-nums;
	}
</style>
