<script lang="ts">
	import { Card, Button, Spinner } from '$lib/components';
	import { data } from '$lib/stores/data.svelte';
	import { RefreshCw } from 'lucide-svelte';
	import { highlightLogs } from '$lib/highlight';

	let logsLoading = $state(false);

	let logsEl: HTMLPreElement | undefined = $state();

	async function handleRefreshLogs() {
		logsLoading = true;
		try {
			await data.refetchLogs();
			requestAnimationFrame(() => {
				if (logsEl) logsEl.scrollTop = logsEl.scrollHeight;
			});
		} finally {
			logsLoading = false;
		}
	}
</script>

<div class="page">
	{#if !data.initialLoaded}
		<div class="center"><Spinner /></div>
	{:else}
		<Card title="Service Logs">
			{#snippet actions()}
				<Button size="sm" variant="ghost" loading={logsLoading} onclick={handleRefreshLogs}>
					<RefreshCw size={13} />
					Refresh
				</Button>
			{/snippet}
			<div class="logs-container">
				<pre class="logs" bind:this={logsEl}>{#if data.serviceLogs}{@html highlightLogs(data.serviceLogs)}{:else}No logs available{/if}</pre>
			</div>
		</Card>
	{/if}
</div>

<style>
	.page {
		display: flex;
		flex-direction: column;
		gap: 20px;
	}
	.center {
		display: flex;
		justify-content: center;
		padding: 60px 0;
	}
	.logs-container {
		margin-top: 4px;
		min-width: 0;
		overflow: hidden;
	}
	.logs {
		background: var(--surface-0);
		border: 1px solid var(--border);
		border-radius: var(--radius);
		padding: 12px;
		font-family: var(--font-mono);
		font-size: 12px;
		line-height: 1.5;
		color: var(--text-dim);
		max-height: 500px;
		overflow-y: auto;
		overflow-x: auto;
		white-space: pre;
		margin: 0;
		max-width: 100%;
	}

	@media (max-width: 768px) {
		.logs {
			font-size: 11px;
			padding: 10px;
			white-space: pre-wrap;
			word-break: break-all;
		}
	}

	/* Log syntax highlighting */
	.logs :global(.hl-date) { color: var(--text-muted); }
	.logs :global(.hl-host) { color: var(--text-dim); }
	.logs :global(.hl-tag) { color: var(--cyan); }
	.logs :global(.hl-err) { color: var(--rose); font-weight: 600; }
	.logs :global(.hl-warn) { color: var(--amber); }
	.logs :global(.hl-info) { color: var(--emerald); }
	.logs :global(.hl-str) { color: var(--amber); }
	.logs :global(.hl-num) { color: var(--accent); }
	.logs :global(.hl-path) { color: var(--text); }
</style>
