'use client';

/**
 * Sidebar — Collapsible navigation component with sections.
 *
 * Features:
 * - Expanded (260px) or collapsed (64px icon-only) on desktop (≥1024px)
 * - Navigation items grouped into collapsible sections: Favorites, Dashboards, Pages
 * - Section expand/collapse with smooth animation (≤300ms)
 * - Active item highlighted with accent-colored left border (3-4px) + background
 * - "Divisi" brand logo and name at the top
 * - Settings pinned at the bottom with a visual divider
 * - Mobile hamburger menu + overlay drawer preserved for viewports below 1024px
 * - Collapse toggle button at the bottom of the sidebar
 *
 * Requirements: 1.1–1.10
 */

import { useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import Link from 'next/link';
import { useAuthStore } from '@/lib/stores/auth-store';
import { useSidebarStore } from '@/lib/stores/sidebar-store';
import { useThemeStore } from '@/lib/stores/theme-store';
import { useLangStore } from '@/lib/stores/lang-store';
import { useTranslation } from '@/lib/hooks/useTranslation';
import type { TranslationKeys } from '@/lib/i18n/translations';
import {
  getNavItemsForRole,
  getBottomNavItemsForRole,
  groupNavItemsBySection,
  type IconName,
  type NavItem,
  type NavSection,
} from '@/lib/constants/navigation';

// ── Icon map — simple SVG icons for each nav item ───────────────────────────

function NavIcon({ name, className }: { name: IconName; className?: string }) {
  const cls = className ?? 'h-5 w-5';

  switch (name) {
    case 'overview':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="3" width="7" height="7" />
          <rect x="14" y="3" width="7" height="7" />
          <rect x="3" y="14" width="7" height="7" />
          <rect x="14" y="14" width="7" height="7" />
        </svg>
      );
    case 'works':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M9 18V5l12-2v13" />
          <circle cx="6" cy="18" r="3" />
          <circle cx="18" cy="16" r="3" />
        </svg>
      );
    case 'composers':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
          <circle cx="9" cy="7" r="4" />
          <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
          <path d="M16 3.13a4 4 0 0 1 0 7.75" />
        </svg>
      );
    case 'payees':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
          <circle cx="12" cy="7" r="4" />
        </svg>
      );
    case 'contracts':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
          <polyline points="14 2 14 8 20 8" />
          <line x1="16" y1="13" x2="8" y2="13" />
          <line x1="16" y1="17" x2="8" y2="17" />
          <polyline points="10 9 9 9 8 9" />
        </svg>
      );
    case 'income':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <line x1="12" y1="1" x2="12" y2="23" />
          <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
        </svg>
      );
    case 'transactions':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="17 1 21 5 17 9" />
          <path d="M3 11V9a4 4 0 0 1 4-4h14" />
          <polyline points="7 23 3 19 7 15" />
          <path d="M21 13v2a4 4 0 0 1-4 4H3" />
        </svg>
      );
    case 'costs':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="1" y="4" width="22" height="16" rx="2" ry="2" />
          <line x1="1" y1="10" x2="23" y2="10" />
        </svg>
      );
    case 'statements':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
        </svg>
      );
    case 'suspense':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10" />
          <line x1="12" y1="8" x2="12" y2="12" />
          <line x1="12" y1="16" x2="12.01" y2="16" />
        </svg>
      );
    case 'audit':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
        </svg>
      );
    case 'settings':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="3" />
          <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
        </svg>
      );
    case 'home':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
          <polyline points="9 22 9 12 15 12 15 22" />
        </svg>
      );
    case 'analytics':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <line x1="18" y1="20" x2="18" y2="10" />
          <line x1="12" y1="20" x2="12" y2="4" />
          <line x1="6" y1="20" x2="6" y2="14" />
        </svg>
      );
    case 'songs':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M9 18V5l12-2v13" />
          <circle cx="6" cy="18" r="3" />
          <circle cx="18" cy="16" r="3" />
        </svg>
      );
    case 'documents':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
          <polyline points="14 2 14 8 20 8" />
          <line x1="16" y1="13" x2="8" y2="13" />
          <line x1="16" y1="17" x2="8" y2="17" />
          <polyline points="10 9 9 9 8 9" />
        </svg>
      );
    case 'chart-overview':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="3" width="7" height="7" />
          <rect x="14" y="3" width="7" height="7" />
          <rect x="3" y="14" width="7" height="7" />
          <rect x="14" y="14" width="7" height="7" />
        </svg>
      );
    case 'top-songs':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M9 18V5l12-2v13" />
          <circle cx="6" cy="18" r="3" />
          <circle cx="18" cy="16" r="3" />
        </svg>
      );
    case 'income-groups':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21.21 15.89A10 10 0 1 1 8 2.83" />
          <path d="M22 12A10 10 0 0 0 12 2v10z" />
        </svg>
      );
    case 'territories':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10" />
          <line x1="2" y1="12" x2="22" y2="12" />
          <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
        </svg>
      );
    case 'sources':
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <polygon points="12 2 2 7 12 12 22 7 12 2" />
          <polyline points="2 17 12 22 22 17" />
          <polyline points="2 12 12 17 22 12" />
        </svg>
      );
    default:
      return (
        <svg className={cls} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <circle cx="12" cy="12" r="10" />
        </svg>
      );
  }
}

