// src/components/admin/layout/sidebar.tsx
"use client";

import { useState, useEffect, useRef, useMemo, useCallback, useSyncExternalStore } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { usePermissions } from "@/hooks/usePermissions";
import { motion, AnimatePresence } from "framer-motion";
import {
  LayoutDashboard,
  UserCog,
  Users,
  UserPlus,
  ShieldCheck,
  KeyRound,
  Languages,
  Ruler,
  FolderTree,
  SlidersHorizontal,
  ListChecks,
  Tags,
  Package,
  ShoppingBag,
  ShoppingCart,
  Heart,
  Ticket,
  Star,
  Landmark,
  Wallet,
  Inbox,
  Image as ImageIcon,
  FileText,
  Newspaper,
  Menu as MenuIcon,
  ScrollText,
  Settings,
  Settings2,
  Palette,
  List,
  ChevronDown,
  ChevronsLeft,
  ChevronsRight,
  Search,
  Store,
  X,
  type LucideIcon,
} from "lucide-react";
import { useAdminStore } from "@/store/adminStore";
import { useAdminMobileNav } from "@/store/adminMobileNavStore";

// ─── Icons ────────────────────────────────────────────────────────────────────
// One distinct lucide icon per nav item (the old inline-SVG map came from a
// different HRMS project and had no entry for most of these modules, so nearly
// every item silently fell back to the same "home" icon).

const ICONS: Record<string, LucideIcon> = {
  dashboard: LayoutDashboard,
  "employee-management": UserCog,
  "all-employees": Users,
  "add-employee": UserPlus,
  roles: ShieldCheck,
  permissions: KeyRound,
  languages: Languages,
  "unit-types": Ruler,
  categories: FolderTree,
  attributes: SlidersHorizontal,
  "attribute-options": ListChecks,
  "product-tags": Tags,
  products: Package,
  orders: ShoppingBag,
  cart: ShoppingCart,
  wishlist: Heart,
  coupons: Ticket,
  reviews: Star,
  "bank-accounts": Landmark,
  "withdrawal-requests": Wallet,
  "contact-messages": Inbox,
  banners: ImageIcon,
  pages: FileText,
  posts: Newspaper,
  menus: MenuIcon,
  users: Users,
  "audit-logs": ScrollText,
  setting: Settings,
  "general-setting": Settings2,
  "color-setting": Palette,
};

function ModuleIcon({ name, size = 18 }: { name: string; size?: number }) {
  const Icon = ICONS[name] ?? List;
  return <Icon size={size} strokeWidth={1.8} aria-hidden="true" />;
}

// ─── Types ────────────────────────────────────────────────────────────────────

interface ChildItemType {
  name: string;
  displayName: string;
  icon: string;
  route: string;
  requiredPermission: string;
}

interface NavItemType {
  name: string;
  displayName: string;
  icon: string;
  route?: string;
  requiredPermission: string;
  children?: ChildItemType[];
}

interface NavSectionType {
  name: string;
  title: string;
  items: NavItemType[];
}

// ─── Nav Config (categorized) ──────────────────────────────────────────────────
// Grouped by what an admin is doing rather than one long list, so the sidebar
// is scannable — and short enough sections that the mobile drawer isn't a wall.

