<script lang="ts">
	import { page } from '$app/state';
	import { goto } from '$app/navigation';
	import logo from '$lib/assets/logo_governo_PE.png';
	import type { Snippet } from 'svelte';
	import { loginModalStore } from '$lib/stores/loginModal.svelte';
	import { useQuery } from 'convex-svelte';
	import { api } from '@sgse-app/backend/convex/_generated/api';
	import NotificationBell from '$lib/components/chat/NotificationBell.svelte';
	import ChatWidget from '$lib/components/chat/ChatWidget.svelte';
	import PresenceManager from '$lib/components/chat/PresenceManager.svelte';
	import { getAvatarUrl } from '$lib/utils/avatarGenerator';
	import { Menu, User, Home, UserPlus, XCircle, LogIn, Tag, Plus, Check } from 'lucide-svelte';
	import { authClient } from '$lib/auth';
	import { resolve } from '$app/paths';

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

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

	const currentUser = useQuery(api.auth.getCurrentUser, {});

	// Função para obter a URL do avatar/foto do usuário
	const avatarUrlDoUsuario = $derived(() => {
		if (!currentUser.data) return null;

		// Prioridade: fotoPerfilUrl > avatar > fallback com nome
		if (currentUser.data.fotoPerfil) {
			return currentUser.data.fotoPerfil;
		}

		// Fallback: gerar avatar baseado no nome
		return getAvatarUrl(currentUser.data.nome);
	});

	// Função para gerar classes do menu ativo
	function getMenuClasses(isActive: boolean) {
		const baseClasses =
			'group font-semibold flex items-center justify-center gap-2 text-center p-3.5 rounded-xl border-2 transition-all duration-300 shadow-md hover:shadow-lg hover:scale-105';

		if (isActive) {
			return `${baseClasses} border-primary bg-primary text-white shadow-lg scale-105`;
		}

		return `${baseClasses} border-primary/30 bg-linear-to-br from-base-100 to-base-200 text-base-content hover:from-primary hover:to-primary/80 hover:text-white`;
	}

	// Função para gerar classes do botão "Solicitar Acesso"
	function getSolicitarClasses(isActive: boolean) {
		const baseClasses =
			'group font-semibold flex items-center justify-center gap-2 text-center p-3.5 rounded-xl border-2 transition-all duration-300 shadow-md hover:shadow-lg hover:scale-105';

		if (isActive) {
			return `${baseClasses} border-success bg-success text-white shadow-lg scale-105`;
		}

		return `${baseClasses} border-success/30 bg-linear-to-br from-success/10 to-success/20 text-base-content hover:from-success hover:to-success/80 hover:text-white`;
	}

	const setores = [
		{ nome: 'Recursos Humanos', link: '/recursos-humanos' as const },
		{ nome: 'Financeiro', link: '/financeiro' as const },
		{ nome: 'Controladoria', link: '/controladoria' as const },
		{ nome: 'Licitações', link: '/licitacoes' as const },
		{ nome: 'Compras', link: '/compras' as const },
		{ nome: 'Jurídico', link: '/juridico' as const },
		{ nome: 'Comunicação', link: '/comunicacao' as const },
		{ nome: 'Programas Esportivos', link: '/programas-esportivos' as const },
		{ nome: 'Secretaria Executiva', link: '/secretaria-executiva' as const },
		{
			nome: 'Secretaria de Gestão de Pessoas',
			link: '/gestao-pessoas' as const
		},
		{ nome: 'Tecnologia da Informação', link: '/ti' as const }
	];

	let showAboutModal = $state(false);
	let matricula = $state('');
	let senha = $state('');
	let erroLogin = $state('');
	let carregandoLogin = $state(false);

	// Sincronizar com o store global
	$effect(() => {
		if (loginModalStore.showModal && !matricula && !senha) {
			matricula = '';
			senha = '';
			erroLogin = '';
		}
	});

	function openLoginModal() {
		loginModalStore.open();
		matricula = '';
		senha = '';
		erroLogin = '';
	}

	function closeLoginModal() {
		loginModalStore.close();
		matricula = '';
		senha = '';
		erroLogin = '';
	}

	function openAboutModal() {
		showAboutModal = true;
	}

	function closeAboutModal() {
		showAboutModal = false;
	}

	async function handleLogin(e: Event) {
		e.preventDefault();
		erroLogin = '';
		carregandoLogin = true;

		// const browserInfo = await getBrowserInfo();

		const result = await authClient.signIn.email(
			{ email: matricula.trim(), password: senha },
			{
				onError: (ctx) => {
					alert(ctx.error.message);
				}
			}
		);

		if (result.data) {
			closeLoginModal();
			goto(resolve('/'));
		} else {
			erroLogin = 'Erro ao fazer login';
		}
		carregandoLogin = false;
	}

	async function handleLogout() {
		const result = await authClient.signOut();
		if (result.error) {
			console.error('Sign out error:', result.error);
		}
		goto(resolve('/'));
	}