// ── Chevron icon for section expand/collapse ─────────────────────────────────

function ChevronIcon({ expanded, className }: { expanded: boolean; className?: string }) {
  return (
    <svg
      className={`h-4 w-4 transition-transform duration-200 ${expanded ? 'rotate-90' : 'rotate-0'} ${className ?? ''}`}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <polyline points="9 18 15 12 9 6" />
    </svg>
  );
}

// ── Section header labels ────────────────────────────────────────────────────

function getSectionLabels(t: TranslationKeys): Record<NavSection, string> {
  return {
    favorites: t.sidebar.favorites,
    dashboards: t.sidebar.dashboards,
    pages: t.sidebar.pages,
    analytics: t.sidebar.analytics,
  };
}

const SECTION_ORDER: NavSection[] = ['dashboards', 'analytics', 'pages'];

// ── Nav label translation helper ─────────────────────────────────────────────

function getTranslatedLabel(label: string, t: TranslationKeys): string {
  const keyMap: Record<string, string> = {
    'Overview': t.nav.overview,
    'Works': t.nav.works,
    'Composers': t.nav.composers,
    'Payees': t.nav.payees,
    'Contracts': t.nav.contracts,
    'Income': t.nav.income,
    'Transactions': t.nav.transactions,
    'Costs': t.nav.costs,
    'Statements': t.nav.statements,
    'Suspense': t.nav.suspense,
    'Audit': t.nav.audit,
    'Settings': t.nav.settings,
    'Inicio': t.nav.inicio,
    'Top Songs': t.nav.topSongs,
    'Income Groups': t.nav.incomeGroups,
    'Territories': t.nav.territories,
    'Exploitation Sources': t.nav.exploitationSources,
    'Canciones': t.nav.canciones,
    'Documentos': t.nav.documentos,
  };
  return keyMap[label] ?? label;
}

// ── Collapsible nav section ──────────────────────────────────────────────────