const NAV_SECTIONS: NavSectionType[] = [
  {
    name: "overview",
    title: "Overview",
    items: [
      {
        name: "dashboard",
        displayName: "Dashboard",
        icon: "dashboard",
        route: "/dashboard",
        requiredPermission: "dashboard:read",
      },
    ],
  },
  {
    name: "sales",
    title: "Sales",
    items: [
      {
        name: "orders",
        displayName: "Orders",
        icon: "orders",
        route: "/admin/dashboard/orders",
        requiredPermission: "orders:read",
      },
      {
        name: "cart",
        displayName: "Customer Carts",
        icon: "cart",
        route: "/admin/dashboard/cart",
        requiredPermission: "cart:read",
      },
      {
        name: "wishlist",
        displayName: "Customer Wishlists",
        icon: "wishlist",
        route: "/admin/dashboard/wishlist",
        requiredPermission: "wishlist:read",
      },
      {
        name: "coupons",
        displayName: "Coupons",
        icon: "coupons",
        route: "/admin/dashboard/coupons",
        requiredPermission: "coupons:read",
      },
      {
        name: "bank-accounts",
        displayName: "Bank Accounts",
        icon: "bank-accounts",
        route: "/admin/dashboard/bank-accounts",
        requiredPermission: "bank_accounts:read",
      },
      {
        name: "withdrawal-requests",
        displayName: "Withdrawal Requests",
        icon: "withdrawal-requests",
        route: "/admin/dashboard/withdrawal-requests",
        requiredPermission: "withdrawal_requests:read",
      },
    ],
  },
  {
    name: "catalog",
    title: "Catalog",
    items: [
      {
        name: "products",
        displayName: "Products",
        icon: "products",
        route: "/admin/dashboard/products",
        requiredPermission: "product:read",
      },
      {
        name: "categories",
        displayName: "Categories",
        icon: "categories",
        route: "/admin/dashboard/categories",
        requiredPermission: "categories:read",
      },
      {
        name: "attributes",
        displayName: "Attributes",
        icon: "attributes",
        route: "/admin/dashboard/attributes",
        requiredPermission: "attributes:read",
      },
      {
        name: "attribute-options",
        displayName: "Attribute Options",
        icon: "attribute-options",
        route: "/admin/dashboard/attribute-options",
        requiredPermission: "attribute_options:read",
      },
      {
        name: "product-tags",
        displayName: "Product Tags",
        icon: "product-tags",
        route: "/admin/dashboard/product-tags",
        requiredPermission: "product_tags:read",
      },
      {
        name: "unit-types",
        displayName: "Unit Types",
        icon: "unit-types",
        route: "/admin/dashboard/system/unit-types",
        requiredPermission: "unit_types:read",
      },
    ],
  },
  {
    name: "customers",
    title: "Customers",
    items: [
      {
        name: "users",
        displayName: "Users",
        icon: "users",
        route: "/admin/dashboard/users",
        requiredPermission: "users:read",
      },
      {
        name: "reviews",
        displayName: "Reviews",
        icon: "reviews",
        route: "/admin/dashboard/reviews",
        requiredPermission: "reviews:read",
      },
      {
        name: "contact-messages",
        displayName: "Contact Messages",
        icon: "contact-messages",
        route: "/admin/dashboard/contact-messages",
        requiredPermission: "contact_messages:read",
      },
    ],
  },
  {
    name: "content",
    title: "Content",
    items: [
      {
        name: "banners",
        displayName: "Banners",
        icon: "banners",
        route: "/admin/dashboard/banners",
        requiredPermission: "banners:read",
      },
      {
        name: "pages",
        displayName: "Pages",
        icon: "pages",
        route: "/admin/dashboard/pages",
        requiredPermission: "pages:read",
      },
      {
        name: "posts",
        displayName: "Blog Posts",
        icon: "posts",
        route: "/admin/dashboard/posts",
        requiredPermission: "posts:read",
      },
      {
        name: "menus",
        displayName: "Menus",
        icon: "menus",
        route: "/admin/dashboard/menus",
        requiredPermission: "menus:read",
      },
    ],
  },
  {
    name: "system",
    title: "System",
    items: [
      {
        name: "employee-management",
        displayName: "Employees",
        icon: "employee-management",
        requiredPermission: "employees:read",
        children: [
          {
            name: "all-employees",
            displayName: "All Employees",
            icon: "all-employees",
            route: "/admin/dashboard/employees",
            requiredPermission: "employees:read",
          },
          {
            name: "add-employee",
            displayName: "Add Employee",
            icon: "add-employee",
            route: "/admin/dashboard/employees/new",
            requiredPermission: "employees:create",
          },
          {
            name: "roles",
            displayName: "Roles",
            icon: "roles",
            route: "/admin/dashboard/employees/roles",
            requiredPermission: "roles:read",
          },
          {
            name: "permissions",
            displayName: "Permissions",
            icon: "permissions",
            route: "/admin/dashboard/employees/permissions",
            requiredPermission: "permissions:read",
          },
        ],
      },
      {
        name: "languages",
        displayName: "Languages",
        icon: "languages",
        route: "/admin/dashboard/system/languages",
        requiredPermission: "languages:read",
      },
      {
        name: "audit-logs",
        displayName: "Audit Logs",
        icon: "audit-logs",
        route: "/admin/dashboard/audit-logs",
        requiredPermission: "audit_logs:read",
      },
      {
        name: "setting",
        displayName: "Settings",
        icon: "setting",
        requiredPermission: "setting:read",
        children: [
          {
            name: "general-setting",
            displayName: "General Settings",
            icon: "general-setting",
            route: "/admin/dashboard/settings",
            requiredPermission: "general_settings:read",
          },
          {
            name: "color-setting",
            displayName: "Color Settings",
            icon: "color-setting",
            route: "/admin/dashboard/skins",
            requiredPermission: "skins:create",
          },
        ],
      },
    ],
  },
];

