import { useAuth } from "@/_core/hooks/useAuth";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInset,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarProvider,
  SidebarSeparator,
  SidebarTrigger,
  useSidebar,
} from "@/components/ui/sidebar";
import { getLoginUrl } from "@/const";
import { useTheme } from "@/contexts/ThemeContext";
import { useViewportFlags } from "@/hooks/useMobile";
import { buildRoutePrefetchHandlers } from "@/lib/routePrefetch";
import { trpc } from "@/lib/trpc";
import {
  BarChart3,
  Bell,
  Building2,
  Calendar,
  CalendarDays,
  ClipboardList,
  Database,
  FileText,
  FolderOpen,
  HelpCircle,
  LayoutDashboard,
  Loader2,
  LogOut,
  Mail,
  Package2,
  PanelLeft,
  Shield,
  TrendingUp,
  Users,
} from "lucide-react";
import { CSSProperties, createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { Link, useLocation, useSearch } from "wouter";
import { DashboardLayoutSkeleton } from './DashboardLayoutSkeleton';

const adminMenuItems = [{ icon: Shield, label: "Administration", path: "/admin" }];

type RoleViewMode = "accueil" | "logistique" | "direction" | "full_admin";

type SidebarNavItem = {
  icon: typeof LayoutDashboard;
  label: string;
  path: string;
  accentClass?: string;
  badgeCount?: number;
};

type SidebarNavSection = {
  id: string;
  label: string;
  accentClass?: string;
  items: SidebarNavItem[];
};

function getRoleViewMode(user: { role?: string | null; canSignSalle?: boolean | null }): RoleViewMode | null {
  if (user?.role === "accueil") return "accueil";
  if (user?.role === "logistique_controle") return "logistique";
  if (user?.role === "admin" || user?.role === "super_admin") return "full_admin";
  if (user?.role === "directrice" || Boolean(user?.canSignSalle)) return "direction";
  return null;
}

function buildAdminSidebarItems(user: {
  role?: string | null;
  canSignSalle?: boolean | null;
  canManageLogistics?: boolean | null;
}): SidebarNavItem[] {
  return buildAdminSidebarSections(user).flatMap((section) => section.items);
}

function buildAdminSidebarSections(user: {
  role?: string | null;
  canSignSalle?: boolean | null;
  canManageLogistics?: boolean | null;
}, notificationBadgeCount?: number): SidebarNavSection[] {
  const roleViewMode = getRoleViewMode(user);
  if (!roleViewMode || roleViewMode === "direction") {
    return [{ id: "admin", label: "Administration", items: adminMenuItems }];
  }

  const canAccessAnalytics = user?.role === "accueil" || user?.role === "admin" || user?.role === "super_admin";
  const canAccessInternalDirectory =
    user?.role === "accueil" || user?.role === "admin" || user?.role === "super_admin";
  const canManageLogistics = user?.role === "super_admin" || Boolean(user?.canManageLogistics);
  const isAccueil = roleViewMode === "accueil";
  const isLogisticsControl = roleViewMode === "logistique";
  const userRole = user?.role;

  const items = [
    { id: "dashboard", label: "Tableau de bord", icon: BarChart3, visibleFor: ["accueil", "logistique", "full_admin"], isEnabled: () => true },
    { id: "analytics", label: "Indicateurs", icon: TrendingUp, visibleFor: ["accueil", "full_admin"], isEnabled: () => canAccessAnalytics },
    { id: "requests", label: "Demandes", icon: ClipboardList, visibleFor: ["accueil", "logistique", "full_admin"], isEnabled: () => true },
    { id: "associations", label: "Comptes associations", icon: Building2, visibleFor: ["full_admin"], isEnabled: () => true },
    { id: "notifications", label: "Alertes", icon: Bell, visibleFor: ["accueil", "logistique", "full_admin"], isEnabled: () => true },
    { id: "calendrier", label: "Calendrier", icon: Calendar, visibleFor: ["accueil", "logistique", "full_admin"], isEnabled: () => true },
    { id: "ccds-directory", label: "Répertoire CCDS", icon: Users, visibleFor: ["accueil", "full_admin"], isEnabled: () => canAccessInternalDirectory },
    { id: "logistique", label: "Suivi logistique", icon: Package2, visibleFor: ["logistique", "full_admin"], isEnabled: () => canManageLogistics && !isAccueil },
    { id: "diffusion", label: "Diffusion matériel", icon: Mail, visibleFor: ["logistique", "full_admin"], isEnabled: () => !isAccueil && userRole !== "directrice" },
    { id: "directory", label: "Référentiel associations", icon: Database, visibleFor: ["full_admin"], isEnabled: () => !isLogisticsControl && (userRole === "admin" || userRole === "super_admin") },
    { id: "conformite", label: "Conformité", icon: Shield, visibleFor: ["full_admin"], isEnabled: () => userRole === "admin" || userRole === "super_admin" },
  ] satisfies Array<{
    id: string;
    label: string;
    icon: typeof LayoutDashboard;
    visibleFor: RoleViewMode[];
    isEnabled: () => boolean;
  }>;

  const visibleItems = items
    .filter((item) => item.visibleFor.some((value) => value === roleViewMode) && item.isEnabled())
    .map((item) => ({
      id: item.id,
      icon: item.icon,
      label: item.label,
      path:
        item.id === "dashboard"
          ? "/admin"
          : `/admin?tab=${item.id}`,
      accentClass:
        item.id === "dashboard"
          ? "text-emerald-600"
          : item.id === "analytics"
            ? "text-sky-600"
            : item.id === "notifications"
              ? "text-rose-600"
              : item.id === "calendrier"
                ? "text-amber-600"
                : item.id === "requests"
                  ? "text-indigo-600"
                  : item.id === "associations" || item.id === "ccds-directory"
                    ? "text-cyan-600"
                    : item.id === "logistique" || item.id === "diffusion" || item.id === "directory"
                      ? "text-orange-600"
                      : "text-violet-600",
      badgeCount: item.id === "notifications" ? notificationBadgeCount : undefined,
    }));

  const has = (id: string) => visibleItems.find((item) => item.id === id);

  return [
    {
      id: "pilotage",
      label: "Pilotage",
      accentClass: "text-sky-700",
      items: [has("dashboard"), has("analytics"), has("notifications"), has("calendrier")].filter(Boolean) as SidebarNavItem[],
    },
    {
      id: "demandes",
      label: "Dossiers & annuaires",
      accentClass: "text-indigo-700",
      items: [has("requests"), has("associations"), has("ccds-directory")].filter(Boolean) as SidebarNavItem[],
    },
    {
      id: "materiel",
      label: "Logistique & référentiels",
      accentClass: "text-orange-700",
      items: [has("logistique"), has("diffusion"), has("directory")].filter(Boolean) as SidebarNavItem[],
    },
    {
      id: "conformite",
      label: "Conformité",
      accentClass: "text-violet-700",
      items: [has("conformite")].filter(Boolean) as SidebarNavItem[],
    },
  ].filter((section) => section.items.length > 0);
}

function buildUserSidebarSections(options: {
  canAccessAdmin?: boolean | null;
}): SidebarNavSection[] {
  const { canAccessAdmin } = options;

  const sections: SidebarNavSection[] = [
    {
      id: "espace",
      label: "Suivi",
      accentClass: "text-emerald-700",
      items: [
        { icon: LayoutDashboard, label: "Tableau de bord", path: "/dashboard", accentClass: "text-emerald-600" },
        { icon: Building2, label: "Mon association", path: "/dashboard/profile", accentClass: "text-sky-600" },
        { icon: FolderOpen, label: "Mes documents", path: "/dashboard/documents", accentClass: "text-cyan-600" },
        { icon: ClipboardList, label: "Mes demandes", path: "/dashboard/requests", accentClass: "text-indigo-600" },
      ],
    },
    {
      id: "demarches",
      label: "Démarches",
      accentClass: "text-amber-700",
      items: [
        { icon: FileText, label: "Nouvelle demande", path: "/dashboard/requests/new", accentClass: "text-amber-600" },
        { icon: CalendarDays, label: "Réservation de salle", path: "/dashboard/reservation-salle", accentClass: "text-blue-600" },
        { icon: Package2, label: "Matériel événementiel", path: "/dashboard/materiel-evenementiel", accentClass: "text-orange-600" },
      ],
    },
    {
      id: "ressources",
      label: "Référentiels",
      accentClass: "text-violet-700",
      items: [
        { icon: Users, label: "Annuaire des associations", path: "/dashboard/associations", accentClass: "text-violet-600" },
        { icon: HelpCircle, label: "Aide", path: "/faq", accentClass: "text-slate-600" },
      ],
    },
  ];

  if (canAccessAdmin) {
    sections.push({
      id: "administration",
      label: "Administration",
      accentClass: "text-slate-700",
      items: [{ icon: Shield, label: "Administration", path: "/admin", accentClass: "text-slate-700" }],
    });
  }

  return sections;
}

const SIDEBAR_WIDTH_KEY = "sidebar-width";
const DEFAULT_WIDTH = 280;
const MIN_WIDTH = 200;
const MAX_WIDTH = 480;

type UnsavedChangesGuard = {
  when: boolean;
  title?: string;
  message?: string;
  onSave?: () => Promise<boolean | void> | boolean | void;
};

type DashboardNavigationGuardContextValue = {
  setUnsavedChangesGuard: (guard: UnsavedChangesGuard | null) => void;
};

const DashboardNavigationGuardContext = createContext<DashboardNavigationGuardContextValue | null>(null);

export function useDashboardNavigationGuard() {
  const context = useContext(DashboardNavigationGuardContext);
  if (!context) {
    throw new Error("useDashboardNavigationGuard must be used within DashboardLayout.");
  }
  return context;
}

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [sidebarWidth, setSidebarWidth] = useState(() => {
    const saved = localStorage.getItem(SIDEBAR_WIDTH_KEY);
    return saved ? parseInt(saved, 10) : DEFAULT_WIDTH;
  });
  const { loading, user } = useAuth();
  const [guard, setGuard] = useState<UnsavedChangesGuard | null>(null);
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const guardContextValue = useMemo(
    () => ({ setUnsavedChangesGuard: setGuard }),
    []
  );

  useEffect(() => {
    localStorage.setItem(SIDEBAR_WIDTH_KEY, sidebarWidth.toString());
  }, [sidebarWidth]);

  if (loading) {
    return <DashboardLayoutSkeleton />
  }

  if (!user) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="flex flex-col items-center gap-8 p-8 max-w-md w-full">
          <div className="flex flex-col items-center gap-6">
            <h1 className="text-2xl font-semibold tracking-tight text-center">
              Connexion requise
            </h1>
            <p className="text-sm text-muted-foreground text-center max-w-sm">
              Connectez-vous pour acceder a votre espace association.
            </p>
          </div>
          <Button
            onClick={() => {
              window.location.href = getLoginUrl();
            }}
            size="lg"
            className="w-full shadow-lg hover:shadow-xl transition-all"
          >
            Se connecter
          </Button>
        </div>
      </div>
    );
  }

  return (
    <DashboardNavigationGuardContext.Provider value={guardContextValue}>
      <SidebarProvider
        open={sidebarOpen}
        onOpenChange={setSidebarOpen}
        style={
          {
            "--sidebar-width": `${sidebarWidth}px`,
          } as CSSProperties
        }
      >
        <DashboardLayoutContent setSidebarWidth={setSidebarWidth} guard={guard}>
          {children}
        </DashboardLayoutContent>
      </SidebarProvider>
    </DashboardNavigationGuardContext.Provider>
  );
}

