import React, { useState, useRef, useEffect, createContext, useContext, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useTranslation } from 'react-i18next';
import {
  Menu,
  ArrowLeft,
  LogOut,
  Settings,
  MoreVertical,
  ChevronRight,
  Filter,
} from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '../../ui/avatar';
import { Popover, PopoverContent, PopoverTrigger } from '../../ui/popover';
import { Tooltip, TooltipProvider, TooltipTrigger } from '../../ui/tooltip';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
  DropdownMenuPortal,
} from '../../ui/dropdown-menu';
import { Input } from '../../ui/input';
import { Search as SearchIcon } from 'lucide-react';
import { cn } from '../../shared/utils';
import { XerticaLogo } from '../../brand/xertica-logo';
import { XerticaXLogo } from '../../brand/xertica-xlogo';
import { Button } from '../../ui/button';
import { useOptionalLayout } from '../../../contexts/LayoutContext';
import { useSidebar } from './use-sidebar';
import { CustomTooltipContent as SidebarTooltipContent } from '../../shared/CustomTooltipContent';

// ─────────────────────────────────────────────────────────────────────────────
// Public interfaces
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Contextual action menu item for routes and groups.
 */
export interface ActionMenuItem {
  /** Text label */
  label: string;
  /** Optional icon component */
  icon?: React.ComponentType<any>;
  /** Click handler */
  onClick?: (item: any) => void;
  /** Visual variant */
  variant?: 'default' | 'destructive';
  /** Nested sub-actions */
  children?: ActionMenuItem[];
}

/**
 * Navigation route configuration.
 */
export interface RouteConfig {
  /** Relative or absolute path */
  path: string;
  /** Navigation label */
  label: string;
  /** Icon component */
  icon?: React.ComponentType<any>;
  /** React component for the route (optional) */
  component?: React.ComponentType<any>;
  /** Hover action menu items (ellipsis) */
  actions?: ActionMenuItem[];
  /** Auxiliary content shown when the route is selected */
  description?: React.ReactNode;
  /** Child routes exposed via contextual menu button at the end of the item */
  children?: RouteConfig[];
}

export interface NavigationItem {
  path: string;
  label: string;
  icon?: any;
  active: boolean;
  children?: RouteConfig[];
  actions?: ActionMenuItem[];
}

export interface SidebarFilterConfig {
  show: boolean;
  content?: React.ReactNode;
  icon?: React.ReactNode;
}

export interface SidebarSearchConfig {
  show: boolean;
  placeholder?: string;
  value?: string;
  onChange?: (value: string) => void;
  filter?: SidebarFilterConfig;
}

export interface SidebarFixedAreaConfig {
  show: boolean;
  content?: React.ReactNode;
  icon?: any;
  onClick?: () => void;
}

export interface SidebarFooterConfig {
  showUser?: boolean;
  showSettings?: boolean;
  showLogout?: boolean;
}

/**
 * Logical grouping of navigation routes (e.g., in Assistant variant).
 */
export interface RouteGroup {
  /** Unique ID */
  id: string;
  /** Group title */
  label?: string;
  /** Group icon */
  icon?: React.ComponentType<any>;
  /** Navigational items in the group */
  items: RouteConfig[];
  /** Context menu for the entire group */
  actions?: ActionMenuItem[];
}

/**
 * Navigation Sidebar component.
 */
export interface SidebarProps {
  /** Whether the sidebar is expanded (defaults to LayoutContext state if available) */
  expanded?: boolean;
  /** Callback to toggle expansion state (defaults to LayoutContext toggle if available) */
  onToggle?: () => void;
  /** Authenticated user info */
  user?: {
    name?: string;
    email?: string;
    avatar?: string;
  } | null;
  /** Logout callback */
  onLogout?: () => void;
  /** Settings callback */
  onSettingsClick?: () => void;
  /** Current location for active state detection (defaults to window.location if missing) */
  location?: { pathname: string };
  /** Navigation callback (defaults to window.location.href if missing) */
  navigate?: (path: string) => void;
  /** Flat list of navigation routes */
  routes?: RouteConfig[];
  /** Logo shown in expanded state */
  logo?: React.ReactNode;
  /** Logo shown in collapsed state */
  logoCollapsed?: React.ReactNode;
  /** Visual variant */
  variant?: 'default' | 'assistant';
  /** Assistant-only fixed area configuration */
  fixedArea?: SidebarFixedAreaConfig;
  /** Assistant-only search bar configuration */
  search?: SidebarSearchConfig;
  /** Grouped navigation items */
  navigationGroups?: RouteGroup[];
  /** Footer content configuration */
  footer?: SidebarFooterConfig;
  /** Whether to show the footer (defaults: true for 'default', false for 'assistant') */
  showFooter?: boolean;
  /** Pixel width when expanded (desktop) */
  width?: number;
}

// ─────────────────────────────────────────────────────────────────────────────
// Compound Component Context
// ─────────────────────────────────────────────────────────────────────────────

interface SidebarContextValue {
  expanded: boolean;
  isMobileViewport: boolean;
  onToggle: () => void;
  navigate: (path: string) => void;
  location: { pathname: string };
  width: number;
}

const SidebarContext = createContext<SidebarContextValue | null>(null);

function useSidebarContext() {
  const ctx = useContext(SidebarContext);
  if (!ctx) {
    throw new Error('Sidebar compound components must be used within <Sidebar.Root>');
  }
  return ctx;
}

// ─────────────────────────────────────────────────────────────────────────────
// Compound Sub-components
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Root container for the Sidebar. Provides context to all sub-components.
 * Use this when building a fully custom sidebar layout.
 *
 * @example
 * <Sidebar.Root expanded={expanded} onToggle={toggle} width={280}>
 *   <Sidebar.Header logo={<MyLogo />} />
 *   <Sidebar.Nav navigationGroups={groups} />
 *   <Sidebar.Footer user={user} onLogout={logout} />
 * </Sidebar.Root>
 */