const ALL_NAV_ITEMS: NavItemType[] = NAV_SECTIONS.flatMap(section => section.items);

// ─── Helpers ──────────────────────────────────────────────────────────────────

function isRouteActive(pathname: string, route: string, exact = false): boolean {
  if (exact) return pathname === route;
  return pathname === route || pathname.startsWith(route + "/");
}

function computeExpanded(pathname: string): Set<string> {
  const expanded = new Set<string>();
  ALL_NAV_ITEMS.forEach(item => {
    if (item.children?.some(child => isRouteActive(pathname, child.route, true))) {
      expanded.add(item.name);
    }
  });
  return expanded;
}

// True at Tailwind's `lg` breakpoint and up. Below it the sidebar is an
// off-canvas drawer (always fully expanded, never the 72px icon rail).
const DESKTOP_QUERY = "(min-width: 1024px)";
function useIsDesktop(): boolean {
  return useSyncExternalStore(
    (onChange) => {
      const mq = window.matchMedia(DESKTOP_QUERY);
      mq.addEventListener("change", onChange);
      return () => mq.removeEventListener("change", onChange);
    },
    () => window.matchMedia(DESKTOP_QUERY).matches,
    () => true,
  );
}

// ─── Shared Styles ────────────────────────────────────────────────────────────

const activeStyle  = { background: "var(--color-cta)", color: "#ffffff" } as const;
const inactiveStyle = { background: "transparent", color: "rgba(255,255,255,0.65)" } as const;

function useHoverHandlers(isActive: boolean) {
  return {
    onMouseEnter(e: React.MouseEvent<HTMLElement>) {
      if (!isActive) {
        (e.currentTarget as HTMLElement).style.background = "var(--color-sidebar-hover)";
        (e.currentTarget as HTMLElement).style.color = "#ffffff";
      }
    },
    onMouseLeave(e: React.MouseEvent<HTMLElement>) {
      if (!isActive) {
        (e.currentTarget as HTMLElement).style.background = "transparent";
        (e.currentTarget as HTMLElement).style.color = "rgba(255,255,255,0.65)";
      }
    },
  };
}

// ─── Tooltip ─────────────────────────────────────────────────────────────────

function Tooltip({ label }: { label: string }) {
  return (
    <span
      className="absolute left-full ml-3 px-2.5 py-1.5 rounded-lg text-xs font-medium
                 whitespace-nowrap pointer-events-none opacity-0 group-hover:opacity-100
                 transition-opacity z-50"
      style={{
        background: "var(--color-sidebar)",
        color: "white",
        boxShadow: "0 4px 12px rgba(0,0,0,0.3)",
      }}
    >
      {label}
    </span>
  );
}

// ─── Section Header ───────────────────────────────────────────────────────────
// Expanded state mein chhota uppercase label, collapsed state mein bas
// ek thin divider line — dono cases mein groups visually separate rehte hain.