type DashboardLayoutContentProps = {
  children: React.ReactNode;
  setSidebarWidth: (width: number) => void;
  guard: UnsavedChangesGuard | null;
};

function DashboardLayoutContent({
  children,
  setSidebarWidth,
  guard,
}: DashboardLayoutContentProps) {
  const { user, logout } = useAuth();
  const { appearance } = useTheme();
  const [location, setLocation] = useLocation();
  const search = useSearch();
  const { state, open, setOpen, setOpenMobile, toggleSidebar } = useSidebar();
  const isCollapsed = state === "collapsed";
  const [isResizing, setIsResizing] = useState(false);
  const sidebarRef = useRef<HTMLDivElement>(null);
  const { isMobile, isTablet } = useViewportFlags();
  const [guardDialogOpen, setGuardDialogOpen] = useState(false);
  const [isSavingBeforeLeave, setIsSavingBeforeLeave] = useState(false);
  const pendingActionRef = useRef<(() => void) | null>(null);
  const canAccessAdmin =
    user?.role === "accueil" ||
    user?.role === "logistique_controle" ||
    user?.role === "admin" ||
    user?.role === "super_admin" ||
    user?.role === "directrice" ||
    Boolean(user?.canSignSalle);
  const { data: unreadCount } = trpc.notifications.getUnreadCount.useQuery(undefined, {
    staleTime: 30_000,
    refetchOnWindowFocus: true,
  });
  const currentAdminPath = search ? `${location}?${search}` : location;
  const isAdminRoute = location === "/admin";
  const isAdminLikeRoute = isAdminRoute;
  const notificationBadgeCount = unreadCount && unreadCount > 0 ? unreadCount : undefined;
  const adminSidebarSections = useMemo(
    () => buildAdminSidebarSections(user || {}, notificationBadgeCount),
    [notificationBadgeCount, user]
  );
  const adminSidebarItems = useMemo(() => buildAdminSidebarItems(user || {}), [user]);
  const userSidebarSections = useMemo(
    () =>
      buildUserSidebarSections({
        canAccessAdmin,
      }),
    [canAccessAdmin]
  );
  const allMenuItems = isAdminLikeRoute
    ? adminSidebarItems
    : userSidebarSections.flatMap((section) => section.items);
  const isMenuItemActive = useCallback(
    (path: string) => {
      if (path === "/admin") {
        return currentAdminPath === "/admin";
      }

      if (path.startsWith("/admin?")) {
        const currentUrl = new URL(currentAdminPath, window.location.origin);
        const targetUrl = new URL(path, window.location.origin);
        return (
          currentUrl.pathname === "/admin" &&
          (currentUrl.searchParams.get("tab") || "dashboard") ===
            (targetUrl.searchParams.get("tab") || "dashboard")
        );
      }

      if (path === "/dashboard") {
        return location === "/dashboard";
      }

      if (path === "/dashboard/requests") {
        return (
          location === "/dashboard/requests" ||
          (/^\/dashboard\/requests\/[^/]+/.test(location) && !location.startsWith("/dashboard/requests/new"))
        );
      }
      return location === path;
    },
    [currentAdminPath, location]
  );
  const activeMenuItem = allMenuItems.find((item) => isMenuItemActive(item.path));
  const portalTitle = appearance.portalTitle?.trim() || "Portail Associations 973";
  const sidebarSections = isAdminLikeRoute ? adminSidebarSections : userSidebarSections;
  const displayDensity = appearance.displayDensity || "comfortable";
  const isCompactDensity = displayDensity === "compact";
  const isDetailedDensity = displayDensity === "detailed";

  const requestNavigation = useCallback(
    (action: () => void) => {
      if (guard?.when) {
        pendingActionRef.current = action;
        setGuardDialogOpen(true);
        return;
      }
      action();
    },
    [guard]
  );

  useEffect(() => {
    if (isMobile) {
      return;
    }

    if (!isAdminLikeRoute && !open) {
      setOpen(true);
    }
  }, [isAdminLikeRoute, isMobile, open, setOpen]);

  useEffect(() => {
    if (isCollapsed) {
      setIsResizing(false);
    }
  }, [isCollapsed]);

  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      if (!isResizing) return;

      const sidebarLeft = sidebarRef.current?.getBoundingClientRect().left ?? 0;
      const newWidth = e.clientX - sidebarLeft;
      if (newWidth >= MIN_WIDTH && newWidth <= MAX_WIDTH) {
        setSidebarWidth(newWidth);
      }
    };

    const handleMouseUp = () => {
      setIsResizing(false);
    };

    if (isResizing) {
      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);
      document.body.style.cursor = "col-resize";
      document.body.style.userSelect = "none";
    }

    return () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
      document.body.style.cursor = "";
      document.body.style.userSelect = "";
    };
  }, [isResizing, setSidebarWidth]);

  useEffect(() => {
    if (!guard?.when) {
      setGuardDialogOpen(false);
      pendingActionRef.current = null;
    }
  }, [guard?.when]);

  useEffect(() => {
    if (!guard?.when) {
      return;
    }

    const handleBeforeUnload = (event: BeforeUnloadEvent) => {
      event.preventDefault();
      event.returnValue = "";
    };

    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => window.removeEventListener("beforeunload", handleBeforeUnload);
  }, [guard?.when]);

  useEffect(() => {
    if (!guard?.when) {
      return;
    }

    const handleDocumentClick = (event: MouseEvent) => {
      if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
        return;
      }

      const target = event.target instanceof Element ? event.target.closest("a[href]") : null;
      if (!(target instanceof HTMLAnchorElement)) {
        return;
      }

      if (target.target === "_blank" || target.hasAttribute("download")) {
        return;
      }

      const rawHref = target.getAttribute("href");
      if (!rawHref || rawHref.startsWith("#") || rawHref.startsWith("mailto:") || rawHref.startsWith("tel:")) {
        return;
      }

      const nextUrl = new URL(rawHref, window.location.origin);
      const currentUrl = new URL(window.location.href);
      const nextPath = `${nextUrl.pathname}${nextUrl.search}${nextUrl.hash}`;
      const currentPath = `${currentUrl.pathname}${currentUrl.search}${currentUrl.hash}`;

      if (nextPath === currentPath) {
        return;
      }

      event.preventDefault();
      requestNavigation(() => {
        if (nextUrl.origin === currentUrl.origin) {
          setLocation(nextPath);
        } else {
          window.location.assign(nextUrl.href);
        }
      });
    };

    document.addEventListener("click", handleDocumentClick, true);
    return () => document.removeEventListener("click", handleDocumentClick, true);
  }, [guard?.when, requestNavigation, setLocation]);

  const handleContinueWithoutSaving = () => {
    setGuardDialogOpen(false);
    const action = pendingActionRef.current;
    pendingActionRef.current = null;
    action?.();
  };

  const handleCancelNavigation = () => {
    setGuardDialogOpen(false);
    pendingActionRef.current = null;
  };

  const handleSaveAndContinue = async () => {
    if (!guard?.onSave) {
      handleContinueWithoutSaving();
      return;
    }

    try {
      setIsSavingBeforeLeave(true);
      const result = await guard.onSave();
      if (result === false) {
        return;
      }
      setGuardDialogOpen(false);
      const action = pendingActionRef.current;
      pendingActionRef.current = null;
      action?.();
    } finally {
      setIsSavingBeforeLeave(false);
    }
  };

  return (
    <>
      <div className="relative" ref={sidebarRef}>
        <Sidebar
          collapsible="icon"
          className="border-r-0"
          disableTransition={isResizing}
        >
          <SidebarHeader className={isDetailedDensity ? "h-[4.5rem] justify-center" : isCompactDensity ? "h-[3.8rem] justify-center" : "h-16 justify-center"}>
            <div className="flex items-center gap-3 px-2 transition-all w-full">
              <button
                onClick={toggleSidebar}
                className="h-8 w-8 flex items-center justify-center hover:bg-accent rounded-lg transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-ring shrink-0"
                aria-label="Toggle navigation"
              >
                <PanelLeft className="h-4 w-4 text-muted-foreground" />
              </button>
              {!isCollapsed ? (
                <Link href="/" className="flex items-center gap-2 min-w-0">
                  {appearance.logoUrl ? (
                    <img
                      src={appearance.logoUrl}
                      alt={portalTitle}
                      className="h-8 w-8 shrink-0 rounded-md object-contain"
                    />
                  ) : null}
                  <span className="font-semibold tracking-tight truncate text-primary">
                    {portalTitle}
                  </span>
                </Link>
              ) : null}
            </div>
          </SidebarHeader>

          <SidebarContent className="gap-0">
            <div className={isDetailedDensity ? "px-3 py-3" : isCompactDensity ? "px-1.5 py-1.5" : "px-2 py-2"}>
              {sidebarSections.map((section, sectionIndex) => (
                <div key={section.id}>
                  {sectionIndex > 0 ? <SidebarSeparator className={isDetailedDensity ? "my-3 opacity-70" : isCompactDensity ? "my-1.5 opacity-70" : "my-2 opacity-70"} /> : null}
                  <SidebarGroup className={isDetailedDensity ? "py-1.5" : isCompactDensity ? "py-0" : "py-0.5"}>
                    {!isCollapsed ? (
                      <SidebarGroupLabel
                        className={`px-2 ${isDetailedDensity ? "pb-2 text-[11px]" : isCompactDensity ? "pb-0.5 text-[9px]" : "pb-1 text-[10px]"} font-semibold uppercase tracking-[0.12em] text-muted-foreground/75 ${section.accentClass ?? ""}`}
                      >
                        {section.label}
                      </SidebarGroupLabel>
                    ) : null}
                    <SidebarGroupContent>
                      <SidebarMenu className={isDetailedDensity ? "px-0 py-1.5" : isCompactDensity ? "px-0 py-0" : "px-0 py-0.5"}>
                        {section.items.map((item) => {
                          const isActive = isMenuItemActive(item.path);
                          const hasBadge = item.label === "Notifications" && item.badgeCount && item.badgeCount > 0;
                          return (
                            <SidebarMenuItem key={item.path}>
                              <SidebarMenuButton
                                asChild
                                isActive={isActive}
                                tooltip={item.label}
                                className={`${isDetailedDensity ? "h-11 rounded-2xl px-3" : isCompactDensity ? "h-8 rounded-lg px-2" : "h-9 rounded-xl px-2"} font-medium transition-all data-[active=true]:shadow-sm`}
                              >
                                <a
                                  href={item.path}
                                  onClick={(event) => {
                                    event.preventDefault();
                                    requestNavigation(() => {
                                      if (isMobile) {
                                        setOpenMobile(false);
                                      }
                                      setLocation(item.path);
                                    });
                                  }}
                                  {...buildRoutePrefetchHandlers(item.path)}
                                  className={`flex w-full items-center ${isDetailedDensity ? "gap-3" : isCompactDensity ? "gap-2" : "gap-2.5"}`}
                                >
                                  <item.icon
                                    className={`${isDetailedDensity ? "h-[1.05rem] w-[1.05rem]" : "h-4 w-4"} shrink-0 transition-colors ${isActive ? "text-primary" : item.accentClass ?? "text-muted-foreground"}`}
                                  />
                                  <span className="min-w-0 flex-1 truncate">{item.label}</span>
                                  {!isCollapsed && hasBadge ? (
                                    <Badge className="min-w-5 rounded-full px-1.5 py-0 text-[10px] leading-4 shadow-sm">
                                      {item.badgeCount && item.badgeCount > 99 ? "99+" : item.badgeCount}
                                    </Badge>
                                  ) : null}
                                </a>
                              </SidebarMenuButton>
                            </SidebarMenuItem>
                          );
                        })}
                      </SidebarMenu>
                    </SidebarGroupContent>
                  </SidebarGroup>
                </div>
              ))}
            </div>
          </SidebarContent>

          <SidebarFooter className={isDetailedDensity ? "p-4" : isCompactDensity ? "p-2.5" : "p-3"}>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button className="flex items-center gap-3 rounded-lg px-1 py-1 hover:bg-accent/50 transition-colors w-full text-left group-data-[collapsible=icon]:justify-center focus:outline-none focus-visible:ring-2 focus-visible:ring-ring">
                  <Avatar className="h-9 w-9 border shrink-0">
                    <AvatarFallback className="text-xs font-medium">
                      {user?.name?.charAt(0).toUpperCase()}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0 group-data-[collapsible=icon]:hidden">
                    <p className="text-sm font-medium truncate leading-none">
                      {user?.name || "-"}
                    </p>
                    <p className="text-xs text-muted-foreground truncate mt-1.5">
                      {user?.email || "-"}
                    </p>
                  </div>
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-48">
                <DropdownMenuItem
                  onClick={() => requestNavigation(() => void logout())}
                  className="cursor-pointer text-destructive focus:text-destructive"
                >
                  <LogOut className="mr-2 h-4 w-4" />
                  <span>Sign out</span>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </SidebarFooter>
        </Sidebar>
        <div
          className={`absolute top-0 right-0 h-full w-1 cursor-col-resize transition-colors hover:bg-primary/20 ${isCollapsed || isTablet ? "hidden" : ""}`}
          onMouseDown={() => {
            if (isCollapsed || isTablet) return;
            setIsResizing(true);
          }}
          style={{ zIndex: 50 }}
        />
      </div>

      <SidebarInset className="min-w-0 overflow-x-hidden">
        {isMobile && (
          <div className={`sticky top-0 z-40 flex ${isDetailedDensity ? "h-16 px-4" : isCompactDensity ? "h-[3.25rem] px-3" : "h-14 px-3"} items-center justify-between border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:backdrop-blur`}>
            <div className="flex items-center gap-2">
              <SidebarTrigger className="h-9 w-9 rounded-lg bg-background" />
              <div className="flex items-center gap-3">
                {appearance.logoUrl ? (
                  <img
                    src={appearance.logoUrl}
                    alt={portalTitle}
                    className="h-7 w-7 shrink-0 rounded-md object-contain"
                  />
                ) : null}
                <div className="flex min-w-0 flex-col gap-1">
                  <span className="truncate tracking-tight text-foreground">
                    {activeMenuItem?.label ?? "Menu"}
                  </span>
                </div>
              </div>
            </div>
          </div>
        )}
        <main className={`portal-immersive-main min-w-0 flex-1 overflow-x-hidden ${isDetailedDensity ? "p-4 sm:p-5 lg:p-7" : isCompactDensity ? "p-2.5 sm:p-3.5 lg:p-5" : "p-3 sm:p-4 lg:p-6"}`}>{children}</main>
      </SidebarInset>
      <Dialog open={guardDialogOpen} onOpenChange={setGuardDialogOpen}>
        <DialogContent showCloseButton={false}>
          <DialogHeader>
            <DialogTitle>{guard?.title || "Modifications non enregistrées"}</DialogTitle>
            <DialogDescription>
              {guard?.message ||
                "Vous avez des modifications non enregistrées ou une fiche incomplète. Souhaitez-vous enregistrer vos changements avant de quitter cette page ?"}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex-col gap-2 sm:flex-row sm:justify-end">
            <Button type="button" variant="outline" onClick={handleCancelNavigation} disabled={isSavingBeforeLeave}>
              Annuler et revenir au formulaire
            </Button>
            <Button type="button" variant="secondary" onClick={handleContinueWithoutSaving} disabled={isSavingBeforeLeave}>
              Continuer sans enregistrer
            </Button>
            <Button type="button" onClick={() => void handleSaveAndContinue()} disabled={isSavingBeforeLeave}>
              {isSavingBeforeLeave ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
              Enregistrer et continuer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
