<script lang="ts">
	import { page } from '$app/stores';
	import {
		LayoutDashboard, Users, BarChart3, Key, ListTodo,
		Server, FileText, Network, Settings, TreePine, Globe, BookOpen,
		Sun, Moon, LogOut, RefreshCw, Timer, ChevronDown, Bot
	} from 'lucide-svelte';
	import { sidebar } from '$lib/stores/sidebar.svelte';
	import { theme } from '$lib/stores/theme.svelte';
	import { refresh, INTERVAL_LABELS } from '$lib/stores/refresh.svelte';
	import { auth } from '$lib/stores/auth.svelte';
	import { logoutCookie } from '$lib/api/admin';
	import { navbarExtra } from '$lib/stores/navbar-extra.svelte';

	const navItems = [
		{ href: '/', label: 'Overview', icon: LayoutDashboard },
		{ href: '/tenants', label: 'Tenants', icon: Users },
		{ href: '/usage', label: 'Usage', icon: BarChart3 },
		{ href: '/credentials', label: 'Credentials', icon: Key },
		{ href: '/tasks', label: 'Tasks', icon: ListTodo },
		{ href: '/domains', label: 'Domains', icon: Globe },
		{ href: '/agents', label: 'Agents', icon: Bot },
		{ href: '/skills', label: 'Skills', icon: BookOpen },
		{ href: '/service', label: 'Service', icon: Server },
		{ href: '/logs', label: 'Logs', icon: FileText },
		{ href: '/caddy', label: 'Caddy', icon: Network },
		{ href: '/settings', label: 'Settings', icon: Settings },
	];

	let currentPath = $derived($page.url.pathname);
	let dropdownOpen = $state(false);

	let _tick = $state(0);
	$effect(() => {
		const id = setInterval(() => _tick++, 1000);
		return () => clearInterval(id);
	});

	let displayLastUpdated = $derived.by(() => {
		void _tick;
		const d = refresh.lastUpdated;
		if (!d) return '';
		const now = new Date();
		const diffSec = Math.floor((now.getTime() - d.getTime()) / 1000);
		if (diffSec < 2) return 'just now';
		if (diffSec < 60) return `${diffSec}s ago`;
		const diffMin = Math.floor(diffSec / 60);
		if (diffMin < 60) return `${diffMin}m ago`;
		return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
	});

	function handleSelect(value: string) {
		refresh.setInterval(value as any);
		dropdownOpen = false;
	}

	async function handleLogout() {
		try { await logoutCookie(); } catch {}
		auth.logout();
	}
</script>

<svelte:window onclick={() => { if (dropdownOpen) dropdownOpen = false; }} />

