<script lang="ts">
	import { onMount } from "svelte";
	import { page } from "$app/state";
	import { useSidebar } from "$lib/components/ui/sidebar/context.svelte.js";
	import { getSidebarData } from "$lib/components/sidebar/modules";
	import { currentUser } from "$lib/auth";
	import NavMain from "./nav-main.svelte";
	import NavProjects from "./nav-projects.svelte";
	import NavUser from "./nav-user.svelte";
	import TeamSwitcher from "./team-switcher.svelte";
	import * as Sidebar from "$lib/components/ui/sidebar/index.js";
	import type { ComponentProps } from "svelte";

	let {
		ref = $bindable(null),
		collapsible = "icon",
		...restProps
	}: ComponentProps<typeof Sidebar.Root> = $props();

	// Leer siempre de page.data para que el sidebar reaccione tras invalidateAll()
	const userTenants = $derived((page.data.userTenants as { id: number; name: string; slug: string }[]) ?? []);

	// Obtener datos del sidebar con traducciones
	const sidebarData = getSidebarData();
	const mergedUser = $derived((page.data.user as any) || $currentUser || null);

	// Combinar los datos estáticos del sidebar con los datos del usuario de Keycloak
	const data = $derived({
		...sidebarData,
		user: mergedUser
			? {
					name: _displayName(mergedUser),
					email: mergedUser.email || "",
					username: mergedUser.preferred_username || mergedUser.username || "",
					firstName: mergedUser.first_name || mergedUser.firstName || mergedUser.given_name || null,
					lastName: mergedUser.last_name || mergedUser.lastName || mergedUser.family_name || null,
					displayName:
						mergedUser.displayName ||
						_displayName(mergedUser) ||
						mergedUser.preferred_username ||
						mergedUser.username ||
						"",
					avatarUrl:
						mergedUser.workspaceAvatarUrl ||
						mergedUser.workspace_avatar_url ||
						mergedUser.avatarUrl ||
						mergedUser.avatar_url ||
						mergedUser.legacyAvatarUrl ||
						mergedUser.legacy_avatar_url ||
						null,
					workspaceAvatarUrl:
						mergedUser.workspaceAvatarUrl ||
						mergedUser.workspace_avatar_url ||
						null,
					legacyAvatarUrl:
						mergedUser.legacyAvatarUrl ||
						mergedUser.legacy_avatar_url ||
						mergedUser.avatar_url ||
						null,
			  }
			: sidebarData.user,
	});

	$effect(() => {
		if (mergedUser) {
			console.debug('[avatar][sidebar] avatar final en page.data.user:', data.user?.avatarUrl ?? '(null)');
		}
	});

	function _displayName(u: any): string {
		const first = u.first_name || u.given_name || "";
		const last  = u.last_name  || u.family_name  || "";
		return (first + " " + last).trim() || u.name || u.preferred_username || "";
	}

	const sidebar = useSidebar();

	onMount(() => {
		const expandForKeyboardNav = () => {
			sidebar.setOpen(true);
			if (sidebar.isMobile) sidebar.setOpenMobile(true);
		};
		window.addEventListener("anexo76:expand-sidebar-for-nav", expandForKeyboardNav);
		return () =>
			window.removeEventListener("anexo76:expand-sidebar-for-nav", expandForKeyboardNav);
	});
</script>

<Sidebar.Root {collapsible} {...restProps}>
	<Sidebar.Header>
		<TeamSwitcher {userTenants} />
	</Sidebar.Header>
	<Sidebar.Content>
		<NavMain items={data.navMain} />
		<NavProjects projects={data.projects} />
	</Sidebar.Content>
	<Sidebar.Footer>
		<NavUser user={data.user} tenants={userTenants} />
	</Sidebar.Footer>
	<Sidebar.Rail />
</Sidebar.Root>
