<script lang="ts">
	import type { Snippet } from 'svelte';
	import { page } from '$app/stores';
	import { settingsCache } from '$lib/stores/caches';
	import { t } from '$lib/i18n';
	import {
		IconSettings,
		IconDatabase,
		IconShield,
		IconHardDrive,
		IconWifi,
		IconGlobe,
		IconRefresh,
		IconServer
	} from '$lib/components/icons';
	import ForgeHero from '$lib/components/ForgeHero.svelte';

	interface Props { children: Snippet; }
	let { children }: Props = $props();

	// Reactive to the shared settings cache: warm on revisit so the proxy-
	// specific sub-nav items (NPM / Traefik) render correctly on first paint
	// instead of defaulting to npm then snapping, and it updates live when the
	// landing page saves a provider change.
	const proxyProvider = $derived($settingsCache.value?.proxy_provider ?? 'npm');

	$effect(() => {
		settingsCache.refresh();
	});

	type NavGroup = 'main' | 'proxy' | 'system' | 'security';

	interface NavItem {
		href: string;
		labelKey: string;
		icon: string;
		group: NavGroup;
		provider?: 'npm' | 'traefik';
	}

	// Sidebar layout: grouped, with clear separators. Provider-specific items
	// (NPM / Traefik) only appear under "Proxy" when that provider is active.
	const baseItems: NavItem[] = [
		{ href: '/settings',                labelKey: 'settings.general',        icon: 'general',      group: 'main' },
		{ href: '/settings/integrations',   labelKey: 'settings.integrations',   icon: 'integrations', group: 'main' },

		{ href: '/settings/registries',     labelKey: 'settings.registries',     icon: 'registries',   group: 'proxy' },
		{ href: '/settings/npm',            labelKey: 'settings.npm',            icon: 'npm',          group: 'proxy', provider: 'npm' },
		{ href: '/settings/traefik',        labelKey: 'settings.traefik',        icon: 'traefik',      group: 'proxy', provider: 'traefik' },
		{ href: '/settings/dns',            labelKey: 'settings.dns',            icon: 'dns',          group: 'proxy' },

		{ href: '/settings/maintenance',    labelKey: 'settings.maintenance',    icon: 'maintenance',  group: 'system' },
		{ href: '/settings/backup',         labelKey: 'settings.backup',         icon: 'backup',       group: 'system' },

		{ href: '/settings/auth',           labelKey: 'settings.authentication', icon: 'auth',         group: 'security' }
	];

	const navItems = $derived(baseItems.filter((i) => !i.provider || i.provider === proxyProvider));

	// Order of group rendering + headings.
	const groupOrder: { key: NavGroup; labelKey: string }[] = [
		{ key: 'main',     labelKey: 'settings.groupMain' },
		{ key: 'proxy',    labelKey: 'settings.groupProxy' },
		{ key: 'system',   labelKey: 'settings.groupSystem' },
		{ key: 'security', labelKey: 'settings.groupSecurity' }
	];

	const grouped = $derived(groupOrder
		.map((g) => ({ ...g, items: navItems.filter((i) => i.group === g.key) }))
		.filter((g) => g.items.length > 0));

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

	function isActive(href: string): boolean {
		if (href === '/settings') return currentPath === '/settings';
		return currentPath.startsWith(href);
	}
</script>

<div class="mx-auto max-w-5xl">
	<ForgeHero
		eyebrowSuffix={$t('nav.settings').toUpperCase()}
		title={$t('settings.title')}
		size="lg"
	/>

	<div class="flex flex-col gap-6 sm:flex-row">
		<!-- Sub-navigation (grouped) -->
		<nav class="w-full flex-shrink-0 sm:w-56">
			<ul class="flex gap-1 overflow-x-auto sm:flex-col sm:gap-0">
				{#each grouped as group, gIdx}
					{#if gIdx > 0}
						<li class="hidden sm:block" aria-hidden="true">
							<div class="my-2 border-t border-[var(--border-secondary)]"></div>
						</li>
					{/if}
					<li class="hidden sm:block px-3 pt-1 pb-1.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-[var(--text-tertiary)]">
						{$t(group.labelKey)}
					</li>
					{#each group.items as item}
						{@const active = isActive(item.href)}
						<li>
							<a
								href={item.href}
								class="flex items-center gap-2.5 whitespace-nowrap rounded-lg px-3 py-2 text-sm font-medium transition-all duration-150
									{active
										? 'bg-[var(--color-brand-50)] text-[var(--color-brand-700)] shadow-sm'
										: 'text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] hover:text-[var(--text-primary)]'}"
							>
								{#if item.icon === 'general'}
									<IconSettings size={16} class={active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)]'} />
								{:else if item.icon === 'integrations'}
									<IconRefresh size={16} class={active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)]'} />
								{:else if item.icon === 'registries'}
									<IconDatabase size={16} class={active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)]'} />
								{:else if item.icon === 'npm' || item.icon === 'traefik'}
									<IconWifi size={16} class={active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)]'} />
								{:else if item.icon === 'dns'}
									<IconGlobe size={16} class={active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)]'} />
								{:else if item.icon === 'maintenance'}
									<IconServer size={16} class={active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)]'} />
								{:else if item.icon === 'backup'}
									<IconHardDrive size={16} class={active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)]'} />
								{:else if item.icon === 'auth'}
									<IconShield size={16} class={active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)]'} />
								{/if}
								{$t(item.labelKey)}
							</a>
						</li>
					{/each}
				{/each}
			</ul>
		</nav>

		<div class="flex-1 min-w-0">
			{@render children()}
		</div>
	</div>
</div>
