<script>
	import { page } from '$app/state';
	import {
		LayoutDashboard,
		MessageSquare,
		BarChart2,
		Settings,
		LogOut,
		Bell,
		Search,
		Menu,
		X,
		TrendingUp,
		ChevronLeft,
		ChevronRight,
		Moon,
		Sun,
		UserRound,
		User,
		CreditCard,
		HelpCircle,
		PieChart,
		Users
	} from 'lucide-svelte';
	import { goto } from '$app/navigation';
	import logoWhite from '$lib/assets/images/nettown_white_logo.svg';
	import logoBlack from '$lib/assets/images/nettown_black_logo.svg.svg';
	import { theme, toggleTheme } from '$lib/core/stores/theme';
	import { auth } from '$lib/core/stores/auth';
	import { onMount } from 'svelte';

	let { children } = $props();

	/** Iniciais para o avatar a partir do nome do usuário. */
	function getInitials(name) {
		const parts = (name ?? '').trim().split(/\s+/).filter(Boolean);
		if (parts.length === 0) return 'NT';
		return parts
			.slice(0, 2)
			.map((p) => p[0].toUpperCase())
			.join('');
	}
	let isMobileMenuOpen = $state(false);
	let isSidebarCollapsed = $state(false);
	let currentTheme = $state('light');
	let isUserMenuOpen = $state(false);

	onMount(() => {
		theme.subscribe((val) => {
			currentTheme = val;
		});

		// Guard de sessão: reidrata o perfil via /v1/me. Sem sessão válida,
		// redireciona ao login. (Um 401 em qualquer chamada já limpa o token
		// e redireciona via client HTTP.)
		auth.loadMe().then((profile) => {
			if (!profile) goto('/login');
		});
	});

	const navItems = [
		{ name: 'Dashboard Executivo', href: '/dashboard/executive', icon: PieChart, adminOnly: true },
		{ name: 'Visão Geral', href: '/dashboard', icon: LayoutDashboard },
		{ name: 'Interações', href: '/dashboard/interactions', icon: MessageSquare },
		{ name: 'Análise de Sentimento', href: '/dashboard/analytics', icon: BarChart2 },
		{ name: 'Personas', href: '/dashboard/personas', icon: UserRound },
		{ name: 'Evolução', href: '/dashboard/evolucao', icon: TrendingUp },
		{ name: 'Agentes', href: '/dashboard/operators', icon: Users },
		{ name: 'Configurações', href: '/dashboard/settings', icon: Settings }
	];

	// Itens com `adminOnly` só aparecem para usuários com papel admin.
	const visibleNavItems = $derived(
		navItems.filter((item) => !item.adminOnly || $auth.user?.user_role === 'admin')
	);

	function handleLogout() {
		auth.logout();
		goto('/login');
	}

	function toggleMobileMenu() {
		isMobileMenuOpen = !isMobileMenuOpen;
	}

	function toggleSidebar() {
		isSidebarCollapsed = !isSidebarCollapsed;
	}

	function isNavItemActive(href) {
		const currentPath = page.url.pathname;
		if (href === '/dashboard') {
			return currentPath === '/dashboard';
		}
		return currentPath === href || currentPath.startsWith(`${href}/`);
	}

	function toggleUserMenu() {
		isUserMenuOpen = !isUserMenuOpen;
	}

	function closeUserMenu() {
		isUserMenuOpen = false;
	}
</script>

<div
	class="flex h-screen w-screen overflow-hidden bg-slate-50 font-sans text-slate-900 transition-colors duration-200 dark:bg-[#0f172a] dark:text-slate-300"