</script>

<!-- Header Fixo acima de tudo -->
<div
	class="navbar from-primary/30 via-primary/20 to-primary/30 border-primary/10 fixed top-0 right-0 left-0 z-50 min-h-24 border-b bg-linear-to-r px-6 shadow-lg backdrop-blur-sm lg:px-8"
>
	<div class="flex-none lg:hidden">
		<label
			for="my-drawer-3"
			class="group relative flex h-14 w-14 cursor-pointer items-center justify-center overflow-hidden rounded-2xl transition-all duration-300 hover:scale-105"
			style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); box-shadow: 0 8px 24px -4px rgba(102, 126, 234, 0.4);"
			aria-label="Abrir menu"
		>
			<!-- Efeito de brilho no hover -->
			<div
				class="absolute inset-0 bg-linear-to-br from-white/0 to-white/20 opacity-0 transition-opacity duration-300 group-hover:opacity-100"
			></div>

			<!-- Ícone de menu hambúrguer -->
			<Menu
				class="relative z-10 h-7 w-7 text-white transition-transform duration-300 group-hover:scale-110"
				style="filter: drop-shadow(0 2px 8px rgba(0,0,0,0.3));"
				strokeWidth={2.5}
			/>
		</label>
	</div>
	<div class="flex flex-1 items-center gap-4 lg:gap-6">
		<!-- Logo MODERNO do Governo -->
		<div class="avatar">
			<div
				class="group relative w-16 overflow-hidden rounded-2xl p-2 shadow-xl transition-all duration-300 hover:scale-105 lg:w-20"
				style="background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%); border: 2px solid rgba(102, 126, 234, 0.1);"
			>
				<!-- Efeito de brilho no hover -->
				<div
					class="from-primary/5 absolute inset-0 bg-linear-to-br to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100"
				></div>

				<!-- Logo -->
				<img
					src={logo}
					alt="Logo do Governo de PE"
					class="relative z-10 h-full w-full object-contain transition-transform duration-300 group-hover:scale-105"
					style="filter: drop-shadow(0 2px 4px rgba(0,0,0,0.08));"
				/>

				<!-- Brilho sutil no canto -->
				<div
					class="absolute top-0 right-0 h-8 w-8 rounded-bl-full bg-linear-to-br from-white/40 to-transparent opacity-70"
				></div>
			</div>
		</div>
		<div class="flex flex-col">
			<h1 class="text-primary text-xl font-bold tracking-tight lg:text-3xl">SGSE</h1>
			<p
				class="text-base-content/80 hidden text-xs leading-tight font-medium sm:block lg:text-base"
			>
				Sistema de Gerenciamento da<br class="lg:hidden" /> Secretaria de Esportes
			</p>
		</div>
	</div>
	<div class="ml-auto flex flex-none items-center gap-4">
		{#if currentUser.data}
			<!-- Sino de notificações no canto superior direito -->
			<div class="relative">
				<NotificationBell />
			</div>

			<div class="mr-2 hidden flex-col items-end lg:flex">
				<span class="text-primary text-sm font-semibold">{currentUser.data.nome}</span>
				<span class="text-base-content/60 text-xs">{currentUser.data.role?.nome}</span>
			</div>
			<div class="dropdown dropdown-end">
				<!-- Botão de Perfil ULTRA MODERNO -->
				<button
					type="button"
					tabindex="0"
					class="group relative flex h-14 w-14 items-center justify-center overflow-hidden rounded-2xl transition-all duration-300 hover:scale-105"
					style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); box-shadow: 0 8px 24px -4px rgba(102, 126, 234, 0.4);"
					aria-label="Menu do usuário"
				>
					<!-- Efeito de brilho no hover -->
					<div
						class="absolute inset-0 bg-linear-to-br from-white/0 to-white/20 opacity-0 transition-opacity duration-300 group-hover:opacity-100"
					></div>

					<!-- Anel de pulso sutil -->
					<div
						class="absolute inset-0 rounded-2xl"
						style="animation: pulse-ring-subtle 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;"
					></div>

					<!-- Avatar/Foto do usuário ou ícone padrão -->
					{#if avatarUrlDoUsuario()}
						<img
							src={avatarUrlDoUsuario()}
							alt={currentUser.data?.nome || 'Usuário'}
							class="relative z-10 h-full w-full object-cover"
						/>
					{:else}
						<!-- Ícone de usuário moderno (fallback) -->
						<User
							class="relative z-10 h-7 w-7 text-white transition-transform duration-300 group-hover:scale-110"
							style="filter: drop-shadow(0 2px 8px rgba(0,0,0,0.3));"
						/>
					{/if}

					<!-- Badge de status online -->
					<div
						class="bg-success absolute top-1 right-1 z-20 h-3 w-3 rounded-full border-2 border-white shadow-lg"
						style="animation: pulse-dot 2s ease-in-out infinite;"
					></div>
				</button>
				<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
				<ul
					tabindex="0"
					class="dropdown-content menu bg-base-100 rounded-box border-primary/20 z-1 mt-4 w-52 border p-2 shadow-xl"
				>
					<li class="menu-title">
						<span class="text-primary font-bold">{currentUser.data?.nome}</span>
					</li>
					<li><a href={resolve('/perfil')}>Meu Perfil</a></li>
					<li><a href={resolve('/alterar-senha')}>Alterar Senha</a></li>
					<div class="divider my-0"></div>
					<li>
						<button type="button" onclick={handleLogout} class="text-error">Sair</button>
					</li>
				</ul>
			</div>
		{:else}
			<button
				type="button"
				class="btn btn-lg hover:shadow-primary/30 group from-primary via-primary to-primary/80 hover:from-primary/90 hover:via-primary/80 hover:to-primary/70 relative overflow-hidden border-0 bg-linear-to-br shadow-2xl transition-all duration-500 hover:scale-110"
				style="width: 4rem; height: 4rem; border-radius: 9999px;"
				onclick={() => openLoginModal()}
				aria-label="Login"
			>
				<!-- Efeito de brilho animado -->
				<div
					class="absolute inset-0 -translate-x-full bg-linear-to-r from-transparent via-white/30 to-transparent transition-transform duration-1000 group-hover:translate-x-full"
				></div>

				<!-- Anel pulsante de fundo -->
				<div class="absolute inset-0 rounded-full bg-white/10 group-hover:animate-ping"></div>

				<!-- Ícone de login premium -->
				<User
					class="relative z-10 h-8 w-8 text-white transition-all duration-500 group-hover:scale-110"
					style="filter: drop-shadow(0 2px 8px rgba(0,0,0,0.3));"
					strokeWidth={2.5}
				/>
			</button>
		{/if}
	</div>
</div>

<div class="drawer lg:drawer-open" style="margin-top: 96px;">
	<input id="my-drawer-3" type="checkbox" class="drawer-toggle" />
	<div class="drawer-content flex flex-col lg:ml-72" style="min-height: calc(100vh - 96px);">
		<!-- Page content -->
		<div class="flex-1 overflow-y-auto">
			{@render children?.()}
		</div>

		<!-- Footer -->
		<footer
			class="footer footer-center from-primary/30 via-primary/20 to-primary/30 text-base-content border-primary/20 shrink-0 border-t-2 bg-linear-to-r p-6 shadow-inner backdrop-blur-sm"
		>
			<div class="grid grid-flow-col gap-6 text-sm font-medium">
				<button
					type="button"
					class="link link-hover hover:text-primary transition-colors"
					onclick={() => openAboutModal()}>Sobre</button
				>
				<span class="text-base-content/30">•</span>
				<a href={resolve('/')} class="link link-hover hover:text-primary transition-colors"
					>Contato</a
				>
				<span class="text-base-content/30">•</span>
				<a href={resolve('/')} class="link link-hover hover:text-primary transition-colors"
					>Suporte</a
				>
				<span class="text-base-content/30">•</span>
				<a href={resolve('/')} class="link link-hover hover:text-primary transition-colors"
					>Privacidade</a
				>
			</div>
			<div class="mt-2 flex items-center gap-3">
				<div class="avatar">
					<div class="w-10 rounded-lg bg-white p-1.5 shadow-md">
						<img src={logo} alt="Logo" class="h-full w-full object-contain" />
					</div>
				</div>
				<div class="text-left">
					<p class="text-primary text-xs font-bold">Governo do Estado de Pernambuco</p>
					<p class="text-base-content/70 text-xs">Secretaria de Esportes</p>
				</div>
			</div>
			<p class="text-base-content/60 mt-2 text-xs">
				© {new Date().getFullYear()} - Todos os direitos reservados
			</p>
		</footer>
	</div>
	<div class="drawer-side fixed z-40" style="margin-top: 96px;">
		<label for="my-drawer-3" aria-label="close sidebar" class="drawer-overlay"></label>
		<div
			class="menu from-primary/25 to-primary/15 border-primary/20 flex h-[calc(100vh-96px)] w-72 flex-col gap-2 overflow-y-auto border-r-2 bg-linear-to-b p-4 shadow-xl backdrop-blur-sm"
		>
			<!-- Sidebar menu items -->
			<ul class="flex flex-col gap-2">
				<li class="rounded-xl">
					<a href={resolve('/')} class={getMenuClasses(currentPath === '/')}>
						<Home class="h-5 w-5 transition-transform group-hover:scale-110" strokeWidth={2} />
						<span>Dashboard</span>
					</a>
				</li>
				{#each setores as s (s.link)}
					{@const isActive = currentPath.startsWith(s.link)}
					<li class="rounded-xl">
						<a
							href={resolve(s.link)}
							aria-current={isActive ? 'page' : undefined}
							class={getMenuClasses(isActive)}
						>
							<span>{s.nome}</span>
						</a>
					</li>
				{/each}
				<li class="mt-auto rounded-xl">
					<a
						href={resolve('/solicitar-acesso')}
						class={getSolicitarClasses(currentPath === '/solicitar-acesso')}
					>
						<UserPlus class="h-5 w-5" strokeWidth={2} />
						<span>Solicitar acesso</span>
					</a>
				</li>
			</ul>
		</div>
	</div>
</div>

<!-- Modal de Login -->
{#if loginModalStore.showModal}
	<dialog class="modal modal-open">
		<div class="modal-box bg-base-100 relative max-w-md overflow-hidden">
			<button
				type="button"
				class="btn btn-sm btn-circle btn-ghost absolute top-2 right-2"
				onclick={closeLoginModal}
			>
				✕
			</button>

			<div class="p-4">
				<div class="mb-6 text-center">
					<div class="avatar mb-4">
						<div class="bg-primary/10 w-20 rounded-lg p-3">
							<img src={logo} alt="Logo" class="h-full w-full object-contain" />
						</div>
					</div>
					<h3 class="text-primary text-3xl font-bold">Login</h3>
					<p class="text-base-content/60 mt-2 text-sm">Acesse o sistema com suas credenciais</p>
				</div>

				{#if erroLogin}
					<div class="alert alert-error mb-4">
						<XCircle class="h-6 w-6 shrink-0 stroke-current" strokeWidth={2} />
						<span>{erroLogin}</span>
					</div>
				{/if}

				<form class="space-y-4" onsubmit={handleLogin}>
					<div class="form-control">
						<label class="label" for="login-matricula">
							<span class="label-text font-semibold">Matrícula ou E-mail</span>
						</label>
						<input
							id="login-matricula"
							type="text"
							placeholder="Digite sua matrícula ou e-mail"
							class="input input-bordered input-primary w-full"
							bind:value={matricula}
							required
							disabled={carregandoLogin}
						/>
					</div>
					<div class="form-control">
						<label class="label" for="login-password">
							<span class="label-text font-semibold">Senha</span>
						</label>
						<input
							id="login-password"
							type="password"
							placeholder="Digite sua senha"
							class="input input-bordered input-primary w-full"
							bind:value={senha}
							required
							disabled={carregandoLogin}
						/>
					</div>
					<div class="form-control mt-6">
						<button type="submit" class="btn btn-primary w-full" disabled={carregandoLogin}>
							{#if carregandoLogin}
								<span class="loading loading-spinner loading-sm"></span>
								Entrando...
							{:else}
								<LogIn class="h-5 w-5" strokeWidth={2} />
								Entrar
							{/if}
						</button>
					</div>
					<div class="mt-4 space-y-2 text-center">
						<a
							href={resolve('/solicitar-acesso')}
							class="link link-primary block text-sm"
							onclick={closeLoginModal}
						>
							Não tem acesso? Solicite aqui
						</a>
						<a
							href={resolve('/esqueci-senha')}
							class="link link-secondary block text-sm"
							onclick={closeLoginModal}
						>
							Esqueceu sua senha?
						</a>
					</div>
				</form>

				<div class="divider text-base-content/40 text-xs">Credenciais de teste</div>
				<div class="bg-base-200 rounded-lg p-3 text-xs">
					<p class="mb-1 font-semibold">Admin:</p>
					<p>
						Matrícula: <code class="bg-base-300 rounded px-2 py-1">0000</code>
					</p>
					<p>
						Senha: <code class="bg-base-300 rounded px-2 py-1">Admin@123</code>
					</p>
				</div>
			</div>
		</div>
		<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
		<!-- svelte-ignore a11y_click_events_have_key_events -->
		<form method="dialog" class="modal-backdrop" onclick={closeLoginModal}>
			<button type="button">close</button>
		</form>
	</dialog>
{/if}

<!-- Modal Sobre -->
{#if showAboutModal}
	<dialog class="modal modal-open">
		<div
			class="modal-box from-base-100 to-base-200 relative max-w-2xl overflow-hidden bg-linear-to-br"
		>
			<button
				type="button"
				class="btn btn-sm btn-circle btn-ghost absolute top-2 right-2"
				onclick={closeAboutModal}
			>
				✕
			</button>

			<div class="space-y-6 py-4 text-center">
				<!-- Logo e Título -->
				<div class="flex flex-col items-center gap-4">
					<div class="avatar">
						<div class="w-24 rounded-xl bg-white p-3 shadow-lg">
							<img src={logo} alt="Logo SGSE" class="h-full w-full object-contain" />
						</div>
					</div>
					<div>
						<h3 class="text-primary mb-2 text-3xl font-bold">SGSE</h3>
						<p class="text-base-content/80 text-lg font-semibold">
							Sistema de Gerenciamento da<br />Secretaria de Esportes
						</p>
					</div>
				</div>

				<!-- Divider -->
				<div class="divider"></div>

				<!-- Informações de Versão -->
				<div class="bg-primary/10 space-y-3 rounded-xl p-6">
					<div class="flex items-center justify-center gap-2">
						<Tag class="text-primary h-5 w-5" strokeWidth={2} />
						<p class="text-base-content/70 text-sm font-medium">Versão</p>
					</div>
					<p class="text-primary text-2xl font-bold">1.0 26_2025</p>
					<div class="badge badge-warning badge-lg gap-2">
						<Plus class="h-4 w-4" strokeWidth={2} />
						Em Desenvolvimento
					</div>
				</div>

				<!-- Desenvolvido por -->
				<div class="space-y-2">
					<p class="text-base-content/60 text-sm font-medium">Desenvolvido por</p>
					<p class="text-primary text-lg font-bold">Secretaria de Esportes de Pernambuco</p>
				</div>

				<!-- Divider -->
				<div class="divider"></div>

				<!-- Informações Adicionais -->
				<div class="grid grid-cols-2 gap-4 text-sm">
					<div class="bg-base-200 rounded-lg p-3">
						<p class="text-primary font-semibold">Governo</p>
						<p class="text-base-content/70 text-xs">Estado de Pernambuco</p>
					</div>
					<div class="bg-base-200 rounded-lg p-3">
						<p class="text-primary font-semibold">Ano</p>
						<p class="text-base-content/70 text-xs">2025</p>
					</div>
				</div>

				<!-- Botão OK -->
				<div class="pt-4">
					<button
						type="button"
						class="btn btn-primary btn-lg mx-auto w-full max-w-xs shadow-lg transition-all duration-300 hover:shadow-xl"
						onclick={closeAboutModal}
					>
						<Check class="h-6 w-6" strokeWidth={2} />
						OK
					</button>
				</div>
			</div>
		</div>
		<div
			class="modal-backdrop"
			onclick={closeAboutModal}
			role="button"
			tabindex="0"
			onkeydown={(e) => e.key === 'Escape' && closeAboutModal()}
		></div>
	</dialog>
{/if}

<!-- Componentes de Chat (apenas se autenticado) -->
{#if currentUser.data}
	<PresenceManager />
	<ChatWidget />
{/if}

<style>
	/* Animação de pulso sutil para o anel do botão de perfil */
	@keyframes pulse-ring-subtle {
		0%,
		100% {
			opacity: 0.1;
			transform: scale(1);
		}
		50% {
			opacity: 0.3;
			transform: scale(1.05);
		}
	}

	/* Animação de pulso para o badge de status online */
	@keyframes pulse-dot {
		0%,
		100% {
			opacity: 1;
			transform: scale(1);
		}
		50% {
			opacity: 0.8;
			transform: scale(1.1);
		}
	}
</style>