function SidebarRoot({
  expanded: expandedProp,
  onToggle: onToggleProp,
  navigate: navigateProp,
  location: locationProp,
  width: widthProp,
  children,
  className,
}: {
  expanded?: boolean;
  onToggle?: () => void;
  navigate?: (path: string) => void;
  location?: { pathname: string };
  width?: number;
  children: React.ReactNode;
  className?: string;
}) {
  const layoutContext = useOptionalLayout();
  const [localExpanded, setLocalExpanded] = useState(false);
  const [isMobileViewport, setIsMobileViewport] = useState(false);

  const expanded =
    expandedProp !== undefined ? expandedProp : (layoutContext?.sidebarExpanded ?? localExpanded);
  const onToggle =
    onToggleProp || layoutContext?.toggleSidebar || (() => setLocalExpanded(prev => !prev));
  const width = widthProp !== undefined ? widthProp : (layoutContext?.sidebarWidth ?? 280);
  const navigate =
    navigateProp ||
    ((path: string) => {
      if (typeof window !== 'undefined') window.location.href = path;
    });
  const location =
    locationProp || (typeof window !== 'undefined' ? window.location : { pathname: '/' });

  useEffect(() => {
    const checkViewport = () => setIsMobileViewport(window.innerWidth < 768);
    checkViewport();
    window.addEventListener('resize', checkViewport);
    return () => window.removeEventListener('resize', checkViewport);
  }, []);

  return (
    <SidebarContext.Provider
      value={{ expanded, isMobileViewport, onToggle, navigate, location, width }}
    >
      <TooltipProvider delayDuration={300}>
        <style>{`
          @media (max-width: 767px) {
            [style*="padding-left"].flex-1,
            [style*="paddingLeft"].flex-1 {
              padding-left: 0 !important;
            }
          }
        `}</style>
        <div
          className={cn(
            'bg-sidebar text-sidebar-foreground transition-all duration-300 ease-in-out flex flex-col z-50',
            expanded
              ? 'fixed inset-0 md:fixed md:inset-y-0 md:left-0'
              : 'fixed inset-y-0 left-0 w-20 -translate-x-full md:translate-x-0',
            className
          )}
          style={expanded && !isMobileViewport ? { width: `${width}px` } : undefined}
        >
          {children}
        </div>
      </TooltipProvider>
    </SidebarContext.Provider>
  );
}

/**
 * Toggle button + logo header area for the Sidebar.
 */