>
	<!-- Mobile Sidebar Overlay -->
	{#if isMobileMenuOpen}
		<div
			class="fixed inset-0 z-40 bg-slate-950/80 lg:hidden"
			onclick={toggleMobileMenu}
			onkeydown={(e) => e.key === 'Escape' && toggleMobileMenu()}
			tabindex="0"
			role="button"
			aria-label="Fechar menu"
		></div>
	{/if}

	<!-- User Menu Overlay -->
	{#if isUserMenuOpen}
		<div
			class="fixed inset-0 z-40"
			onclick={() => (isUserMenuOpen = false)}
			onkeydown={(e) => e.key === 'Escape' && (isUserMenuOpen = false)}
			tabindex="0"
			role="button"
			aria-label="Fechar menu"
		></div>
	{/if}

	<!-- Sidebar -->
	<aside
		class="fixed inset-y-0 left-0 z-50 flex h-full flex-col border-r border-slate-200 bg-white transition-all duration-300 ease-in-out lg:static dark:border-slate-800 dark:bg-[#1e293b] {isSidebarCollapsed
			? 'w-20'
			: 'w-64'} {isMobileMenuOpen
			? 'translate-x-0'
			: '-translate-x-full lg:translate-x-0'} shrink-0 shadow-sm dark:shadow-none"
	>
		<div
			class="flex h-16 shrink-0 items-center justify-between border-b border-slate-200 px-4 dark:border-slate-800"
		>
			<div class="flex items-center gap-2 overflow-hidden text-indigo-600 dark:text-indigo-400">
				<div
					class="flex h-6 shrink-0 items-center {isSidebarCollapsed
						? 'w-8 justify-center'
						: 'w-auto'}"
				>
					{#if isSidebarCollapsed}
						<TrendingUp size={24} strokeWidth={2.5} class="text-indigo-600 dark:text-indigo-500" />
					{:else}
						<img
							src={currentTheme === 'dark' ? logoWhite : logoBlack}
							alt="NetTown Analytics"
							class="h-full w-auto"
						/>
					{/if}
				</div>
			</div>

			<button
				class="hidden shrink-0 items-center justify-center rounded-lg p-1.5 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-700 lg:flex dark:hover:bg-slate-800 dark:hover:text-white"
				onclick={toggleSidebar}
			>
				{#if isSidebarCollapsed}
					<ChevronRight size={18} />
				{:else}
					<ChevronLeft size={18} />
				{/if}
			</button>

			<button
				class="shrink-0 p-1 text-slate-400 hover:text-slate-700 lg:hidden dark:hover:text-white"
				onclick={toggleMobileMenu}
			>
				<X size={20} />
			</button>
		</div>

		<div
			class="flex flex-1 flex-col gap-2 overflow-x-hidden overflow-y-auto py-6 {isSidebarCollapsed
				? 'px-2'
				: 'px-4'}"
		>
			<div
				class="mb-2 px-2 text-xs font-semibold tracking-wider whitespace-nowrap text-slate-500 uppercase {isSidebarCollapsed
					? 'text-center text-[10px]'
					: ''}"
			>
				{isSidebarCollapsed ? 'Menu' : 'Menu Principal'}
			</div>
			{#each visibleNavItems as item}
				{@const Icon = item.icon}
				{@const isActive = isNavItemActive(item.href)}
				<a
					href={item.href}
					title={isSidebarCollapsed ? item.name : ''}
					class="flex items-center gap-3 rounded-lg py-2.5 transition-colors {isActive
						? 'bg-indigo-50 font-medium text-indigo-700 dark:bg-indigo-500/10 dark:text-indigo-400'
						: 'text-slate-600 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-slate-200'} {isSidebarCollapsed
						? 'justify-center px-0'
						: 'px-3'}"
					onclick={() => (isMobileMenuOpen = false)}
				>
					<Icon
						size={isSidebarCollapsed ? 22 : 18}
						strokeWidth={isActive ? 2.5 : 2}
						class="shrink-0"
					/>
					{#if !isSidebarCollapsed}
						<span class="truncate">{item.name}</span>
					{/if}
				</a>
			{/each}
		</div>

		<div class="shrink-0 border-t border-slate-200 p-4 dark:border-slate-800">
			<button
				onclick={handleLogout}
				title={isSidebarCollapsed ? 'Sair' : ''}
				class="flex w-full items-center gap-3 rounded-lg py-2.5 text-slate-600 transition-colors hover:bg-red-50 hover:text-red-600 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-red-400 {isSidebarCollapsed
					? 'justify-center px-0'
					: 'px-3'}"
			>
				<LogOut size={18} class="shrink-0" />
				{#if !isSidebarCollapsed}
					<span>Sair</span>
				{/if}
			</button>
		</div>
	</aside>

	<!-- Main Wrapper -->
	<div class="relative flex h-full min-w-0 flex-1 flex-col overflow-hidden">
		<!-- Top Header -->
		<header
			class="flex h-16 w-full shrink-0 items-center justify-between border-b border-slate-200 bg-white/95 px-4 backdrop-blur-sm transition-colors duration-200 lg:px-8 dark:border-slate-800 dark:bg-[#1e293b]/95 {isUserMenuOpen
				? 'relative z-50'
				: 'z-30'}"
		>
			<div class="flex items-center gap-4">
				<button
					class="text-slate-400 hover:text-slate-700 lg:hidden dark:hover:text-white"
					onclick={toggleMobileMenu}
				>
					<Menu size={24} />
				</button>
				<div class="relative hidden items-center sm:flex">
					<Search size={18} class="absolute left-3 text-slate-400 dark:text-slate-500" />
					<input
						type="text"
						placeholder="Buscar cliente, número..."
						class="w-64 rounded-lg border border-transparent bg-slate-100 py-1.5 pr-4 pl-10 text-sm text-slate-900 placeholder-slate-500 transition-all focus:border-indigo-500 focus:bg-white focus:ring-1 focus:ring-indigo-500 focus:outline-none dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200"
					/>
				</div>
			</div>

			<div class="flex items-center gap-4">
				<!-- Theme Toggle -->
				<button
					onclick={toggleTheme}
					class="relative rounded-lg p-2 text-slate-400 transition-colors hover:bg-indigo-50 hover:text-indigo-600 dark:hover:bg-slate-800 dark:hover:text-indigo-400"
					title={currentTheme === 'dark' ? 'Mudar para modo claro' : 'Mudar para modo escuro'}
				>
					{#if currentTheme === 'dark'}
						<Sun size={20} />
					{:else}
						<Moon size={20} />
					{/if}
				</button>

				<button
					class="relative rounded-full p-2 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-700 dark:hover:bg-slate-800 dark:hover:text-white"
				>
					<Bell size={20} />
					<span
						class="absolute top-1.5 right-1.5 h-2 w-2 rounded-full border-2 border-white bg-red-500 dark:border-[#1e293b]"
					></span>
				</button>
				<div class="mx-1 h-8 w-px bg-slate-200 dark:bg-slate-700"></div>
				<div class="relative flex items-center gap-3">
					<div class="hidden text-right sm:block">
						<div class="text-sm font-medium text-slate-900 dark:text-white">
							{$auth.user?.user_name ?? 'Usuário'}
						</div>
						<div class="text-xs text-slate-500 capitalize">{$auth.user?.user_role ?? ''}</div>
					</div>
					<div class="relative">
						<button
							onclick={toggleUserMenu}
							class="flex h-9 w-9 items-center justify-center rounded-full bg-indigo-600 text-sm font-bold text-white shadow-sm shadow-indigo-900/20 transition-colors hover:bg-indigo-700"
							title="Menu do usuário"
						>
							{getInitials($auth.user?.user_name)}
						</button>

						<!-- User Dropdown Menu -->
						{#if isUserMenuOpen}
							<div
								class="absolute right-0 z-50 mt-2 w-56 rounded-lg border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-800 dark:bg-[#1e293b]"
							>
								<div class="border-b border-slate-200 px-4 py-3 dark:border-slate-800">
									<p class="text-sm font-medium text-slate-900 dark:text-white">
										{$auth.user?.user_name ?? 'Usuário'}
									</p>
									<p class="text-xs text-slate-500 dark:text-slate-400">
										{$auth.user?.user_email ?? ''}
									</p>
								</div>

								<a
									href="/dashboard/profile"
									onclick={closeUserMenu}
									class="flex w-full items-center gap-3 px-4 py-2 text-sm text-slate-700 transition-colors hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800"
								>
									<User size={16} />
									Meu Perfil
								</a>

								<a
									href="/dashboard/subscription"
									onclick={closeUserMenu}
									class="flex w-full items-center gap-3 px-4 py-2 text-sm text-slate-700 transition-colors hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800"
								>
									<CreditCard size={16} />
									Assinatura
								</a>

								<a
									href="/dashboard/help"
									onclick={closeUserMenu}
									class="flex w-full items-center gap-3 px-4 py-2 text-sm text-slate-700 transition-colors hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800"
								>
									<HelpCircle size={16} />
									Ajuda
								</a>
							</div>
						{/if}
					</div>
				</div>
			</div>
		</header>

		<!-- Page Content Scrollable Area -->
		<main class="relative flex-1 overflow-x-hidden overflow-y-auto p-4 lg:p-8">
			{@render children()}
		</main>
	</div>
</div>
