<script lang="ts">
	import { Card, Badge, Spinner, Button } from '$lib/components';
	import { data } from '$lib/stores/data.svelte';
	import { Cpu, MemoryStick, HardDrive, Users, Activity, Clock } from 'lucide-svelte';

	function fmtBytes(mb: number): string {
		if (mb >= 1024) return `${(mb / 1024).toFixed(1)} GB`;
		return `${Math.round(mb)} MB`;
	}

	function fmtGB(gb: number): string {
		return `${gb.toFixed(1)} GB`;
	}

	function fmtNum(n: number): string {
		return n.toLocaleString();
	}

	function fmtSizeFromMb(mb: number): string {
		if (mb >= 1024) return `${(mb / 1024).toFixed(1)} GB`;
		if (mb >= 1) return `${mb.toFixed(1)} MB`;
		return `${Math.round(mb * 1024)} KB`;
	}

	function fmtDuration(ms: number): string {
		const mins = Math.floor(ms / 60000);
		if (mins < 60) return `${mins}m`;
		const hrs = Math.floor(mins / 60);
		const rem = mins % 60;
		return `${hrs}h ${rem}m`;
	}

	function pct(used: number, total: number): number {
		if (total === 0) return 0;
		return Math.round((used / total) * 100);
	}

	function statusColor(status: string): 'emerald' | 'amber' | 'rose' | 'dim' {
		if (status === 'active') return 'emerald';
		if (status === 'suspended') return 'amber';
		if (status === 'archived') return 'rose';
		return 'dim';
	}

	// Color palette for tenant slices in bar charts
	const TENANT_COLORS = [
		'#6366f1', '#8b5cf6', '#a78bfa', '#7c3aed',
		'#22d3ee', '#06b6d4', '#0ea5e9', '#3b82f6',
		'#34d399', '#10b981', '#14b8a6', '#2dd4bf',
		'#fbbf24', '#f59e0b', '#fb923c', '#f97316',
	];

	function tenantColor(idx: number): string {
		return TENANT_COLORS[idx % TENANT_COLORS.length];
	}

	// Computed memory bar segments
	let memSegments = $derived.by(() => {
		if (!data.memory) return [];
		const total = data.memory.host_total_mb;
		if (total === 0) return [];
		const segs: { label: string; mb: number; pct: number; color: string }[] = [];
		segs.push({ label: 'System', mb: data.memory.system_mb, pct: (data.memory.system_mb / total) * 100, color: 'var(--rose)' });
		segs.push({ label: 'NanoClaw', mb: data.memory.nanoclaw_mb, pct: (data.memory.nanoclaw_mb / total) * 100, color: 'var(--amber)' });
		data.memory.tenants.forEach((t, i) => {
			if (t.current_mb > 0) {
				segs.push({ label: t.id, mb: t.current_mb, pct: (t.current_mb / total) * 100, color: tenantColor(i) });
			}
		});
		return segs;
	});

	// Computed disk bar segments
	let diskSegments = $derived.by(() => {
		if (!data.disk) return [];
		const totalMb = data.disk.host_total_gb * 1024;
		if (totalMb === 0) return [];
		const segs: { label: string; mb: number; pct: number; color: string }[] = [];
		let tenantTotal = 0;
		data.disk.tenants.forEach((t, i) => {
			if (t.used_mb > 0) {
				segs.push({ label: t.id, mb: t.used_mb, pct: (t.used_mb / totalMb) * 100, color: tenantColor(i) });
				tenantTotal += t.used_mb;
			}
		});
		// Estimate system disk usage (total used - tenant used)
		const hostUsedMb = data.stats ? data.stats.disk_used_gb * 1024 : 0;
		const systemMb = Math.max(0, hostUsedMb - tenantTotal);
		if (systemMb > 0) {
			segs.unshift({ label: 'System', mb: systemMb, pct: (systemMb / totalMb) * 100, color: 'var(--rose)' });
		}
		return segs;
	});
</script>