function SectionHeader({ title, isFirst }: { title: string; isFirst: boolean }) {
  return (
    <div
      className={`px-3 ${isFirst ? "pt-1" : "pt-4"} pb-1.5 text-[10.5px] font-semibold uppercase`}
      style={{ color: "rgba(255,255,255,0.32)", letterSpacing: "0.08em" }}
    >
      {title}
    </div>
  );
}

function SectionDivider({ isFirst }: { isFirst: boolean }) {
  if (isFirst) return null;
  return (
    <div
      className="mx-2 my-2 h-px"
      style={{ background: "rgba(255,255,255,0.08)" }}
    />
  );
}

// ─── Search Box ───────────────────────────────────────────────────────────────

function SearchBox({
  value,
  onChange,
}: {
  value: string;
  onChange: (v: string) => void;
}) {
  return (
    <div className="px-2 pb-3">
      <div
        className="flex items-center gap-2 px-3 py-2 rounded-xl"
        style={{
          background: "rgba(255,255,255,0.07)",
          border: "1px solid rgba(255,255,255,0.1)",
        }}
      >
        <Search size={14} style={{ color: "rgba(255,255,255,0.4)", flexShrink: 0 }} aria-hidden="true" />
        <input
          type="text"
          value={value}
          onChange={e => onChange(e.target.value)}
          placeholder="Search menu..."
          aria-label="Search menu"
          // 16px on touch screens stops iOS from zooming the page on focus.
          className="bg-transparent outline-none w-full text-base lg:text-xs"
          style={{ color: "rgba(255,255,255,0.85)", caretColor: "var(--color-cta)" }}
        />
        {value && (
          <button
            onClick={() => onChange("")}
            aria-label="Clear search"
            style={{ color: "rgba(255,255,255,0.4)", lineHeight: 1 }}
          >
            <X size={12} strokeWidth={2.5} />
          </button>
        )}
      </div>
    </div>
  );
}

// ─── Child Nav Item ───────────────────────────────────────────────────────────

const ChildNavItem = ({
  child,
  pathname,
}: {
  child: ChildItemType;
  pathname: string;
}) => {
  const isActive = isRouteActive(pathname, child.route, true);
  const hoverHandlers = useHoverHandlers(isActive);

  return (
    <Link
      href={child.route}
      className="flex items-center gap-3 px-3 py-2.5 lg:py-2 rounded-lg text-sm transition-all duration-150"
      style={isActive ? activeStyle : inactiveStyle}
      {...hoverHandlers}
    >
      <ModuleIcon name={child.icon} size={15} />
      <span>{child.displayName}</span>
    </Link>
  );
};

// ─── Nav Item ─────────────────────────────────────────────────────────────────