function NavSectionGroup({
  section,
  items,
  expanded,
  onToggle,
  pathname,
  onItemClick,
  collapsed,
  t,
}: {
  section: NavSection;
  items: NavItem[];
  expanded: boolean;
  onToggle: () => void;
  pathname: string;
  onItemClick?: () => void;
  collapsed?: boolean;
  t: TranslationKeys;
}) {
  if (items.length === 0) return null;

  const sectionLabels = getSectionLabels(t);

  // Collapsed mode: just show icons, no section headers
  if (collapsed) {
    return (
      <div className="mb-1 flex flex-col items-center gap-0.5">
        {items.map((item) => {
          const isActive = pathname === item.href;
          const translatedLabel = getTranslatedLabel(item.label, t);
          return (
            <Link
              key={item.href}
              href={item.href}
              onClick={onItemClick}
              title={translatedLabel}
              className={`
                relative flex items-center justify-center rounded-lg p-2.5
                transition-colors duration-150
                ${
                  isActive
                    ? 'bg-divisi-accent/10 text-divisi-accent'
                    : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                }
              `}
              aria-current={isActive ? 'page' : undefined}
            >
              {isActive && (
                <span className="absolute left-0 top-1/2 -translate-y-1/2 h-6 w-[3px] rounded-r-full bg-divisi-accent" />
              )}
              <NavIcon name={item.icon} />
            </Link>
          );
        })}
      </div>
    );
  }

  return (
    <div className="mb-1">
      {/* Section header */}
      <button
        type="button"
        onClick={onToggle}
        className="flex w-full items-center justify-between px-3 py-2 text-xs font-semibold uppercase tracking-wider text-divisi-text-secondary hover:text-divisi-text-primary transition-colors duration-150"
        aria-expanded={expanded}
      >
        <span>{sectionLabels[section]}</span>
        <ChevronIcon expanded={expanded} />
      </button>

      {/* Collapsible items with smooth animation */}
      <div
        className="overflow-hidden transition-all duration-300 ease-in-out"
        style={{
          maxHeight: expanded ? `${items.length * 44}px` : '0px',
          opacity: expanded ? 1 : 0,
        }}
      >
        <div className="flex flex-col gap-0.5">
          {items.map((item) => {
            const isActive = pathname === item.href;
            const translatedLabel = getTranslatedLabel(item.label, t);
            return (
              <Link
                key={item.href}
                href={item.href}
                onClick={onItemClick}
                className={`
                  relative flex items-center gap-3 rounded-lg px-3 py-2.5
                  transition-colors duration-150
                  ${
                    isActive
                      ? 'bg-divisi-accent/10 text-divisi-accent'
                      : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                  }
                `}
                aria-current={isActive ? 'page' : undefined}
              >
                {isActive && (
                  <span className="absolute left-0 top-1/2 -translate-y-1/2 h-6 w-[3px] rounded-r-full bg-divisi-accent" />
                )}
                <span className="flex-shrink-0">
                  <NavIcon name={item.icon} />
                </span>
                <span className="text-sm font-medium">{translatedLabel}</span>
              </Link>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── Sidebar component ───────────────────────────────────────────────────────

export default function Sidebar() {
  const pathname = usePathname();
  const router = useRouter();
  const role = useAuthStore((s) => s.role);
  const user = useAuthStore((s) => s.user);
  const logout = useAuthStore((s) => s.logout);
  const { isMobileOpen, closeMobile, toggleMobile, isCollapsed, toggleCollapse } = useSidebarStore();
  const { mode: themeMode, toggle: toggleTheme } = useThemeStore();
  const { lang, toggle: toggleLang } = useLangStore();
  const t = useTranslation();

  // Section expand/collapse state — all default to expanded
  const [expandedSections, setExpandedSections] = useState<Record<NavSection, boolean>>({
    favorites: true,
    dashboards: true,
    pages: true,
    analytics: true,
  });

  const toggleSection = (section: NavSection) => {
    setExpandedSections((prev) => ({
      ...prev,
      [section]: !prev[section],
    }));
  };

  // Filter nav items based on current role
  const visibleItems = role ? getNavItemsForRole(role) : [];
  const bottomItems = role ? getBottomNavItemsForRole(role) : [];

  // Group items by section
  const groupedItems = groupNavItemsBySection(visibleItems);

  return (
    <>
      {/* ─── Desktop sidebar (≥1024px) — collapsible ─────────────────── */}
      <aside
        className={`
          hidden lg:flex flex-col
          fixed top-14 left-0 bottom-0 z-20
          border-r border-divisi-border bg-divisi-card
          py-4 overflow-y-auto
          transition-[width] duration-300 ease-in-out
          ${isCollapsed ? 'w-16' : 'w-[260px]'}
        `}
      >
        {/* Navigation sections */}
        <nav className={`flex flex-1 flex-col gap-0.5 overflow-y-auto ${isCollapsed ? 'px-1' : 'px-2'}`}>
          {/* Overview — standalone at top */}
          {groupedItems.favorites.map((item) => {
            const isActive = pathname === item.href;
            const translatedLabel = getTranslatedLabel(item.label, t);
            return (
              <Link
                key={item.href}
                href={item.href}
                title={isCollapsed ? translatedLabel : undefined}
                className={`
                  relative flex items-center rounded-lg mb-2
                  transition-colors duration-150
                  ${isCollapsed ? 'justify-center p-2.5' : 'gap-3 px-3 py-2.5'}
                  ${isActive
                    ? 'bg-divisi-accent/10 text-divisi-accent'
                    : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                  }
                `}
                aria-current={isActive ? 'page' : undefined}
              >
                {isActive && (
                  <span className="absolute left-0 top-1/2 -translate-y-1/2 h-6 w-[3px] rounded-r-full bg-divisi-accent" />
                )}
                <span className="flex-shrink-0">
                  <NavIcon name={item.icon} />
                </span>
                {!isCollapsed && <span className="text-sm font-medium">{translatedLabel}</span>}
              </Link>
            );
          })}

          {/* Grouped sections */}
          {SECTION_ORDER.map((section) => (
            <NavSectionGroup
              key={section}
              section={section}
              items={groupedItems[section]}
              expanded={expandedSections[section]}
              onToggle={() => toggleSection(section)}
              pathname={pathname}
              collapsed={isCollapsed}
              t={t}
            />
          ))}
        </nav>

        {/* Bottom-pinned items (Language + Theme toggle + Settings) with visual divider */}
        <div className={`mt-auto border-t border-divisi-border pt-3 ${isCollapsed ? 'px-1' : 'px-2'}`}>
          {/* Language toggle */}
          <button
            type="button"
            onClick={toggleLang}
            title={lang === 'es' ? 'Switch to English' : 'Cambiar a Español'}
            className={`
              flex items-center rounded-lg w-full mb-0.5
              text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5
              transition-colors duration-150
              ${isCollapsed ? 'justify-center p-2.5' : 'gap-3 px-3 py-2.5'}
            `}
          >
            <svg className="h-5 w-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10" />
              <line x1="2" y1="12" x2="22" y2="12" />
              <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
            </svg>
            {!isCollapsed && <span className="text-sm font-medium">{lang === 'es' ? t.sidebar.espanol : t.sidebar.english}</span>}
          </button>

          {/* Theme toggle */}
          <button
            type="button"
            onClick={toggleTheme}
            title={themeMode === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
            className={`
              flex items-center rounded-lg w-full mb-0.5
              text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5
              transition-colors duration-150
              ${isCollapsed ? 'justify-center p-2.5' : 'gap-3 px-3 py-2.5'}
            `}
          >
            {themeMode === 'dark' ? (
              <svg className="h-5 w-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="5" />
                <line x1="12" y1="1" x2="12" y2="3" />
                <line x1="12" y1="21" x2="12" y2="23" />
                <line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
                <line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
                <line x1="1" y1="12" x2="3" y2="12" />
                <line x1="21" y1="12" x2="23" y2="12" />
                <line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
                <line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
              </svg>
            ) : (
              <svg className="h-5 w-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
              </svg>
            )}
            {!isCollapsed && <span className="text-sm font-medium">{themeMode === 'dark' ? t.sidebar.lightMode : t.sidebar.darkMode}</span>}
          </button>

          {/* Settings */}
          {bottomItems.length > 0 && bottomItems.map((item) => {
              const isActive = pathname === item.href;
              const translatedLabel = getTranslatedLabel(item.label, t);
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  title={isCollapsed ? translatedLabel : undefined}
                  className={`
                    relative flex items-center rounded-lg
                    transition-colors duration-150
                    ${isCollapsed ? 'justify-center p-2.5' : 'gap-3 px-3 py-2.5'}
                    ${
                      isActive
                        ? 'bg-divisi-accent/10 text-divisi-accent'
                        : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                    }
                  `}
                  aria-current={isActive ? 'page' : undefined}
                >
                  {isActive && (
                    <span className="absolute left-0 top-1/2 -translate-y-1/2 h-6 w-[3px] rounded-r-full bg-divisi-accent" />
                  )}
                  <span className="flex-shrink-0">
                    <NavIcon name={item.icon} />
                  </span>
                  {!isCollapsed && <span className="text-sm font-medium">{translatedLabel}</span>}
                </Link>
              );
            })}
        </div>

        {/* User info */}
        {user && (
          <div className={`pt-2 ${isCollapsed ? 'px-1' : 'px-2'}`}>
            {isCollapsed ? (
              <div className="flex justify-center" title={`${user.name}\n${role?.replace(/_/g, ' ')}`}>
                <div className="flex h-8 w-8 items-center justify-center rounded-full bg-divisi-accent/15 text-xs font-bold text-divisi-accent">
                  {user.name.charAt(0)}
                </div>
              </div>
            ) : (
              <div className="flex items-center gap-3 px-3 py-2">
                <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-divisi-accent/15 text-xs font-bold text-divisi-accent">
                  {user.name.charAt(0)}
                </div>
                <div className="min-w-0">
                  <p className="text-sm font-medium text-divisi-text-primary truncate">{user.name}</p>
                  {role && (
                    <p className="text-xs text-divisi-accent truncate">{role.replace(/_/g, ' ')}</p>
                  )}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Logout button */}
        <div className={`pt-1 ${isCollapsed ? 'px-1' : 'px-2'}`}>
          <button
            type="button"
            onClick={() => { logout(); router.push('/login'); }}
            title={isCollapsed ? t.sidebar.logout : undefined}
            className={`
              flex items-center rounded-lg w-full
              text-red-400 hover:text-red-300 hover:bg-red-500/10
              transition-colors duration-150
              ${isCollapsed ? 'justify-center p-2.5' : 'gap-3 px-3 py-2.5'}
            `}
            aria-label={t.sidebar.logout}
          >
            <svg className="h-5 w-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
              <polyline points="16 17 21 12 16 7" />
              <line x1="21" y1="12" x2="9" y2="12" />
            </svg>
            {!isCollapsed && <span className="text-sm font-medium">{t.sidebar.logout}</span>}
          </button>
        </div>

        {/* Collapse toggle button */}
        <div className={`border-t border-divisi-border pt-2 mt-2 ${isCollapsed ? 'px-1' : 'px-2'}`}>
          <button
            type="button"
            onClick={toggleCollapse}
            className={`
              flex items-center rounded-lg w-full
              text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5
              transition-colors duration-150
              ${isCollapsed ? 'justify-center p-2.5' : 'gap-3 px-3 py-2.5'}
            `}
            aria-label={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}
            title={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}
          >
            <svg
              className={`h-5 w-5 transition-transform duration-300 ${isCollapsed ? 'rotate-180' : ''}`}
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <polyline points="11 17 6 12 11 7" />
              <polyline points="18 17 13 12 18 7" />
            </svg>
            {!isCollapsed && <span className="text-sm font-medium">{t.sidebar.collapse}</span>}
          </button>
        </div>
      </aside>

      {/* ─── Mobile hamburger button (visible below lg) ───────────────── */}
      <button
        type="button"
        onClick={toggleMobile}
        className="
          fixed top-3 left-3 z-50
          lg:hidden
          flex items-center justify-center
          h-10 w-10 rounded-lg
          bg-divisi-card border border-divisi-border
          text-divisi-text-primary
        "
        aria-label={isMobileOpen ? 'Close navigation menu' : 'Open navigation menu'}
        aria-expanded={isMobileOpen}
      >
        {isMobileOpen ? (
          <svg className="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <line x1="18" y1="6" x2="6" y2="18" />
            <line x1="6" y1="6" x2="18" y2="18" />
          </svg>
        ) : (
          <svg className="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <line x1="3" y1="12" x2="21" y2="12" />
            <line x1="3" y1="6" x2="21" y2="6" />
            <line x1="3" y1="18" x2="21" y2="18" />
          </svg>
        )}
      </button>

      {/* ─── Mobile overlay + drawer (below lg) ───────────────────────── */}
      {isMobileOpen && (
        <>
          {/* Backdrop */}
          <div
            className="fixed inset-0 z-40 bg-black/60 lg:hidden"
            onClick={closeMobile}
            aria-hidden="true"
          />

          {/* Drawer — always expanded on mobile */}
          <aside
            className="
              fixed inset-y-0 left-0 z-40
              w-[280px] lg:hidden
              flex flex-col
              bg-divisi-card border-r border-divisi-border
              py-4
              animate-slide-in
            "
          >
            {/* Navigation sections */}
            <nav className="flex flex-1 flex-col gap-0.5 px-2 overflow-y-auto pt-2">
              {/* Overview — standalone at top */}
              {groupedItems.favorites.map((item) => {
                const isActive = pathname === item.href;
                const translatedLabel = getTranslatedLabel(item.label, t);
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    onClick={closeMobile}
                    className={`
                      relative flex items-center gap-3 rounded-lg px-3 py-2.5 mb-2
                      transition-colors duration-150
                      ${isActive
                        ? 'bg-divisi-accent/10 text-divisi-accent'
                        : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                      }
                    `}
                    aria-current={isActive ? 'page' : undefined}
                  >
                    {isActive && (
                      <span className="absolute left-0 top-1/2 -translate-y-1/2 h-6 w-[3px] rounded-r-full bg-divisi-accent" />
                    )}
                    <span className="flex-shrink-0">
                      <NavIcon name={item.icon} />
                    </span>
                    <span className="text-sm font-medium">{translatedLabel}</span>
                  </Link>
                );
              })}

              {/* Grouped sections */}
              {SECTION_ORDER.map((section) => (
                <NavSectionGroup
                  key={section}
                  section={section}
                  items={groupedItems[section]}
                  expanded={expandedSections[section]}
                  onToggle={() => toggleSection(section)}
                  pathname={pathname}
                  onItemClick={closeMobile}
                  t={t}
                />
              ))}
            </nav>

            {/* Bottom-pinned items (Language + Theme toggle + Settings) with visual divider */}
            <div className="mt-auto border-t border-divisi-border pt-3 px-2 pb-2">
              {/* Language toggle */}
              <button
                type="button"
                onClick={toggleLang}
                title={lang === 'es' ? 'Switch to English' : 'Cambiar a Español'}
                className="flex items-center gap-3 rounded-lg px-3 py-2.5 w-full mb-0.5 text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5 transition-colors duration-150"
              >
                <svg className="h-5 w-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="12" cy="12" r="10" />
                  <line x1="2" y1="12" x2="22" y2="12" />
                  <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
                </svg>
                <span className="text-sm font-medium">{lang === 'es' ? t.sidebar.espanol : t.sidebar.english}</span>
              </button>

              {/* Theme toggle */}
              <button
                type="button"
                onClick={toggleTheme}
                className="flex items-center gap-3 rounded-lg px-3 py-2.5 w-full mb-0.5 text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5 transition-colors duration-150"
              >
                {themeMode === 'dark' ? (
                  <svg className="h-5 w-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="12" cy="12" r="5" />
                    <line x1="12" y1="1" x2="12" y2="3" />
                    <line x1="12" y1="21" x2="12" y2="23" />
                    <line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
                    <line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
                    <line x1="1" y1="12" x2="3" y2="12" />
                    <line x1="21" y1="12" x2="23" y2="12" />
                    <line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
                    <line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
                  </svg>
                ) : (
                  <svg className="h-5 w-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
                  </svg>
                )}
                <span className="text-sm font-medium">{themeMode === 'dark' ? t.sidebar.lightMode : t.sidebar.darkMode}</span>
              </button>

              {/* Settings */}
              {bottomItems.map((item) => {
                  const isActive = pathname === item.href;
                  const translatedLabel = getTranslatedLabel(item.label, t);
                  return (
                    <Link
                      key={item.href}
                      href={item.href}
                      onClick={closeMobile}
                      className={`
                        relative flex items-center gap-3 rounded-lg px-3 py-2.5
                        transition-colors duration-150
                        ${
                          isActive
                            ? 'bg-divisi-accent/10 text-divisi-accent'
                            : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                        }
                      `}
                      aria-current={isActive ? 'page' : undefined}
                    >
                      {isActive && (
                        <span className="absolute left-0 top-1/2 -translate-y-1/2 h-6 w-[3px] rounded-r-full bg-divisi-accent" />
                      )}
                      <span className="flex-shrink-0">
                        <NavIcon name={item.icon} />
                      </span>
                      <span className="text-sm font-medium">{translatedLabel}</span>
                    </Link>
                  );
                })}

              {/* User info */}
              {user && (
                <div className="flex items-center gap-3 px-3 py-2 mt-1">
                  <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-divisi-accent/15 text-xs font-bold text-divisi-accent">
                    {user.name.charAt(0)}
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-medium text-divisi-text-primary truncate">{user.name}</p>
                    {role && (
                      <p className="text-xs text-divisi-accent truncate">{role.replace(/_/g, ' ')}</p>
                    )}
                  </div>
                </div>
              )}

              {/* Logout */}
              <button
                type="button"
                onClick={() => { logout(); router.push('/login'); }}
                className="flex items-center gap-3 rounded-lg px-3 py-2.5 w-full text-red-400 hover:text-red-300 hover:bg-red-500/10 transition-colors duration-150"
                aria-label={t.sidebar.logout}
              >
                <svg className="h-5 w-5 flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
                  <polyline points="16 17 21 12 16 7" />
                  <line x1="21" y1="12" x2="9" y2="12" />
                </svg>
                <span className="text-sm font-medium">{t.sidebar.logout}</span>
              </button>
              </div>
          </aside>
        </>
      )}
    </>
  );
}