{#if !data.initialLoaded}
	<div class="loading-container">
		<Spinner size={28} />
		<span class="dim">Loading system overview...</span>
	</div>
{:else if data.stats}
	<div class="overview">
		<!-- Stat Cards -->
		<div class="stat-grid">
			<div class="stat-card">
				<div class="stat-icon cpu">
					<Cpu size={18} />
				</div>
				<div class="stat-content">
					<span class="stat-label">CPU Load</span>
					<span class="stat-value">{data.stats.load_avg[0].toFixed(2)}</span>
					<span class="stat-sub">{data.stats.load_avg.map(l => l.toFixed(2)).join(' / ')} &middot; {data.stats.cpu_cores} cores</span>
				</div>
			</div>

			<div class="stat-card">
				<div class="stat-icon mem">
					<MemoryStick size={18} />
				</div>
				<div class="stat-content">
					<span class="stat-label">Memory</span>
					<span class="stat-value">{pct(data.stats.mem_used_gb, data.stats.mem_total_gb)}%</span>
					<span class="stat-sub">{fmtGB(data.stats.mem_used_gb)} / {fmtGB(data.stats.mem_total_gb)}</span>
				</div>
			</div>

			<div class="stat-card">
				<div class="stat-icon disk">
					<HardDrive size={18} />
				</div>
				<div class="stat-content">
					<span class="stat-label">Disk</span>
					<span class="stat-value">{pct(data.stats.disk_used_gb, data.stats.disk_total_gb)}%</span>
					<span class="stat-sub">{fmtGB(data.stats.disk_used_gb)} / {fmtGB(data.stats.disk_total_gb)}</span>
				</div>
			</div>

			<div class="stat-card">
				<div class="stat-icon tenants">
					<Users size={18} />
				</div>
				<div class="stat-content">
					<span class="stat-label">Tenants</span>
					<span class="stat-value">{data.stats.tenant_count}</span>
					<span class="stat-sub">
						<span class="svc-dot" class:svc-running={data.stats.service_status === 'running'}></span>
						{data.stats.service_status} &middot; {fmtBytes(data.stats.service_memory_mb)}
					</span>
				</div>
			</div>
		</div>

		<!-- Breakdown Bars -->
		<div class="breakdown-grid">
			{#if data.memory}
				<Card title="Memory Breakdown" compact>
					<div class="bar-info">
						<span class="dim">Total: {fmtBytes(data.memory.host_total_mb)}</span>
						<span class="dim">Used: {fmtBytes(data.memory.host_used_mb)} ({pct(data.memory.host_used_mb, data.memory.host_total_mb)}%)</span>
					</div>
					<div class="stacked-bar">
						{#each memSegments as seg}
							{#if seg.pct > 0.3}
								<div
									class="bar-seg"
									style="width:{seg.pct}%;background:{seg.color}"
									title="{seg.label}: {fmtBytes(seg.mb)}"
								></div>
							{/if}
						{/each}
					</div>
					<div class="bar-legend">
						{#each memSegments as seg}
							<div class="legend-item">
								<span class="legend-dot" style="background:{seg.color}"></span>
								<span class="legend-label">{seg.label}</span>
								<span class="legend-value mono">{fmtBytes(seg.mb)}</span>
							</div>
						{/each}
						<div class="legend-item">
							<span class="legend-dot" style="background:var(--surface-3)"></span>
							<span class="legend-label">Free</span>
							<span class="legend-value mono">{fmtBytes(data.memory.host_free_mb)}</span>
						</div>
					</div>
				</Card>
			{/if}

			{#if data.disk}
				<Card title="Disk Breakdown" compact>
					<div class="bar-info">
						<span class="dim">Total: {fmtGB(data.disk.host_total_gb)}</span>
						{#if data.stats}
							<span class="dim">Used: {fmtGB(data.stats.disk_used_gb)} ({pct(data.stats.disk_used_gb, data.stats.disk_total_gb)}%)</span>
						{/if}
					</div>
					<div class="stacked-bar">
						{#each diskSegments as seg}
							{#if seg.pct > 0.3}
								<div
									class="bar-seg"
									style="width:{seg.pct}%;background:{seg.color}"
									title="{seg.label}: {fmtBytes(seg.mb)}"
								></div>
							{/if}
						{/each}
					</div>
					<div class="bar-legend">
						{#each diskSegments as seg}
							<div class="legend-item">
								<span class="legend-dot" style="background:{seg.color}"></span>
								<span class="legend-label">{seg.label}</span>
								<span class="legend-value mono">{fmtBytes(seg.mb)}</span>
							</div>
						{/each}
						{#if data.stats}
							<div class="legend-item">
								<span class="legend-dot" style="background:var(--surface-3)"></span>
								<span class="legend-label">Free</span>
								<span class="legend-value mono">{fmtGB(data.stats.disk_free_gb)}</span>
							</div>
						{/if}
					</div>
				</Card>
			{/if}
		</div>

		{#if data.stats.db}
			<Card title="Database" compact>
				<div class="db-grid">
					<div class="db-metric">
						<span class="db-label">Main DB</span>
						<span class="db-value mono">{fmtSizeFromMb(data.stats.db.file_mb)}</span>
					</div>
					<div class="db-metric">
						<span class="db-label">WAL</span>
						<span class="db-value mono">{fmtSizeFromMb(data.stats.db.wal_mb)}</span>
					</div>
					<div class="db-metric">
						<span class="db-label">Messages</span>
						<span class="db-value mono">{fmtNum(data.stats.db.messages)}</span>
					</div>
					<div class="db-metric">
						<span class="db-label">Usage Rows</span>
						<span class="db-value mono">{fmtNum(data.stats.db.usage_log)}</span>
					</div>
				</div>
				<div class="db-meta">
					<span class="dim">Chats: {fmtNum(data.stats.db.chats)}</span>
					<span class="dim">Pages: {fmtNum(data.stats.db.page_count)}</span>
					<span class="dim">Free pages: {fmtNum(data.stats.db.freelist_count)}</span>
					<span class="dim">SHM: {fmtNum(data.stats.db.shm_kb)} KB</span>
				</div>
			</Card>
		{/if}

		<!-- Footer info -->
		<div class="footer-info dim">
			<span>{data.stats.hostname} &middot; {data.stats.platform} &middot; {data.stats.cpu_model}</span>
			<span>
				<Clock size={12} />
				Uptime: {Math.floor(data.stats.uptime_hours / 24)}d {Math.round(data.stats.uptime_hours % 24)}h
			</span>
		</div>
	</div>
{/if}

<style>
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 12px;
		min-height: 400px;
	}

	.overview {
		display: flex;
		flex-direction: column;
		gap: 20px;
	}

	/* ─── Stat Cards Grid ─── */
	.stat-grid {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 14px;
	}

	.stat-card {
		display: flex;
		align-items: flex-start;
		gap: 14px;
		padding: 16px 18px;
		background: var(--surface-1);
		border: 1px solid var(--border);
		border-radius: var(--radius-lg);
	}

	.stat-icon {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 36px;
		height: 36px;
		border-radius: var(--radius);
		flex-shrink: 0;
	}
	.stat-icon.cpu { background: var(--accent-dim); color: var(--accent); }
	.stat-icon.mem { background: var(--amber-dim); color: var(--amber); }
	.stat-icon.disk { background: var(--cyan-dim); color: var(--cyan); }
	.stat-icon.tenants { background: var(--emerald-dim); color: var(--emerald); }

	.stat-content {
		display: flex;
		flex-direction: column;
		gap: 2px;
		min-width: 0;
	}

	.stat-label {
		font-size: var(--font-size-xs);
		color: var(--text-dim);
		text-transform: uppercase;
		letter-spacing: 0.06em;
		font-weight: 500;
	}

	.stat-value {
		font-size: var(--font-size-xl);
		font-weight: 700;
		color: var(--text-bright);
		font-family: var(--font-mono);
		line-height: 1.2;
	}

	.stat-sub {
		font-size: var(--font-size-xs);
		color: var(--text-dim);
		font-family: var(--font-mono);
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.svc-dot {
		display: inline-block;
		width: 6px;
		height: 6px;
		border-radius: 50%;
		background: var(--rose);
		vertical-align: middle;
		margin-right: 2px;
	}
	.svc-dot.svc-running {
		background: var(--emerald);
	}

	/* ─── Breakdown Bars ─── */
	.breakdown-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 14px;
	}

	.bar-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 8px;
		font-size: var(--font-size-xs);
	}

	.stacked-bar {
		display: flex;
		height: 20px;
		border-radius: var(--radius-sm);
		overflow: hidden;
		background: var(--surface-3);
		gap: 1px;
	}

	.bar-seg {
		height: 100%;
		min-width: 2px;
		transition: width var(--duration) var(--ease);
	}

	.bar-legend {
		display: flex;
		flex-wrap: wrap;
		gap: 4px 14px;
		margin-top: 10px;
	}

	.db-grid {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
		gap: 12px;
	}

	.db-metric {
		display: flex;
		flex-direction: column;
		gap: 4px;
		padding: 10px 12px;
		border: 1px solid var(--border);
		border-radius: var(--radius);
		background: var(--surface-2);
	}

	.db-label {
		font-size: var(--font-size-xs);
		color: var(--text-dim);
		text-transform: uppercase;
		letter-spacing: 0.06em;
	}

	.db-value {
		font-size: var(--font-size-lg);
		color: var(--text-bright);
	}

	.db-meta {
		display: flex;
		flex-wrap: wrap;
		gap: 10px 14px;
		margin-top: 12px;
		font-size: var(--font-size-sm);
	}

	.legend-item {
		display: flex;
		align-items: center;
		gap: 5px;
		font-size: var(--font-size-xs);
	}

	.legend-dot {
		width: 8px;
		height: 8px;
		border-radius: 2px;
		flex-shrink: 0;
	}

	.legend-label {
		color: var(--text-dim);
	}

	.legend-value {
		color: var(--text);
	}

	/* ─── Tenant Table ─── */
	.tenant-table-wrap {
		overflow-x: auto;
	}

	.tenant-table {
		width: 100%;
		border-collapse: collapse;
		font-size: var(--font-size-sm);
	}

	.tenant-table th {
		text-align: left;
		padding: 8px 12px;
		font-size: var(--font-size-xs);
		font-weight: 500;
		color: var(--text-dim);
		text-transform: uppercase;
		letter-spacing: 0.05em;
		border-bottom: 1px solid var(--border);
		white-space: nowrap;
	}

	.tenant-table td {
		padding: 8px 12px;
		border-bottom: 1px solid var(--border-subtle);
		vertical-align: middle;
	}

	.tenant-table tbody tr:hover {
		background: var(--surface-hover);
	}

	.tenant-table tbody tr:last-child td {
		border-bottom: none;
	}

	.tenant-table .num {
		text-align: right;
	}

	.tenant-link {
		font-weight: 500;
		color: var(--text-bright);
	}
	.tenant-link:hover {
		color: var(--accent);
	}

	.empty-row {
		text-align: center;
		padding: 24px 12px !important;
	}

	/* ─── Footer ─── */
	.footer-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: var(--font-size-xs);
		font-family: var(--font-mono);
		padding: 4px 0;
	}
	.footer-info span {
		display: inline-flex;
		align-items: center;
		gap: 4px;
	}

	/* ─── Responsive ─── */
	@media (max-width: 900px) {
		.stat-grid { grid-template-columns: 1fr; }
		.breakdown-grid { grid-template-columns: 1fr; }
	}

	@media (max-width: 768px) {
		.stat-grid { grid-template-columns: 1fr; }
		.stat-card { padding: 12px 14px; gap: 10px; }
		.stat-icon { width: 30px; height: 30px; }
		.stat-value { font-size: var(--font-size-lg); }
		.tenant-table-wrap { display: none; }
		.mobile-tenant-cards { display: flex; }
		.footer-info { flex-direction: column; align-items: flex-start; gap: 4px; }
	}

	/* ─── Mobile tenant cards ─── */
	.mobile-tenant-cards {
		display: none;
		flex-direction: column;
	}

	.mobile-tenant-card {
		padding: 14px 16px;
		border-bottom: 1px solid var(--border-subtle);
		display: flex;
		flex-direction: column;
		gap: 6px;
		color: inherit;
		text-decoration: none;
		transition: background var(--duration) var(--ease);
	}

	.mobile-tenant-card:hover {
		background: var(--surface-hover);
	}

	.mobile-tenant-card:last-child {
		border-bottom: none;
	}

	.mobile-tenant-top {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 8px;
		flex-wrap: wrap;
	}

	.mobile-tenant-name {
		font-weight: 600;
		font-size: var(--font-size-sm);
		color: var(--text-bright);
	}

	.mobile-tenant-badges {
		display: flex;
		gap: 4px;
		flex-shrink: 0;
	}

	.mobile-tenant-stats {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
		gap: 4px 8px;
		font-size: var(--font-size-xs);
	}

	.mobile-tenant-stat {
		display: flex;
		flex-direction: column;
		gap: 1px;
	}

	.mobile-stat-key {
		color: var(--text-muted);
		font-size: 10px;
		text-transform: uppercase;
		letter-spacing: 0.05em;
	}

	.mobile-stat-val {
		color: var(--text);
		font-family: var(--font-mono);
	}

	.mobile-empty {
		padding: 24px;
		text-align: center;
		font-size: var(--font-size-sm);
	}
</style>