const NavItem = ({
  item,
  collapsed,
  pathname,
  isExpanded,
  onToggle,
}: {
  item: NavItemType;
  collapsed: boolean;
  pathname: string;
  isExpanded: boolean;
  onToggle: (name: string) => void;
}) => {
  const hasChildren = !!item.children?.length;
  const isDashboard = item.route === "/dashboard";
  const isActive = !hasChildren && !!item.route
    ? isRouteActive(pathname, item.route, isDashboard)
    : false;
  // A parent whose child page is open should read as "current" too.
  const hasActiveChild = hasChildren && item.children!.some(c => isRouteActive(pathname, c.route, true));

  const hoverHandlers = useHoverHandlers(isActive);

  if (collapsed) {
    const href = hasChildren ? item.children![0].route : item.route!;
    const isCollapsedActive = hasChildren ? hasActiveChild : isActive;

    return (
      <Link
        href={href}
        title={item.displayName}
        aria-label={item.displayName}
        className="flex items-center justify-center w-10 h-10 mx-auto rounded-xl
                   transition-all duration-150 group relative"
        style={isCollapsedActive ? activeStyle : inactiveStyle}
        onMouseEnter={e => {
          if (!isCollapsedActive) {
            e.currentTarget.style.background = "var(--color-sidebar-hover)";
            e.currentTarget.style.color = "#ffffff";
          }
        }}
        onMouseLeave={e => {
          if (!isCollapsedActive) {
            e.currentTarget.style.background = "transparent";
            e.currentTarget.style.color = "rgba(255,255,255,0.65)";
          }
        }}
      >
        <ModuleIcon name={item.icon} size={18} />
        <Tooltip label={item.displayName} />
      </Link>
    );
  }

  if (hasChildren) {
    return (
      <div>
        <button
          onClick={() => onToggle(item.name)}
          aria-expanded={isExpanded}
          className="w-full flex items-center justify-between px-3 py-2.5 rounded-xl transition-all duration-150"
          style={hasActiveChild ? { ...inactiveStyle, color: "#ffffff" } : inactiveStyle}
          onMouseEnter={e => {
            e.currentTarget.style.background = "var(--color-sidebar-hover)";
            e.currentTarget.style.color = "#ffffff";
          }}
          onMouseLeave={e => {
            e.currentTarget.style.background = "transparent";
            e.currentTarget.style.color = hasActiveChild ? "#ffffff" : "rgba(255,255,255,0.65)";
          }}
        >
          <div className="flex items-center gap-3 min-w-0">
            <ModuleIcon name={item.icon} size={18} />
            <span className="text-sm font-medium truncate">{item.displayName}</span>
          </div>
          <motion.div
            animate={{ rotate: isExpanded ? 180 : 0 }}
            transition={{ duration: 0.2 }}
          >
            <ChevronDown size={16} strokeWidth={2} aria-hidden="true" />
          </motion.div>
        </button>

        <AnimatePresence initial={false}>
          {isExpanded && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              exit={{ opacity: 0, height: 0 }}
              transition={{ duration: 0.2 }}
              className="overflow-hidden"
            >
              <div className="ml-6 mt-1 space-y-1">
                {item.children!.map(child => (
                  <ChildNavItem key={child.name} child={child} pathname={pathname} />
                ))}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    );
  }

  return (
    <Link
      href={item.route!}
      className="flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-150"
      style={isActive ? activeStyle : inactiveStyle}
      aria-current={isActive ? "page" : undefined}
      {...hoverHandlers}
    >
      <ModuleIcon name={item.icon} size={18} />
      <span className="text-sm font-medium truncate">{item.displayName}</span>
    </Link>
  );
};

// ─── Main Sidebar ─────────────────────────────────────────────────────────────

export default function Sidebar() {
  const pathname = usePathname();
  const {
    hasPermission,
    permissions,          // ← FIX: permissions array bhi lo
    loading: permissionsLoading,
    refresh,
  } = usePermissions();
  const { user, sidebarCollapsed, toggleSidebar, userRole } = useAdminStore();

  const isDesktop = useIsDesktop();
  const mobileOpen = useAdminMobileNav((s) => s.open);
  const setMobileOpen = useAdminMobileNav((s) => s.setOpen);
  // The icon-only rail is a desktop affordance; the mobile drawer is always full.
  const collapsed = sidebarCollapsed && isDesktop;

  const [expandedItems, setExpandedItems] = useState<Set<string>>(
    () => computeExpanded(pathname)
  );
  const [search, setSearch] = useState("");

  const prevPathnameRef = useRef(pathname);
  useEffect(() => {
    if (prevPathnameRef.current === pathname) return;
    prevPathnameRef.current = pathname;
    setSearch("");
    setExpandedItems(prev => {
      const next = new Set(prev);
      computeExpanded(pathname).forEach(name => next.add(name));
      return next;
    });
    // Navigating from inside the drawer should dismiss it.
    setMobileOpen(false);
  }, [pathname, setMobileOpen]);

  // Escape closes the drawer; growing past the breakpoint (e.g. rotating a
  // tablet) also closes it so it can't be left "open" behind the static sidebar.
  useEffect(() => {
    if (!mobileOpen) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setMobileOpen(false);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [mobileOpen, setMobileOpen]);

  useEffect(() => {
    if (isDesktop) setMobileOpen(false);
  }, [isDesktop, setMobileOpen]);

  useEffect(() => {
    window.addEventListener("permissions-updated", refresh);
    return () => window.removeEventListener("permissions-updated", refresh);
  }, [refresh]);

  // Permission filter ab section-wise chalta hai, taake empty section
  // (jiske sab items hide ho gaye) apna heading bhi na dikhaye.
  const visibleSections = useMemo(() => {
    if (permissionsLoading) return [];

    const isSuperAdmin = hasPermission("access:anytime");

    if (permissions.length === 0) return [];

    return NAV_SECTIONS.map(section => {
      const items = section.items.flatMap(item => {
        if (isSuperAdmin) return [item];

        if (!hasPermission(item.requiredPermission)) return [];

        if (item.children) {
          const filteredChildren = item.children.filter(child =>
            hasPermission(child.requiredPermission)
          );
          if (filteredChildren.length === 0) return [];
          return [{ ...item, children: filteredChildren }];
        }

        return [item];
      });

      return { ...section, items };
    }).filter(section => section.items.length > 0);
  }, [hasPermission, permissions, permissionsLoading]);

  const filteredSections = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return visibleSections;

    return visibleSections.map(section => {
      const items = section.items.flatMap(item => {
        if (item.displayName.toLowerCase().includes(q)) return [item];

        if (item.children) {
          const matched = item.children.filter(child =>
            child.displayName.toLowerCase().includes(q)
          );
          if (matched.length > 0) return [{ ...item, children: matched }];
        }

        return [];
      });

      return { ...section, items };
    }).filter(section => section.items.length > 0);
  }, [visibleSections, search]);

  const displayExpandedItems = useMemo(() => {
    if (!search.trim()) return expandedItems;
    const next = new Set(expandedItems);
    filteredSections.forEach(section => {
      section.items.forEach(item => {
        if (item.children) next.add(item.name);
      });
    });
    return next;
  }, [search, filteredSections, expandedItems]);

  const toggleExpand = useCallback((itemName: string) => {
    setExpandedItems(prev => {
      const next = new Set(prev);
      if (next.has(itemName)) {
        next.delete(itemName);
      } else {
        next.add(itemName);
      }
      return next;
    });
  }, []);

  const userInitials =
    user?.firstName && user?.lastName
      ? `${user.firstName[0]}${user.lastName[0]}`.toUpperCase()
      : user?.firstName?.[0]?.toUpperCase() || "U";

  // Below `lg` the aside is fixed and slides in from the left (`translate-x`),
  // above it it's a normal flex child whose width is the collapsed/expanded
  // rail. `h-dvh` (not `h-screen`) so mobile browser chrome doesn't push the
  // footer/collapse button off-screen.
  const asideClass =
    "flex flex-col h-dvh shrink-0 transition-[transform,width] duration-300 " +
    "fixed inset-y-0 left-0 z-50 w-70 max-w-[85vw] " +
    "lg:static lg:z-auto lg:max-w-none " +
    (mobileOpen ? "translate-x-0 " : "-translate-x-full ") +
    "lg:translate-x-0 " +
    (collapsed ? "lg:w-18" : "lg:w-65");
  const asideStyle = {
    background: "var(--color-sidebar)",
    borderRight: "1px solid rgba(255,255,255,0.08)",
  };

  const backdrop = mobileOpen && !isDesktop && (
    <div
      className="fixed inset-0 z-40 bg-black/50 lg:hidden"
      onClick={() => setMobileOpen(false)}
      aria-hidden="true"
    />
  );

  if (permissionsLoading) {
    return (
      <aside className={asideClass} style={asideStyle} aria-label="Admin navigation">
        <div className="flex items-center justify-center h-full">
          <div className="w-6 h-6 rounded-full animate-spin border-2 border-white/20 border-t-white/60" />
        </div>
      </aside>
    );
  }

  const hasAnyVisibleItem = filteredSections.length > 0;

  return (
    <>
      {backdrop}
      <aside className={asideClass} style={asideStyle} aria-label="Admin navigation">
        {/* Logo */}
        <div
          className="flex items-center gap-3 px-4 py-4 lg:py-5 shrink-0"
          style={{ borderBottom: "1px solid rgba(255,255,255,0.08)" }}
        >
          <div
            className="flex items-center justify-center w-9 h-9 rounded-xl shrink-0"
            style={{ background: "var(--color-cta)" }}
          >
            <Store size={18} color="white" strokeWidth={2} aria-hidden="true" />
          </div>
          {!collapsed && (
            <div className="min-w-0 flex-1">
              <div className="text-sm font-bold text-white leading-tight truncate">DesiCart Admin</div>
              <div className="text-xs truncate" style={{ color: "rgba(255,255,255,0.4)" }}>
                {`${userRole.role ?? ""}`}
              </div>
            </div>
          )}
          {/* Drawer close — mobile only */}
          <button
            onClick={() => setMobileOpen(false)}
            aria-label="Close menu"
            className="lg:hidden flex items-center justify-center w-9 h-9 rounded-lg shrink-0"
            style={{ color: "rgba(255,255,255,0.7)", background: "rgba(255,255,255,0.06)" }}
          >
            <X size={18} />
          </button>
        </div>

        {/* Collapsed avatar */}
        {collapsed && user && (
          <div className="flex justify-center py-4">
            <div
              className="w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white"
              style={{ background: "var(--color-cta)" }}
            >
              {userInitials}
            </div>
          </div>
        )}

        {/* Nav — a click on any link inside also closes the mobile drawer, even
            when it points at the page you're already on (no pathname change). */}
        <nav
          className="flex-1 overflow-y-auto overflow-x-hidden py-4 px-2 overscroll-contain"
          onClick={(e) => {
            if ((e.target as HTMLElement).closest("a")) setMobileOpen(false);
          }}
        >
          {!collapsed && (
            <SearchBox value={search} onChange={setSearch} />
          )}

          {hasAnyVisibleItem ? (
            filteredSections.map((section, idx) => (
              <div key={section.name}>
                {!collapsed && (
                  <SectionHeader title={section.title} isFirst={idx === 0} />
                )}
                {collapsed && <SectionDivider isFirst={idx === 0} />}

                <div className="flex flex-col gap-1">
                  {section.items.map(item => (
                    <NavItem
                      key={item.name}
                      item={item}
                      collapsed={collapsed}
                      pathname={pathname}
                      isExpanded={displayExpandedItems.has(item.name)}
                      onToggle={toggleExpand}
                    />
                  ))}
                </div>
              </div>
            ))
          ) : (
            !collapsed && search && (
              <div
                className="text-center py-6 text-xs"
                style={{ color: "rgba(255,255,255,0.3)" }}
              >
                No menu found for
                <br />
                <span style={{ color: "rgba(255,255,255,0.5)" }}>{search}</span>
              </div>
            )
          )}
        </nav>

        {/* Collapse toggle — desktop only (the drawer has its own close button) */}
        <div
          className="hidden lg:block shrink-0 px-2 py-3"
          style={{ borderTop: "1px solid rgba(255,255,255,0.08)" }}
        >
          <button
            onClick={toggleSidebar}
            className="flex items-center gap-3 w-full px-3 py-2.5 rounded-xl
                       transition-all duration-150 group relative"
            style={inactiveStyle}
            onMouseEnter={e => {
              e.currentTarget.style.background = "var(--color-sidebar-hover)";
              e.currentTarget.style.color = "#ffffff";
            }}
            onMouseLeave={e => {
              e.currentTarget.style.background = "transparent";
              e.currentTarget.style.color = "rgba(255,255,255,0.65)";
            }}
            title={collapsed ? "Expand sidebar" : "Collapse sidebar"}
            aria-label={collapsed ? "Expand sidebar" : "Collapse sidebar"}
          >
            {collapsed ? <ChevronsRight size={18} /> : <ChevronsLeft size={18} />}
            {!collapsed && <span className="text-sm font-medium">Collapse</span>}
            {collapsed && <Tooltip label="Expand" />}
          </button>
        </div>
      </aside>
    </>
  );
}