function SidebarHeader({
  logo,
  logoCollapsed,
}: {
  logo?: React.ReactNode;
  logoCollapsed?: React.ReactNode;
}) {
  const { expanded, onToggle } = useSidebarContext();
  const { t } = useTranslation();

  return (
    <>
      {/* Menu Toggle Button */}
      <div className="flex-shrink-0 p-[14px] pt-[13px] pr-[14px] pb-[12px] pl-[14px]">
        <button
          onClick={onToggle}
          className="w-full h-10 flex items-center gap-3 px-3 justify-center rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground"
          aria-label={expanded ? t('sidebar.collapse') : t('sidebar.expand')}
          aria-expanded={expanded}
          aria-controls="sidebar-nav"
        >
          {expanded ? <ArrowLeft className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
        </button>
      </div>

      {/* Logo */}
      <div className="flex-shrink-0 px-4 py-4">
        <div className="flex items-center h-10 justify-center">
          <div className="flex items-center justify-center flex-shrink-0">
            {expanded
              ? logo || <XerticaLogo className="h-5 w-auto" variant="white" />
              : logoCollapsed || <XerticaXLogo className="h-5 w-auto" variant="white" />}
          </div>
        </div>
      </div>
    </>
  );
}

/**
 * Accordion inline para "mais opções" no mobile.
 * Abre abaixo do botão, igual ao padrão dos subitens mobile.
 */
function OverflowGroupsAccordion({
  expanded,
  overflowGroups,
  location,
  handleNavigate,
  moreOptionsLabel,
  onOpenChange,
}: {
  expanded: boolean;
  overflowGroups: RouteGroup[];
  location: { pathname: string };
  handleNavigate: (path: string) => void;
  moreOptionsLabel: string;
  onOpenChange?: (open: boolean) => void;
}) {
  const [isOpen, setIsOpen] = useState(false);

  const toggle = () => {
    const next = !isOpen;
    setIsOpen(next);
    onOpenChange?.(next);
  };

  return (
    <div>
      <button
        onClick={toggle}
        className={cn(
          'w-full h-10 flex items-center rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground',
          expanded ? 'gap-3 px-3 justify-start' : 'justify-center px-0'
        )}
        aria-expanded={isOpen}
        aria-label={moreOptionsLabel}
      >
        <MoreVertical className="w-5 h-5 flex-shrink-0" />
        {expanded && (
          <>
            <span className="truncate flex-1 text-sidebar-foreground text-left">
              {moreOptionsLabel}
            </span>
            <ChevronRight
              className={cn('w-4 h-4 flex-shrink-0 transition-transform duration-200', isOpen && 'rotate-90')}
            />
          </>
        )}
      </button>
      <AnimatePresence initial={false}>
        {isOpen && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="overflow-hidden"
          >
            <div className="mt-1 space-y-3">
              {overflowGroups.map(group => {
                const GroupIcon = group.icon;
                return (
                  <div key={group.id}>
                    {(group.label || GroupIcon) && expanded && (
                      <div className="px-3 mb-1 flex items-center gap-2">
                        {GroupIcon &&
                          (React.isValidElement(GroupIcon) ? (
                            GroupIcon
                          ) : (
                            <GroupIcon className="h-3 w-3 text-sidebar-foreground/60" />
                          ))}
                        {group.label && (
                          <span className="text-xs font-semibold uppercase tracking-wider text-sidebar-foreground/60">
                            {group.label}
                          </span>
                        )}
                      </div>
                    )}
                    <div className="space-y-0.5">
                      {group.items.map(item => {
                        const Icon = item.icon;
                        const isActive =
                          location.pathname === item.path ||
                          location.pathname.startsWith(item.path + '/');
                        return (
                          <button
                            key={item.path}
                            onClick={() => handleNavigate(item.path)}
                            className={cn(
                              'w-full h-9 flex items-center gap-2.5 rounded-[var(--radius-button)] transition-all duration-200 text-left text-sm',
                              expanded ? 'px-3' : 'justify-center px-0',
                              isActive
                                ? 'bg-sidebar-foreground/15 text-sidebar-foreground'
                                : 'text-sidebar-foreground/70 hover:bg-sidebar-foreground/10 hover:text-sidebar-foreground'
                            )}
                          >
                            {Icon && <Icon className="w-4 h-4 flex-shrink-0" />}
                            {expanded && <span className="truncate">{item.label}</span>}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

/**
 * Navigation area for the Sidebar (default variant).
 * Renders grouped or flat navigation items with overflow handling.
 */
function SidebarNav({
  navigationGroups = [],
  routes = [],
  variant = 'default',
}: {
  navigationGroups?: RouteGroup[];
  routes?: RouteConfig[];
  variant?: 'default' | 'assistant';
}) {
  const { expanded, isMobileViewport, navigate, location, onToggle } = useSidebarContext();
  const { t } = useTranslation();
  const navRef = useRef<HTMLDivElement>(null);
  const [localActiveItem, setLocalActiveItem] = useState<string | null>(null);
  const [hasOverflow, setHasOverflow] = useState(false);
  const [visibleItems, setVisibleItems] = useState<NavigationItem[]>([]);
  const [overflowItems, setOverflowItems] = useState<NavigationItem[]>([]);
  const [openSubmenus, setOpenSubmenus] = useState<Set<string>>(new Set());
  const [hasGroupOverflow, setHasGroupOverflow] = useState(false);
  const [visibleGroups, setVisibleGroups] = useState<RouteGroup[]>([]);
  const [overflowGroups, setOverflowGroups] = useState<RouteGroup[]>([]);
  const [isOverflowAccordionOpen, setIsOverflowAccordionOpen] = useState(false);

  const toggleSubmenu = (path: string) => {
    setOpenSubmenus(prev => {
      const next = new Set(prev);
      if (next.has(path)) {
        next.delete(path);
      } else {
        next.add(path);
      }
      return next;
    });
  };

  const labelTranslations = useMemo<Record<string, string>>(
    () => ({
      home: 'Início',
      dashboard: 'Painel',
      components: 'Componentes',
    }),
    []
  );

  const navigationItems = useMemo<NavigationItem[]>(
    () =>
      (routes || []).map(route => ({
        ...route,
        label: labelTranslations[route.label.toLowerCase()] || route.label,
        active: location.pathname === route.path || location.pathname.startsWith(route.path + '/'),
        children: route.children,
      })),
    [routes, location.pathname, labelTranslations]
  );

  useEffect(() => {
    if (typeof window === 'undefined') return;
    const checkOverflow = () => {
      if (!navRef.current) return;
      if (variant === 'assistant') return;
      const navHeight = navRef.current.clientHeight;
      const itemHeight = 44;
      const maxVisibleItems = Math.floor(navHeight / itemHeight);
      if (navigationItems.length > maxVisibleItems) {
        setHasOverflow(true);
        setVisibleItems(navigationItems.slice(0, maxVisibleItems - 1));
        setOverflowItems(navigationItems.slice(maxVisibleItems - 1));
      } else {
        setHasOverflow(false);
        setVisibleItems(navigationItems);
        setOverflowItems([]);
      }
    };
    checkOverflow();
    window.addEventListener('resize', checkOverflow);
    return () => window.removeEventListener('resize', checkOverflow);
  }, [navigationItems.length, variant]);

  useEffect(() => {
    if (typeof window === 'undefined') return;
    if (variant === 'assistant') return;
    if (!navigationGroups || navigationGroups.length === 0) return;

    const checkGroupOverflow = () => {
      if (!navRef.current) return;

      const containerHeight = navRef.current.clientHeight;
      const itemHeight = 40;
      const groupHeaderHeight = 32;
      const groupSpacing = 12;
      const moreButtonHeight = 44;
      const padding = 32;

      let currentHeight = padding;
      let visibleCount = 0;

      for (let i = 0; i < navigationGroups.length; i++) {
        const group = navigationGroups[i];
        let groupHeight = 0;
        if (group.label) groupHeight += groupHeaderHeight;
        groupHeight += group.items.length * itemHeight;
        if (i > 0) groupHeight += groupSpacing;

        const wouldExceed =
          currentHeight + groupHeight + (visibleCount < navigationGroups.length - 1 ? moreButtonHeight : 0) >
          containerHeight;

        if (wouldExceed && visibleCount > 0) break;

        currentHeight += groupHeight;
        visibleCount++;
      }

      if (visibleCount < navigationGroups.length) {
        setHasGroupOverflow(true);
        setVisibleGroups(navigationGroups.slice(0, visibleCount));
        setOverflowGroups(navigationGroups.slice(visibleCount));
      } else {
        setHasGroupOverflow(false);
        setVisibleGroups(navigationGroups);
        setOverflowGroups([]);
      }
    };

    checkGroupOverflow();
    window.addEventListener('resize', checkGroupOverflow);
    return () => window.removeEventListener('resize', checkGroupOverflow);
  }, [navigationGroups, expanded, variant]);

  const handleNavigate = (path: string) => {
    setLocalActiveItem(path);
    navigate(path);
    if (typeof window !== 'undefined' && window.innerWidth < 768) {
      onToggle();
    }
  };

  const toNavItem = (route: RouteConfig): NavigationItem => ({
    path: route.path,
    label: labelTranslations[route.label.toLowerCase()] || route.label,
    icon: route.icon,
    active: location.pathname === route.path || location.pathname.startsWith(route.path + '/'),
    children: route.children,
    actions: route.actions,
  });

  const renderActionItems = (actions: ActionMenuItem[]): React.ReactNode => {
    return actions.map((action, idx) => {
      const Icon = action.icon;
      if (action.children && action.children.length > 0) {
        return (
          <DropdownMenuSub key={idx}>
            <DropdownMenuSubTrigger>
              {Icon && <Icon className="mr-2 h-4 w-4" />}
              <span>{action.label}</span>
            </DropdownMenuSubTrigger>
            <DropdownMenuPortal>
              <DropdownMenuSubContent className="w-48 bg-popover border-border">
                {renderActionItems(action.children)}
              </DropdownMenuSubContent>
            </DropdownMenuPortal>
          </DropdownMenuSub>
        );
      }
      return (
        <DropdownMenuItem
          key={idx}
          className={cn(
            'flex items-center gap-2',
            action.variant === 'destructive' ? 'text-destructive focus:text-destructive' : ''
          )}
          onClick={e => {
            e.stopPropagation();
            action.onClick?.(null);
          }}
        >
          {Icon && <Icon className="h-4 w-4 flex-shrink-0" />}
          <span>{action.label}</span>
        </DropdownMenuItem>
      );
    });
  };

  const renderAssistantActionMenu = (actions?: ActionMenuItem[], isHeader: boolean = false) => {
    if (!actions || actions.length === 0) return null;
    return (
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="ghost"
            size="icon"
            className={cn(
              'h-8 w-8 text-sidebar-foreground/80 hover:bg-sidebar-foreground/20 hover:text-sidebar-foreground rounded-full transition-all',
              !isHeader && 'opacity-0 group-hover/item:opacity-100'
            )}
            aria-label={t('sidebar.moreOptions')}
          >
            <MoreVertical className="h-4 w-4" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-48 bg-popover border-border p-1">
          {renderActionItems(actions)}
        </DropdownMenuContent>
      </DropdownMenu>
    );
  };

  const renderDefaultItem = (item: NavigationItem) => {
    const Icon = item.icon;
    const hasChildren = item.children && item.children.length > 0;
    const activeClass = item.active
      ? 'bg-sidebar-foreground/15 text-sidebar-foreground shadow-sm'
      : 'text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground';

    if (!expanded) {
      return (
        <Tooltip key={item.path}>
          <TooltipTrigger asChild>
            <button
              onClick={() => handleNavigate(item.path)}
              className={cn(
                'w-full h-10 flex items-center justify-center px-0 rounded-[var(--radius-button)] transition-all duration-200',
                activeClass
              )}
              aria-label={item.label}
            >
              {Icon && <Icon className="w-5 h-5 flex-shrink-0" />}
            </button>
          </TooltipTrigger>
          <SidebarTooltipContent side="right" sideOffset={0}>
            <p>{item.label}</p>
          </SidebarTooltipContent>
        </Tooltip>
      );
    }

    // Mobile: accordion inline — subitens abrem abaixo do item pai
    if (isMobileViewport && hasChildren) {
      const isOpen = openSubmenus.has(item.path);
      return (
        <div key={item.path}>
          <div
            className={cn(
              'group/item flex items-center w-full h-10 rounded-[var(--radius-button)] transition-all duration-200',
              activeClass
            )}
          >
            <button
              onClick={() => handleNavigate(item.path)}
              className="flex items-center gap-3 px-3 flex-1 h-full min-w-0 text-left"
            >
              {Icon && <Icon className="w-5 h-5 flex-shrink-0" />}
              <span className="truncate flex-1">{item.label}</span>
            </button>
            <button
              onClick={e => {
                e.stopPropagation();
                toggleSubmenu(item.path);
              }}
              className="h-full px-2 pr-2.5 flex items-center justify-center text-sidebar-foreground/40 hover:text-sidebar-foreground transition-colors"
              aria-label={t('sidebar.submenu', { label: item.label })}
              aria-expanded={isOpen}
            >
              <ChevronRight
                className={cn('w-4 h-4 transition-transform duration-200', isOpen && 'rotate-90')}
              />
            </button>
          </div>
          <AnimatePresence initial={false}>
            {isOpen && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                transition={{ duration: 0.2 }}
                className="overflow-hidden"
              >
                <div className="ml-4 mt-0.5 mb-0.5 space-y-0.5">
                  {item.children!.map(child => {
                    const ChildIcon = child.icon;
                    const isChildActive =
                      location.pathname === child.path ||
                      location.pathname.startsWith(child.path + '/');
                    return (
                      <button
                        key={child.path}
                        onClick={() => handleNavigate(child.path)}
                        className={cn(
                          'w-full h-9 flex items-center gap-2.5 px-3 rounded-[var(--radius-button)] transition-all duration-200 text-left',
                          isChildActive
                            ? 'bg-sidebar-foreground/15 text-sidebar-foreground'
                            : 'text-sidebar-foreground/70 hover:bg-sidebar-foreground/10 hover:text-sidebar-foreground'
                        )}
                      >
                        {ChildIcon && <ChildIcon className="h-4 w-4 flex-shrink-0" />}
                        <span className="truncate text-sm">{child.label}</span>
                      </button>
                    );
                  })}
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      );
    }

    // Desktop: dropdown lateral (comportamento original)
    return (
      <div
        key={item.path}
        className={cn(
          'group/item flex items-center w-full h-10 rounded-[var(--radius-button)] transition-all duration-200',
          activeClass
        )}
      >
        <button
          onClick={() => handleNavigate(item.path)}
          className="flex items-center gap-3 px-3 flex-1 h-full min-w-0 text-left"
        >
          {Icon && <Icon className="w-5 h-5 flex-shrink-0" />}
          <span className="truncate flex-1">{item.label}</span>
        </button>

        {hasChildren && (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button
                onClick={e => e.stopPropagation()}
                className="h-full px-2 pr-2.5 flex items-center justify-center text-sidebar-foreground/40 hover:text-sidebar-foreground transition-colors"
                aria-label={t('sidebar.submenu', { label: item.label })}
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent
              side="right"
              align="start"
              className="w-48 bg-popover border-border p-1"
            >
              {item.children!.map(child => {
                const ChildIcon = child.icon;
                const isChildActive =
                  location.pathname === child.path ||
                  location.pathname.startsWith(child.path + '/');
                return (
                  <DropdownMenuItem
                    key={child.path}
                    onClick={() => handleNavigate(child.path)}
                    className={cn(
                      'flex items-center gap-2 cursor-pointer',
                      isChildActive && 'bg-accent text-accent-foreground'
                    )}
                  >
                    {ChildIcon && <ChildIcon className="h-4 w-4 flex-shrink-0" />}
                    <span className="truncate">{child.label}</span>
                  </DropdownMenuItem>
                );
              })}
            </DropdownMenuContent>
          </DropdownMenu>
        )}
      </div>
    );
  };

  const renderDefaultGroup = (group: RouteGroup) => {
    const GroupIcon = group.icon;
    if (!expanded) {
      return (
        <div key={group.id} className="space-y-1">
          {group.items.map(item => renderDefaultItem(toNavItem(item)))}
        </div>
      );
    }
    return (
      <div key={group.id}>
        {(group.label || GroupIcon) && (
          <div className="px-3 mb-1 flex items-center gap-2">
            {GroupIcon &&
              (React.isValidElement(GroupIcon) ? (
                GroupIcon
              ) : (
                <GroupIcon className="h-3 w-3 text-sidebar-foreground/80" />
              ))}
            {group.label && (
              <span className="text-xs font-semibold uppercase tracking-wider text-sidebar-foreground/80">
                {group.label}
              </span>
            )}
          </div>
        )}
        <div className="space-y-1">
          {group.items.map(item => renderDefaultItem(toNavItem(item)))}
        </div>
      </div>
    );
  };

  const renderAssistantGroup = (group: RouteGroup) => {
    const isAnyItemActive = group.items.some(
      item => location.pathname === item.path || location.pathname.startsWith(item.path + '/')
    );
    const GroupIcon = group.icon;

    if (!expanded) {
      if (!GroupIcon) return null;
      return (
        <div key={group.id} className="py-2 flex justify-center">
          <Tooltip>
            <TooltipTrigger asChild>
              <button
                onClick={() => onToggle()}
                aria-label={group.label}
                className={cn(
                  'h-10 w-10 flex items-center justify-center rounded-[var(--radius-button)] transition-all duration-200',
                  isAnyItemActive
                    ? 'bg-sidebar-foreground/15 text-sidebar-foreground shadow-sm'
                    : 'text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground'
                )}
              >
                {React.isValidElement(GroupIcon) ? GroupIcon : <GroupIcon className="h-5 w-5" />}
              </button>
            </TooltipTrigger>
            <SidebarTooltipContent side="right">
              <p>{group.label}</p>
            </SidebarTooltipContent>
          </Tooltip>
        </div>
      );
    }

    return (
      <div key={group.id} className="py-2 group">
        {(group.label || group.icon) && (
          <div className="flex items-center justify-between px-3 mb-1">
            <div className="flex items-center gap-2 text-sidebar-foreground/80 text-xs font-semibold uppercase tracking-wider">
              {GroupIcon && (
                <div className="flex items-center justify-center">
                  {React.isValidElement(GroupIcon) ? GroupIcon : <GroupIcon className="h-4 w-4" />}
                </div>
              )}
              {group.label && <span>{group.label}</span>}
            </div>
            {renderAssistantActionMenu(group.actions, true)}
          </div>
        )}
        <div className="space-y-1">
          {group.items.map(item => {
            const isRouteActive =
              location.pathname === item.path || location.pathname.startsWith(item.path + '/');
            const isActive = isRouteActive || localActiveItem === item.path;
            const Icon = item.icon;
            return (
              <div
                key={item.path}
                className={`group/item flex items-start justify-between px-3 min-h-[36px] py-2.5 rounded-[var(--radius-button)] cursor-pointer transition-all duration-200 ${isActive ? 'bg-sidebar-foreground/15 text-sidebar-foreground' : 'text-sidebar-foreground/80 hover:bg-sidebar-foreground/10 hover:text-sidebar-foreground'}`}
                onClick={() => handleNavigate(item.path)}
              >
                <div className="flex flex-col min-w-0 flex-1">
                  <div className="flex items-center gap-3 overflow-hidden h-5">
                    {Icon && (
                      <div className="w-4 h-4 flex-shrink-0 flex items-center justify-center">
                        {React.isValidElement(Icon) ? Icon : <Icon className="w-4 h-4" />}
                      </div>
                    )}
                    <span className="truncate text-sm font-medium leading-none">{item.label}</span>
                  </div>
                  {isActive && item.description && (
                    <div className="text-[11px] text-sidebar-foreground/60 mt-1.5 animate-in fade-in slide-in-from-top-1 duration-200">
                      {item.description}
                    </div>
                  )}
                </div>
                <div className="h-5 flex items-center ml-1">
                  {renderAssistantActionMenu(item.actions)}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  if (variant === 'assistant') {
    return (
      <div className="flex-1 min-h-0 overflow-hidden">
        <div
          className="h-full px-4"
          style={{ overflowY: 'auto', overflowX: 'hidden' }}
        >
          {navigationGroups.map(group => renderAssistantGroup(group))}
        </div>
      </div>
    );
  }

  if (isMobileViewport && isOverflowAccordionOpen) {
    return (
      <div className="flex-1 min-h-0 overflow-hidden">
        <div
          className="h-full"
          style={{ overflowY: 'auto', overflowX: 'hidden' }}
        >
          <nav
            id="sidebar-nav"
            aria-label={t('sidebar.mainNavigation')}
            className="px-4 py-4"
            ref={navRef}
          >
            {navigationGroups && navigationGroups.length > 0 ? (
              <div className="space-y-3">
                {(hasGroupOverflow ? visibleGroups : navigationGroups).map(group => (
                  <React.Fragment key={group.id}>{renderDefaultGroup(group)}</React.Fragment>
                ))}
                {hasGroupOverflow && (
                  <OverflowGroupsAccordion
                    expanded={expanded}
                    overflowGroups={overflowGroups}
                    location={location}
                    handleNavigate={handleNavigate}
                    moreOptionsLabel={t('sidebar.moreOptions')}
                    onOpenChange={setIsOverflowAccordionOpen}
                  />
                )}
              </div>
            ) : (
              <div className="space-y-1">
                {(hasOverflow ? visibleItems : navigationItems).map(item => renderDefaultItem(item))}
                {hasOverflow && (
                  <Popover>
                    <PopoverTrigger asChild>
                      <button
                        className={
                          expanded
                            ? 'w-full h-10 flex items-center gap-3 px-3 justify-start rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground'
                            : 'w-full h-10 flex items-center justify-center px-0 rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground'
                        }
                        aria-label={t('sidebar.moreOptions')}
                      >
                        <MoreVertical className="w-5 h-5 flex-shrink-0" />
                        {expanded && (
                          <span className="truncate text-sidebar-foreground">
                            {t('sidebar.moreOptions')}
                          </span>
                        )}
                      </button>
                    </PopoverTrigger>
                    <PopoverContent
                      side="right"
                      align="start"
                      className="w-56 p-2 bg-popover border border-border rounded-[var(--radius-card)] shadow-lg"
                      sideOffset={8}
                    >
                      <div className="space-y-1">
                        {overflowItems.map(item => {
                          const Icon = item.icon;
                          return (
                            <button
                              key={item.path}
                              onClick={() => handleNavigate(item.path)}
                              className="w-full h-9 flex items-center gap-2 px-3 rounded-[var(--radius-button)] transition-all duration-200 text-popover-foreground/80 hover:bg-accent hover:text-accent-foreground text-left"
                            >
                              {Icon && <Icon className="w-4 h-4 flex-shrink-0" />}
                              <span className="truncate">{item.label}</span>
                            </button>
                          );
                        })}
                      </div>
                    </PopoverContent>
                  </Popover>
                )}
              </div>
            )}
          </nav>
        </div>
      </div>
    );
  }

  return (
    <div className="flex-1 min-h-0 overflow-hidden">
      <nav
        id="sidebar-nav"
        aria-label={t('sidebar.mainNavigation')}
        className="h-full px-4 py-4 overflow-hidden"
        ref={navRef}
      >
        {navigationGroups && navigationGroups.length > 0 ? (
          <div className="space-y-3">
            {(hasGroupOverflow ? visibleGroups : navigationGroups).map(group => (
              <React.Fragment key={group.id}>{renderDefaultGroup(group)}</React.Fragment>
            ))}
            {hasGroupOverflow && (
              isMobileViewport ? (
                // Mobile: accordion inline abre abaixo, igual aos subitens
                <OverflowGroupsAccordion
                  expanded={expanded}
                  overflowGroups={overflowGroups}
                  location={location}
                  handleNavigate={handleNavigate}
                  moreOptionsLabel={t('sidebar.moreOptions')}
                  onOpenChange={setIsOverflowAccordionOpen}
                />
              ) : (
                // Desktop: popover lateral direito
                <Popover>
                  <PopoverTrigger asChild>
                    <button
                      className={
                        expanded
                          ? 'w-full h-10 flex items-center gap-3 px-3 justify-start rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground'
                          : 'w-full h-10 flex items-center justify-center px-0 rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground'
                      }
                      aria-label={t('sidebar.moreOptions')}
                    >
                      <MoreVertical className="w-5 h-5 flex-shrink-0" />
                      {expanded && (
                        <span className="truncate text-sidebar-foreground">
                          {t('sidebar.moreOptions')}
                        </span>
                      )}
                    </button>
                  </PopoverTrigger>
                  <PopoverContent
                    side="right"
                    align="start"
                    className="w-56 p-2 bg-popover border border-border rounded-[var(--radius-card)] shadow-lg"
                    sideOffset={8}
                  >
                    <div className="space-y-3">
                      {overflowGroups.map(group => {
                        const GroupIcon = group.icon;
                        return (
                          <div key={group.id}>
                            {(group.label || GroupIcon) && (
                              <div className="px-2 mb-1 flex items-center gap-2">
                                {GroupIcon &&
                                  (React.isValidElement(GroupIcon) ? (
                                    GroupIcon
                                  ) : (
                                    <GroupIcon className="h-3 w-3 text-popover-foreground/60" />
                                  ))}
                                {group.label && (
                                  <span className="text-xs font-semibold uppercase tracking-wider text-popover-foreground/60">
                                    {group.label}
                                  </span>
                                )}
                              </div>
                            )}
                            <div className="space-y-1">
                              {group.items.map(item => {
                                const Icon = item.icon;
                                const isActive =
                                  location.pathname === item.path ||
                                  location.pathname.startsWith(item.path + '/');
                                return (
                                  <button
                                    key={item.path}
                                    onClick={() => handleNavigate(item.path)}
                                    className={cn(
                                      'w-full h-9 flex items-center gap-2 px-2 rounded-[var(--radius-button)] transition-all duration-200 text-left text-sm',
                                      isActive
                                        ? 'bg-accent text-accent-foreground font-medium'
                                        : 'text-popover-foreground/80 hover:bg-accent hover:text-accent-foreground'
                                    )}
                                  >
                                    {Icon && <Icon className="w-4 h-4 flex-shrink-0" />}
                                    <span className="truncate">{item.label}</span>
                                  </button>
                                );
                              })}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </PopoverContent>
                </Popover>
              )
            )}
          </div>
        ) : (
          <div className="space-y-1">
            {(hasOverflow ? visibleItems : navigationItems).map(item => renderDefaultItem(item))}
            {hasOverflow && (
              <Popover>
                <PopoverTrigger asChild>
                  <button
                    className={
                      expanded
                        ? 'w-full h-10 flex items-center gap-3 px-3 justify-start rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground'
                        : 'w-full h-10 flex items-center justify-center px-0 rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground'
                    }
                    aria-label={t('sidebar.moreOptions')}
                  >
                    <MoreVertical className="w-5 h-5 flex-shrink-0" />
                    {expanded && (
                      <span className="truncate text-sidebar-foreground">
                        {t('sidebar.moreOptions')}
                      </span>
                    )}
                  </button>
                </PopoverTrigger>
                <PopoverContent
                  side="right"
                  align="start"
                  className="w-56 p-2 bg-popover border border-border rounded-[var(--radius-card)] shadow-lg"
                  sideOffset={8}
                >
                  <div className="space-y-1">
                    {overflowItems.map(item => {
                      const Icon = item.icon;
                      return (
                        <button
                          key={item.path}
                          onClick={() => handleNavigate(item.path)}
                          className="w-full h-9 flex items-center gap-2 px-3 rounded-[var(--radius-button)] transition-all duration-200 text-popover-foreground/80 hover:bg-accent hover:text-accent-foreground text-left"
                        >
                          {Icon && <Icon className="w-4 h-4 flex-shrink-0" />}
                          <span className="truncate">{item.label}</span>
                        </button>
                      );
                    })}
                  </div>
                </PopoverContent>
              </Popover>
            )}
          </div>
        )}
      </nav>
    </div>
  );
}

/**
 * Assistant-specific search + fixed area header for the Sidebar.
 */
function SidebarSearch({
  fixedArea,
  search,
}: {
  fixedArea?: SidebarFixedAreaConfig;
  search?: SidebarSearchConfig;
}) {
  const { expanded } = useSidebarContext();
  const { t } = useTranslation();
  const [isFilterOpen, setIsFilterOpen] = useState(false);

  if (!((fixedArea && fixedArea.show) || (search && search.show))) return null;

  return (
    <div className="flex-shrink-0 px-4 pb-4 space-y-4 border-b border-sidebar-border/30 mb-2">
      {fixedArea?.show && fixedArea.content && expanded && (
        <div className="animate-in fade-in slide-in-from-top-1 duration-300">
          {fixedArea.content}
        </div>
      )}
      {search?.show && expanded && (
        <>
          <div className="flex items-center gap-2">
            <div className="relative flex-1">
              <SearchIcon className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-sidebar-foreground/50" />
              <Input
                type="text"
                placeholder={search.placeholder || t('sidebar.searchPlaceholder')}
                aria-label={search.placeholder || t('sidebar.searchPlaceholder')}
                value={search.value}
                onChange={e => search.onChange?.(e.target.value)}
                className="w-full h-9 bg-sidebar-foreground/10 border-sidebar-border text-sidebar-foreground placeholder:text-sidebar-foreground/50 pl-9 focus-visible:ring-1 focus-visible:ring-sidebar-foreground/30 focus-visible:ring-offset-0"
              />
            </div>
            {search.filter?.show && search.filter.content && (
              <Button
                variant="ghost"
                size="icon"
                onClick={() => setIsFilterOpen(!isFilterOpen)}
                className={cn(
                  'h-9 w-9 text-sidebar-foreground transition-all duration-200',
                  isFilterOpen ? 'bg-sidebar-foreground/20' : 'hover:bg-sidebar-foreground/15'
                )}
                aria-label={isFilterOpen ? t('sidebar.closeFilters') : t('sidebar.openFilters')}
              >
                {search.filter.icon || <Filter className="h-4 w-4" />}
              </Button>
            )}
          </div>
          <AnimatePresence>
            {isFilterOpen && search.filter?.show && search.filter.content && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                transition={{ duration: 0.2 }}
                className="overflow-hidden"
              >
                <div className="pt-2 border-t border-sidebar-border/20">
                  {search.filter.content}
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </>
      )}
      {!expanded && (fixedArea?.show || search?.show) && (
        <div className="flex flex-col items-center gap-4 py-2">
          {fixedArea?.show && fixedArea.icon && (
            <Tooltip>
              <TooltipTrigger asChild>
                <button
                  onClick={() => fixedArea.onClick?.()}
                  className="h-10 w-10 flex items-center justify-center rounded-[var(--radius-button)] bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 transition-all"
                  aria-label={t('assistant.newConversation')}
                >
                  {React.isValidElement(fixedArea.icon) ? (
                    fixedArea.icon
                  ) : (
                    <fixedArea.icon className="h-5 w-5" />
                  )}
                </button>
              </TooltipTrigger>
              <SidebarTooltipContent side="right">
                {t('assistant.newConversation')}
              </SidebarTooltipContent>
            </Tooltip>
          )}
          {search?.show && (
            <Tooltip>
              <TooltipTrigger asChild>
                <button
                  className="h-10 w-10 flex items-center justify-center rounded-[var(--radius-button)] text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground"
                  aria-label={t('sidebar.search')}
                >
                  <SearchIcon className="h-5 w-5" />
                </button>
              </TooltipTrigger>
              <SidebarTooltipContent side="right">{t('sidebar.search')}</SidebarTooltipContent>
            </Tooltip>
          )}
        </div>
      )}
    </div>
  );
}

/**
 * Footer area for the Sidebar with user info, settings, and logout.
 */
function SidebarFooter({
  user,
  onLogout = () => {},
  onSettingsClick,
  showUser = true,
  showSettings = true,
  showLogout = true,
}: {
  user?: { name?: string; email?: string; avatar?: string } | null;
  onLogout?: () => void;
  onSettingsClick?: () => void;
  showUser?: boolean;
  showSettings?: boolean;
  showLogout?: boolean;
}) {
  const { expanded, navigate, location, onToggle } = useSidebarContext();
  const { t } = useTranslation();
  const isSettingsActive = location.pathname === '/settings';

  const handleSettingsClick = () => {
    if (onSettingsClick) {
      onSettingsClick();
    } else {
      navigate('/settings');
    }
    if (typeof window !== 'undefined' && window.innerWidth < 768) {
      onToggle();
    }
  };

  return (
    <div className="flex-shrink-0 p-4 space-y-2">
      {showUser &&
        (!expanded ? (
          <Tooltip>
            <TooltipTrigger asChild>
              <button
                className="w-full h-10 flex items-center justify-center px-0 rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground"
                aria-label={t('sidebar.userProfile')}
              >
                <Avatar className="w-7 h-7 flex-shrink-0">
                  <AvatarImage src={user?.avatar} alt={user?.name || 'User'} />
                  <AvatarFallback className="bg-sidebar-foreground/15 text-sidebar-foreground text-xs">
                    {user?.name ? user.name.charAt(0).toUpperCase() : 'U'}
                  </AvatarFallback>
                </Avatar>
              </button>
            </TooltipTrigger>
            <SidebarTooltipContent side="right" sideOffset={0}>
              <p>{user?.name || t('sidebar.profile')}</p>
            </SidebarTooltipContent>
          </Tooltip>
        ) : (
          <button className="w-full h-10 flex items-center gap-3 px-3 justify-start rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground">
            <Avatar className="w-7 h-7 flex-shrink-0">
              <AvatarImage src={user?.avatar} alt={user?.name || 'User'} />
              <AvatarFallback className="bg-sidebar-foreground/15 text-sidebar-foreground text-xs">
                {user?.name ? user.name.charAt(0).toUpperCase() : 'U'}
              </AvatarFallback>
            </Avatar>
            <span className="text-sidebar-foreground truncate">
              {user?.name || t('sidebar.profile')}
            </span>
          </button>
        ))}

      {showSettings &&
        (!expanded ? (
          <Tooltip>
            <TooltipTrigger asChild>
              <button
                onClick={handleSettingsClick}
                className={cn(
                  'w-full h-10 flex items-center justify-center px-0 rounded-[var(--radius-button)] transition-all duration-200',
                  isSettingsActive
                    ? 'bg-sidebar-foreground/15 text-sidebar-foreground shadow-sm'
                    : 'text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground'
                )}
                aria-label={t('nav.settings')}
              >
                <Settings className="w-5 h-5 flex-shrink-0" />
              </button>
            </TooltipTrigger>
            <SidebarTooltipContent side="right" sideOffset={0}>
              <p>{t('nav.settings')}</p>
            </SidebarTooltipContent>
          </Tooltip>
        ) : (
          <button
            onClick={handleSettingsClick}
            className={cn(
              'w-full h-10 flex items-center gap-3 px-3 justify-start rounded-[var(--radius-button)] transition-all duration-200',
              isSettingsActive
                ? 'bg-sidebar-foreground/15 text-sidebar-foreground shadow-sm'
                : 'text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground'
            )}
          >
            <Settings className="w-5 h-5 flex-shrink-0" />
            <span className="truncate text-sidebar-foreground">{t('nav.settings')}</span>
          </button>
        ))}

      {showLogout &&
        (!expanded ? (
          <Tooltip>
            <TooltipTrigger asChild>
              <button
                onClick={onLogout}
                className="w-full h-10 flex items-center justify-center px-0 rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground"
                aria-label={t('sidebar.logout')}
              >
                <LogOut className="w-5 h-5 flex-shrink-0" />
              </button>
            </TooltipTrigger>
            <SidebarTooltipContent side="right" sideOffset={0}>
              <p>{t('sidebar.logout')}</p>
            </SidebarTooltipContent>
          </Tooltip>
        ) : (
          <button
            onClick={onLogout}
            className="w-full h-10 flex items-center gap-3 px-3 justify-start rounded-[var(--radius-button)] transition-all duration-200 text-sidebar-foreground/80 hover:bg-sidebar-foreground/15 hover:text-sidebar-foreground"
          >
            <LogOut className="w-5 h-5 flex-shrink-0" />
            <span className="truncate text-sidebar-foreground">{t('sidebar.logout')}</span>
          </button>
        ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Main Sidebar component (backward-compatible monolithic API)
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Primary navigation sidebar component.
 *
 * @description
 * Manages desktop/mobile responsive navigation rendering with two variants:
 * - `"default"` — simple flat or grouped route list.
 * - `"assistant"` — advanced variant with fixed areas, search, filters, and grouped navigation.
 *
 * This component is autonomous: it works out-of-the-box using local state or
 * integrates automatically with `LayoutContext` if wrapped in `LayoutProvider`.
 *
 * For advanced customization, use the Compound Component API:
 * `<Sidebar.Root>`, `<Sidebar.Header>`, `<Sidebar.Search>`, `<Sidebar.Nav>`, `<Sidebar.Footer>`
 *
 * @ai-rules
 * 1. NEVER recreate the sidebar with raw Tailwind classes — always use this component.
 * 2. Use `variant="assistant"` for AI/tool sidebars; use `variant="default"` for standard navigation.
 * 3. Supports `Ctrl+B` keyboard shortcut automatically via `LayoutProvider`.
 */
export function Sidebar({
  expanded: expandedProp,
  onToggle: onToggleProp,
  user,
  onLogout = () => {},
  onSettingsClick,
  location: locationProp,
  navigate: navigateProp,
  routes,
  logo,
  logoCollapsed,
  variant = 'default',
  fixedArea,
  search,
  navigationGroups = [],
  footer,
  showFooter,
  width: widthProp,
}: SidebarProps) {
  const { showUser = true, showSettings = true, showLogout = true } = footer || {};

  const displayFooter = showFooter !== undefined ? showFooter : variant === 'default';

  return (
    <SidebarRoot
      expanded={expandedProp}
      onToggle={onToggleProp}
      navigate={navigateProp}
      location={locationProp}
      width={widthProp}
    >
      <SidebarHeader logo={logo} logoCollapsed={logoCollapsed} />

      {variant === 'assistant' && <SidebarSearch fixedArea={fixedArea} search={search} />}

      <SidebarNav navigationGroups={navigationGroups} routes={routes} variant={variant} />

      {displayFooter && (showUser || showSettings || showLogout) && (
        <SidebarFooter
          user={user}
          onLogout={onLogout}
          onSettingsClick={onSettingsClick}
          showUser={showUser}
          showSettings={showSettings}
          showLogout={showLogout}
        />
      )}
    </SidebarRoot>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Attach Compound Components to Sidebar namespace
// ─────────────────────────────────────────────────────────────────────────────

Sidebar.Root = SidebarRoot;
Sidebar.Header = SidebarHeader;
Sidebar.Search = SidebarSearch;
Sidebar.Nav = SidebarNav;
Sidebar.Footer = SidebarFooter;

// Re-export hook for headless usage
export { useSidebar } from './use-sidebar';
export type { UseSidebarProps } from './use-sidebar';