<aside class="sidebar" class:open={sidebar.open}>
	<div class="logo">
		<TreePine size={20} strokeWidth={2.5} />
		<span class="logo-text">TREEHOUSE</span>
		<span class="logo-sub">MC</span>
	</div>
	<nav>
		{#each navItems as item}
			<a
				href={item.href}
				class="nav-item"
				class:active={item.href === '/' ? currentPath === '/' : currentPath.startsWith(item.href)}
				onclick={() => sidebar.close()}
			>
				<item.icon size={16} />
				<span>{item.label}</span>
			</a>
		{/each}
	</nav>
	<div class="sidebar-footer">
		<div class="footer-refresh">
			<span class="last-updated mono">
				{#if refresh.refreshing}<span class="updating-dot"></span>{/if}
				{displayLastUpdated || 'never'}
			</span>
			<div class="refresh-controls">
				<!-- svelte-ignore a11y_click_events_have_key_events -->
				<!-- svelte-ignore a11y_no_static_element_interactions -->
				<div class="interval-wrap" onclick={(e) => e.stopPropagation()}>
					<button class="footer-btn interval-btn" onclick={(e) => { e.stopPropagation(); dropdownOpen = !dropdownOpen; }} title="Auto-refresh interval">
						<Timer size={13} />
						<span class="mono">{refresh.interval === 'off' ? 'Off' : refresh.interval}</span>
						<ChevronDown size={11} />
					</button>
					{#if dropdownOpen}
						<!-- svelte-ignore a11y_click_events_have_key_events -->
						<!-- svelte-ignore a11y_no_static_element_interactions -->
						<div class="interval-dropdown" onclick={(e) => e.stopPropagation()}>
							{#each INTERVAL_LABELS as opt}
								<button
									class="interval-option"
									class:active={refresh.interval === opt.value}
									onclick={() => handleSelect(opt.value)}
								>
									{opt.label}
								</button>
							{/each}
						</div>
					{/if}
				</div>
				<button
					class="footer-btn"
					class:spinning={refresh.refreshing}
					onclick={() => refresh.triggerNow()}
					title="Refresh now"
				>
					<RefreshCw size={14} />
				</button>
			</div>
		</div>
		{#if navbarExtra.snippet}
			<div class="footer-extra">
				{@render navbarExtra.snippet()}
			</div>
		{/if}
		<div class="footer-controls">
			<span class="version mono">v2.0</span>
			<div class="footer-actions">
				<button class="footer-btn" onclick={() => theme.toggle()} title="Toggle theme">
					{#if theme.isDark}<Sun size={15} />{:else}<Moon size={15} />{/if}
				</button>
				<button class="footer-btn" onclick={handleLogout} title="Logout">
					<LogOut size={15} />
				</button>
			</div>
		</div>
	</div>
</aside>

<style>
	.sidebar {
		width: var(--sidebar-width);
		height: 100vh;
		position: fixed;
		left: 0;
		top: 0;
		background: var(--surface-0);
		border-right: 1px solid var(--border);
		display: flex;
		flex-direction: column;
		z-index: 100;
		transition: transform 0.25s var(--ease);
	}
	.logo {
		display: flex;
		align-items: center;
		gap: 8px;
		padding: 16px 18px;
		color: var(--accent);
		border-bottom: 1px solid var(--border-subtle);
	}
	.logo-text {
		font-weight: 700;
		font-size: var(--font-size-sm);
		letter-spacing: 0.12em;
		color: var(--text-bright);
	}
	.logo-sub {
		font-size: var(--font-size-xs);
		font-family: var(--font-mono);
		color: var(--text-muted);
		margin-left: auto;
	}
	nav {
		flex: 1;
		padding: 12px 8px;
		display: flex;
		flex-direction: column;
		gap: 2px;
		overflow-y: auto;
	}
	.nav-item {
		display: flex;
		align-items: center;
		gap: 10px;
		padding: 8px 12px;
		border-radius: var(--radius);
		color: var(--text-dim);
		font-size: var(--font-size-sm);
		font-weight: 500;
		transition: all var(--duration) var(--ease);
		text-decoration: none;
	}
	.nav-item:hover {
		color: var(--text);
		background: var(--surface-2);
	}
	.nav-item.active {
		color: var(--text-bright);
		background: var(--accent-dim);
	}
	.nav-item.active :global(svg) {
		color: var(--accent);
	}
	.sidebar-footer {
		border-top: 1px solid var(--border-subtle);
		display: flex;
		flex-direction: column;
	}
	.footer-refresh {
		padding: 8px 12px;
		border-bottom: 1px solid var(--border-subtle);
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 8px;
	}
	.last-updated {
		font-size: var(--font-size-xs);
		color: var(--text-muted);
		display: flex;
		align-items: center;
		gap: 4px;
		flex: 1;
		min-width: 0;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.updating-dot {
		flex-shrink: 0;
		width: 5px;
		height: 5px;
		border-radius: 50%;
		background: var(--accent);
		animation: pulse 0.8s ease infinite alternate;
	}
	@keyframes pulse { to { opacity: 0.3; } }
	.refresh-controls {
		display: flex;
		align-items: center;
		gap: 2px;
		flex-shrink: 0;
	}
	.interval-wrap { position: relative; }
	.interval-btn {
		display: flex;
		align-items: center;
		gap: 3px;
	}
	.interval-dropdown {
		position: absolute;
		bottom: calc(100% + 4px);
		right: 0;
		background: var(--surface-2);
		border: 1px solid var(--border-strong);
		border-radius: var(--radius);
		padding: 4px;
		z-index: 200;
		display: flex;
		flex-direction: column;
		min-width: 80px;
		animation: fadeIn 0.1s ease;
	}
	@keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } }
	.interval-option {
		padding: 5px 10px;
		background: none;
		border: none;
		color: var(--text-dim);
		cursor: pointer;
		font-size: var(--font-size-sm);
		font-family: var(--font-mono);
		border-radius: var(--radius-sm);
		text-align: left;
		transition: all var(--duration) var(--ease);
	}
	.interval-option:hover { background: var(--surface-3); color: var(--text); }
	.interval-option.active { color: var(--accent); background: var(--accent-dim); }
	.footer-controls {
		padding: 8px 12px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.version {
		font-size: var(--font-size-xs);
		color: var(--text-muted);
		font-family: var(--font-mono);
	}
	.footer-actions { display: flex; align-items: center; gap: 2px; }
	.footer-btn {
		background: none;
		border: none;
		color: var(--text-dim);
		cursor: pointer;
		padding: 6px;
		border-radius: var(--radius-sm);
		transition: all var(--duration) var(--ease);
		display: flex;
		align-items: center;
		gap: 3px;
		font-size: var(--font-size-xs);
	}
	.footer-btn:hover { color: var(--text); background: var(--surface-2); }
	.footer-btn.spinning :global(svg) { animation: spin 0.8s linear infinite; }
	@keyframes spin { to { transform: rotate(360deg); } }
	.footer-extra {
		display: none;
		padding: 8px 12px;
		border-bottom: 1px solid var(--border-subtle);
	}
	@media (max-width: 768px) {
		.footer-extra { display: flex; align-items: center; gap: 6px; }
		.sidebar { transform: translateX(-100%); }
		.sidebar.open { transform: translateX(0); }
	}
</style>
