import { Link, usePage } from '@inertiajs/react';
import { AnimatePresence, motion } from 'framer-motion';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import type { ModuleKey } from '@/types';

type AuthUser = {
  id: number;
  firstName: string;
  lastName: string;
  username: string;
  roleKey: string;
  schoolId: number | null;
};

/**
 * `module`     — school-level entitlement. Shown with a lock badge when missing,
 *                because the school could buy it.
 * `permission` — this user's own grant. Hidden entirely when missing; we don't
 *                advertise what someone isn't allowed to do.
 */
type NavLeaf = { href: string; label: string; icon: string; module?: ModuleKey; permission?: string };
type NavGroup = { key: string; label: string; icon: string; children: NavLeaf[] };
type NavItem = NavLeaf | NavGroup;
type NavSection = { title: string; items: NavItem[] };

function isGroup(item: NavItem): item is NavGroup {
  return (item as NavGroup).children !== undefined;
}

/* ─────────────── منوها — فقط فارسی ─────────────── */

const superAdminNav: NavSection[] = [
  {
    title: 'نمای کلی',
    items: [{ href: '/super-admin', label: 'داشبورد', icon: 'bi-speedometer2' }],
  },
  {
    title: 'مدیریت',
    items: [
      { href: '/super-admin/schools', label: 'مدارس', icon: 'bi-building' },
      { href: '/super-admin/users', label: 'کاربران و دسترسی‌ها', icon: 'bi-person-lock' },
      { href: '/super-admin/modules', label: 'ماژول‌ها', icon: 'bi-puzzle' },
      { href: '/super-admin/grade-levels', label: 'پایه‌های تحصیلی', icon: 'bi-ladder' },
      { href: '/super-admin/global-eteraz', label: 'سیاست اعتراض سراسری', icon: 'bi-megaphone' },
      { href: '/super-admin/landing-settings', label: 'صفحه عمومی و نمادها', icon: 'bi-globe2' },
      { href: '/super-admin/contact-requests', label: 'درخواست‌های دمو', icon: 'bi-telephone-inbound' },
      { href: '/super-admin/support-tickets', label: 'پشتیبانی مدارس', icon: 'bi-life-preserver' },
    ],
  },
  {
    title: 'پیامک',
    items: [
      {
        key: 'sms-admin',
        label: 'سامانه پیامک',
        icon: 'bi-chat-dots',
        children: [
          { href: '/super-admin/sms-usage', label: 'مصرف و درخواست‌ها', icon: 'bi-graph-up' },
          { href: '/super-admin/sms-settings', label: 'سرویس‌ها و قالب‌ها', icon: 'bi-sliders' },
          { href: '/super-admin/sms-templates', label: 'قالب‌های سراسری', icon: 'bi-file-text' },
          { href: '/super-admin/sms-settings#pricing', label: 'قیمت و هدیه', icon: 'bi-currency-exchange' },
        ],
      },
    ],
  },
  {
    title: 'پایگاه داده',
    items: [
      {
        key: 'database',
        label: 'جدول‌های سامانه',
        icon: 'bi-database',
        children: [
          { href: '/super-admin/database', label: 'نمای کلی جدول‌ها', icon: 'bi-grid-3x3-gap' },
          { href: '/super-admin/database/schools', label: 'مدارس', icon: 'bi-building' },
          { href: '/super-admin/database/users', label: 'کاربران', icon: 'bi-people' },
          { href: '/super-admin/database/students', label: 'دانش‌آموزان', icon: 'bi-person-badge' },
          { href: '/super-admin/database/teachers', label: 'معلمان', icon: 'bi-person-workspace' },
          { href: '/super-admin/database/grades', label: 'نمرات', icon: 'bi-patch-check' },
          { href: '/super-admin/database/sms_messages', label: 'پیامک‌ها', icon: 'bi-send' },
          { href: '/super-admin/database/partner_schools', label: 'مدارس همراه', icon: 'bi-stars' },
          { href: '/super-admin/database/audit_logs', label: 'رویدادها', icon: 'bi-shield-check' },
        ],
      },
    ],
  },
  {
    title: 'پایش',
    items: [
      { href: '/super-admin/status', label: 'وضعیت سیستم', icon: 'bi-activity' },
      { href: '/super-admin/media-servers', label: 'سرورهای رسانه', icon: 'bi-hdd-network' },
      { href: '/super-admin/reports', label: 'گزارش‌ها', icon: 'bi-bar-chart' },
      { href: '/super-admin/revenue', label: 'درآمد', icon: 'bi-cash-stack' },
      { href: '/super-admin/audit-logs', label: 'رویدادهای سیستم', icon: 'bi-shield-check' },
      { href: '/super-admin/login-logs', label: 'لاگ ورود کاربران', icon: 'bi-shield-lock' },
      { href: '/super-admin/inactive-schools', label: 'مدارس غیرفعال', icon: 'bi-building-exclamation' },
      { href: '/super-admin/db-optimizer', label: 'بهینه‌ساز پایگاه داده', icon: 'bi-database-gear' },
      { href: '/super-admin/sql', label: 'SQL خواندنی', icon: 'bi-terminal' },
    ],
  },
  {
    title: 'ابزار',
    items: [
      { href: '/super-admin/backup/download', label: 'دانلود پشتیبان', icon: 'bi-cloud-download' },
    ],
  },
];

const schoolAdminNav: NavSection[] = [
  {
    title: 'نمای کلی',
    items: [{ href: '/school', label: 'داشبورد مدرسه', icon: 'bi-speedometer2' }],
  },
  {
    title: 'افراد',
    items: [
      { href: '/school/users', label: 'کاربران مدرسه', icon: 'bi-people' },
      { href: '/school/students', label: 'دانش‌آموزان', icon: 'bi-person-badge' },
      { href: '/school/teachers', label: 'معلمان', icon: 'bi-person-workspace' },
      { href: '/school/access', label: 'مدیریت دسترسی‌ها', icon: 'bi-person-lock' },
      { href: '/school/credentials', label: 'چاپ کارت ورود', icon: 'bi-printer' },
      { href: '/school/password-reset', label: 'بازنشانی رمز عبور', icon: 'bi-key' },
    ],
  },
  {
    title: 'آموزش',
    items: [
      { href: '/school/classes', label: 'کلاس‌ها', icon: 'bi-door-open' },
      { href: '/school/subjects', label: 'درس‌ها', icon: 'bi-book' },
      { href: '/school/schedule', label: 'برنامه هفتگی', icon: 'bi-calendar2-week' },
      { href: '/school/substitutes', label: 'جانشین معلم', icon: 'bi-person-workspace' },
    ],
  },
  {
    title: 'ارزیابی',
    items: [
      { href: '/school/attendance/absences', label: 'موجه کردن غیبت', icon: 'bi-person-check', module: 'attendance' },
      { href: '/school/attendance/excuse-requests', label: 'درخواست‌های موجه', icon: 'bi-shield-check', module: 'attendance' },
      { href: '/school/students/promote', label: 'ارتقاء پایه', icon: 'bi-arrow-up-circle' },
      { href: '/school/grades', label: 'تایید نمرات', icon: 'bi-patch-check' },
      { href: '/school/grade-logs', label: 'گزارش تغییرات نمره', icon: 'bi-clock-history' },
      { href: '/school/analytics', label: 'آمار و تحلیل', icon: 'bi-bar-chart-line' },
      { href: '/school/grade-weights', label: 'وزن نمرات', icon: 'bi-sliders', module: 'grades' },
      { href: '/school/students/at-risk', label: 'دانش‌آموزان در معرض خطر', icon: 'bi-exclamation-triangle', module: 'grades' },
      { href: '/school/report-card', label: 'کارنامه', icon: 'bi-file-earmark-bar-graph' },
      { href: '/school/awards', label: 'تقدیرنامه‌ها', icon: 'bi-award' },
      { href: '/school/eteraz', label: 'اعتراضات نمره', icon: 'bi-megaphone' },
      { href: '/school/discipline', label: 'پرونده انضباطی', icon: 'bi-clipboard-pulse' },
      { href: '/school/absence-report', label: 'دانش‌آموزان پرغیبت', icon: 'bi-person-x', module: 'attendance' },
    ],
  },
  {
    title: 'ارتباطات',
    items: [
      { href: '/school/messages', label: 'پیام‌رسانی', icon: 'bi-envelope' },
      { href: '/school/news', label: 'اخبار داشبورد', icon: 'bi-newspaper' },
      { href: '/school/online-classes', label: 'کلاس آنلاین', icon: 'bi-camera-video' },
    ],
  },
  {
    title: 'پیامک',
    items: [
      {
        key: 'sms',
        label: 'سامانه پیامک',
        icon: 'bi-chat-dots',
        children: [
          { href: '/school/sms-wallet', label: 'کیف پول پیامک', icon: 'bi-wallet2' },
          { href: '/school/sms-absents', label: 'پیامک غیبت', icon: 'bi-send' },
          { href: '/school/sms-templates', label: 'قالب‌های پیامک', icon: 'bi-file-text' },
        ],
      },
    ],
  },
  {
    title: 'داده‌ها',
    items: [
      { href: '/school/files', label: 'فایل‌ها', icon: 'bi-folder2' },
      { href: '/school/api-tokens', label: 'توکن API', icon: 'bi-key' },
      {
        key: 'imports',
        label: 'ورود اطلاعات',
        icon: 'bi-box-arrow-in-down',
        children: [
          { href: '/school/import/students', label: 'دانش‌آموزان', icon: 'bi-person-badge' },
          { href: '/school/import/teachers', label: 'معلمان', icon: 'bi-person-workspace' },
          { href: '/school/import/users', label: 'کاربران', icon: 'bi-people' },
        ],
      },
      { href: '/school/exports', label: 'مرکز خروجی داده', icon: 'bi-download' },
    ],
  },
  {
    title: 'مشارکت',
    items: [
      { href: '/school/voting', label: 'رأی‌گیری', icon: 'bi-check2-square' },
      { href: '/school/clubs', label: 'باشگاه‌ها', icon: 'bi-stars' },
    ],
  },
  {
    title: 'پایش',
    items: [
      { href: '/school/user-activity', label: 'فعالیت کاربران', icon: 'bi-activity' },
      { href: '/school/reports', label: 'گزارش‌ها', icon: 'bi-bar-chart' },
      { href: '/school/homework-reports', label: 'گزارش تکالیف', icon: 'bi-journal-check' },
      { href: '/school/support-tickets', label: 'پشتیبانی', icon: 'bi-life-preserver' },
      { href: '/school/audit-logs', label: 'رویدادهای مدرسه', icon: 'bi-clock-history' },
      { href: '/school/attendance-minutes', label: 'دقایق حضور آنلاین', icon: 'bi-stopwatch' },
      { href: '/school/years', label: 'سال تحصیلی', icon: 'bi-calendar2-range' },
    ],
  },
  {
    title: 'تنظیمات',
    items: [{ href: '/school/settings', label: 'تنظیمات مدرسه', icon: 'bi-gear' }],
  },
];

const teacherNav: NavSection[] = [
  {
    title: 'نمای کلی',
    items: [{ href: '/teacher', label: 'داشبورد معلم', icon: 'bi-speedometer2' }],
  },
  {
    title: 'آموزش',
    items: [
      { href: '/teacher/students', label: 'لیست دانش‌آموزان', icon: 'bi-people', permission: 'students.view' },
      { href: '/teacher/schedule', label: 'برنامه هفتگی', icon: 'bi-calendar2-week', module: 'schedule' as const },
      { href: '/teacher/calendar', label: 'تقویم کاری', icon: 'bi-calendar-event' },
      { href: '/teacher/homeworks', label: 'تکالیف', icon: 'bi-journal-check', permission: 'homework.create' },
      { href: '/teacher/exams', label: 'امتحانات', icon: 'bi-pencil-square', permission: 'exams.online.create' },
      { href: '/teacher/question-bank', label: 'بانک سوال', icon: 'bi-collection', permission: 'exams.online.create' },
      { href: '/school/online-classes', label: 'کلاس آنلاین', icon: 'bi-camera-video' },
    ],
  },
  {
    title: 'ارزیابی',
    items: [
      { href: '/teacher/grades', label: 'نمره‌دهی', icon: 'bi-patch-check', module: 'grades' as const, permission: 'grades.create' },
      { href: '/teacher/grades/bulk', label: 'ثبت گروهی نمرات', icon: 'bi-table', module: 'grades' as const, permission: 'grades.create' },
      { href: '/teacher/grade-sheet', label: 'کارنامه گروهی کلاس', icon: 'bi-grid-3x3-gap', module: 'grades' as const, permission: 'grades.create' },
      { href: '/teacher/class-stats', label: 'آمار نمرات کلاس', icon: 'bi-bar-chart-line', module: 'grades' as const, permission: 'grades.create' },
      { href: '/teacher/attendance-classes', label: 'حضور و غیاب', icon: 'bi-clipboard-check', module: 'attendance' as const, permission: 'attendance.create' },
    ],
  },
  {
    title: 'ارتباطات',
    items: [{ href: '/school/messages', label: 'پیام‌ها', icon: 'bi-envelope', module: 'messages' as const }],
  },
];

const studentNav: NavSection[] = [
  {
    title: 'نمای کلی',
    items: [{ href: '/student', label: 'داشبورد من', icon: 'bi-house' }],
  },
  {
    title: 'درس و کلاس',
    items: [
      { href: '/student/classes', label: 'کلاس‌های من', icon: 'bi-door-open' },
      { href: '/student/schedule', label: 'برنامه هفتگی', icon: 'bi-calendar2-week' },
      { href: '/student/upcoming', label: 'برنامه آینده', icon: 'bi-calendar-check' },
      { href: '/student/exams', label: 'امتحانات', icon: 'bi-pencil-square' },
      { href: '/student/homeworks', label: 'تکالیف', icon: 'bi-journal-check' },
    ],
  },
  {
    title: 'کارنامه من',
    items: [
      { href: '/student/report-card', label: 'کارنامه', icon: 'bi-file-earmark-bar-graph' },
      { href: '/student/grades', label: 'نمرات (همه)', icon: 'bi-patch-check' },
      { href: '/student/attendance', label: 'حضور و غیاب', icon: 'bi-clipboard-check', module: 'attendance' as const },
      { href: '/student/attendance-hours', label: 'ساعت حضور', icon: 'bi-stopwatch', module: 'attendance' as const },
    ],
  },
  {
    title: 'مشارکت',
    items: [{ href: '/student/voting', label: 'رأی‌گیری', icon: 'bi-check2-square' }],
  },
  {
    title: 'ارتباطات',
    items: [{ href: '/student/messages', label: 'پیام‌ها', icon: 'bi-envelope', module: 'messages' as const }],
  },
];

const supportNav: NavSection[] = [
  {
    title: 'پشتیبانی',
    items: [
      { href: '/school', label: 'داشبورد', icon: 'bi-speedometer2' },
      { href: '/school/users', label: 'کاربران', icon: 'bi-people' },
      { href: '/school/students', label: 'دانش‌آموزان', icon: 'bi-person-badge' },
      { href: '/school/audit-logs', label: 'رویدادها', icon: 'bi-clock-history' },
    ],
  },
];

const financeNav: NavSection[] = [
  {
    title: 'مالی',
    items: [
      { href: '/school', label: 'داشبورد', icon: 'bi-speedometer2' },
      { href: '/school/sms-wallet', label: 'کیف پول پیامک', icon: 'bi-wallet2' },
      { href: '/school/exports', label: 'مرکز خروجی داده', icon: 'bi-download' },
    ],
  },
];

const rootLinks: Record<string, boolean> = {
  '/school': true,
  '/super-admin': true,
  '/teacher': true,
  '/student': true,
  '/super-admin/database': true,
};

const GROUPS_STORAGE_KEY = 'daneshyar-sidebar-groups';

function loadGroupState(): Record<string, boolean> {
  try {
    return JSON.parse(localStorage.getItem(GROUPS_STORAGE_KEY) ?? '{}');
  } catch {
    return {};
  }
}

export function DashboardSidebar() {
  const { props, url } = usePage<{ auth?: { user?: AuthUser }; modules?: ModuleKey[]; permissions?: string[] }>();
  const roleKey = props.auth?.user?.roleKey ?? '';
  const enabledModules = props.modules ?? [];
  const permissions = props.permissions ?? [];

  const sections: NavSection[] = useMemo(() => {
    const roleNav: NavSection[] =
      roleKey === 'super_admin' ? superAdminNav
      : ['owner', 'principal', 'moaven'].includes(roleKey) ? schoolAdminNav
      : roleKey === 'support' ? supportNav
      : roleKey === 'finance' ? financeNav
      : roleKey === 'teacher' ? teacherNav
      : roleKey === 'student' ? studentNav
      : [{ title: 'منو', items: [{ href: '/dashboard', label: 'داشبورد', icon: 'bi-house' }] }];

    // Strip anything this user lacks the permission for, then drop groups and
    // sections left empty by that stripping.
    const allowed = (leaf: NavLeaf) => !leaf.permission || permissions.includes(leaf.permission);

    return roleNav
      .map((section) => ({
        title: section.title,
        items: section.items.flatMap<NavItem>((item) => {
          if (isGroup(item)) {
            const children = item.children.filter(allowed);
            return children.length > 0 ? [{ ...item, children }] : [];
          }
          return allowed(item) ? [item] : [];
        }),
      }))
      .filter((section) => section.items.length > 0);
  }, [roleKey, permissions]);

  const [query, setQuery] = useState('');
  const [openGroups, setOpenGroups] = useState<Record<string, boolean>>(() => loadGroupState());
  const navRef = useRef<HTMLElement>(null);
  const navContentRef = useRef<HTMLDivElement>(null);
  const navScrollAnimationRef = useRef<number | null>(null);
  const [canScrollDown, setCanScrollDown] = useState(false);
  const navScrollStorageKey = `daneshyar-sidebar-scroll:${props.auth?.user?.id ?? 'guest'}:${roleKey}`;

  const updateScrollIndicator = useCallback(() => {
    const nav = navRef.current;
    if (!nav) return;

    const remainingScroll = nav.scrollHeight - nav.scrollTop - nav.clientHeight;
    setCanScrollDown(remainingScroll > 2);
  }, []);

  const handleNavScroll = useCallback(() => {
    updateScrollIndicator();

    const nav = navRef.current;
    if (!nav) return;

    try {
      sessionStorage.setItem(navScrollStorageKey, String(nav.scrollTop));
    } catch {
      /* sessionStorage ممکن است در حالت خصوصی بسته باشد */
    }
  }, [navScrollStorageKey, updateScrollIndicator]);

  const scrollSidebarDown = useCallback(() => {
    const nav = navRef.current;
    if (!nav) return;

    if (navScrollAnimationRef.current !== null) {
      window.cancelAnimationFrame(navScrollAnimationRef.current);
    }

    const startTop = nav.scrollTop;
    const remaining = nav.scrollHeight - nav.clientHeight - startTop;
    const distance = Math.min(remaining, Math.max(170, Math.round(nav.clientHeight * 0.58)));
    if (distance <= 0) return;

    const startedAt = performance.now();
    const duration = 720;
    const animate = (now: number) => {
      const progress = Math.min(1, (now - startedAt) / duration);
      const eased = progress < 0.5
        ? 4 * progress * progress * progress
        : 1 - Math.pow(-2 * progress + 2, 3) / 2;

      nav.scrollTop = startTop + distance * eased;

      if (progress < 1) {
        navScrollAnimationRef.current = window.requestAnimationFrame(animate);
      } else {
        navScrollAnimationRef.current = null;
        updateScrollIndicator();
      }
    };

    navScrollAnimationRef.current = window.requestAnimationFrame(animate);
  }, [updateScrollIndicator]);

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

    let savedScrollTop = 0;
    try {
      const storedValue = Number(sessionStorage.getItem(navScrollStorageKey));
      if (Number.isFinite(storedValue) && storedValue > 0) savedScrollTop = storedValue;
    } catch {
      /* sessionStorage ممکن است در حالت خصوصی بسته باشد */
    }

    const restoreScroll = () => {
      nav.scrollTop = savedScrollTop;
      updateScrollIndicator();
    };

    restoreScroll();
    const animationFrame = window.requestAnimationFrame(restoreScroll);
    const contentSettledTimer = window.setTimeout(restoreScroll, 280);

    return () => {
      window.cancelAnimationFrame(animationFrame);
      window.clearTimeout(contentSettledTimer);
    };
  }, [navScrollStorageKey, updateScrollIndicator]);

  useEffect(() => {
    const nav = navRef.current;
    const content = navContentRef.current;
    if (!nav || !content) return;

    updateScrollIndicator();
    window.addEventListener('resize', updateScrollIndicator);

    const cancelAnimatedScroll = () => {
      if (navScrollAnimationRef.current !== null) {
        window.cancelAnimationFrame(navScrollAnimationRef.current);
        navScrollAnimationRef.current = null;
      }
    };
    nav.addEventListener('wheel', cancelAnimatedScroll, { passive: true });
    nav.addEventListener('touchstart', cancelAnimatedScroll, { passive: true });
    nav.addEventListener('pointerdown', cancelAnimatedScroll, { passive: true });

    const resizeObserver = typeof ResizeObserver === 'undefined'
      ? null
      : new ResizeObserver(updateScrollIndicator);
    resizeObserver?.observe(nav);
    resizeObserver?.observe(content);

    return () => {
      window.removeEventListener('resize', updateScrollIndicator);
      nav.removeEventListener('wheel', cancelAnimatedScroll);
      nav.removeEventListener('touchstart', cancelAnimatedScroll);
      nav.removeEventListener('pointerdown', cancelAnimatedScroll);
      resizeObserver?.disconnect();
      if (navScrollAnimationRef.current !== null) {
        window.cancelAnimationFrame(navScrollAnimationRef.current);
        navScrollAnimationRef.current = null;
      }
    };
  }, [updateScrollIndicator]);

  function isActive(href: string): boolean {
    const path = url.split('?')[0];
    if (rootLinks[href]) return path === href;
    return path === href || path.startsWith(href + '/');
  }

  // گروه دارای لینک فعال، خودکار باز بماند
  useEffect(() => {
    const forced: Record<string, boolean> = {};
    for (const section of sections) {
      for (const item of section.items) {
        if (isGroup(item) && item.children.some((child) => isActive(child.href))) {
          forced[item.key] = true;
        }
      }
    }
    if (Object.keys(forced).length > 0) {
      setOpenGroups((prev) => ({ ...prev, ...forced }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [url, sections]);

  const toggleGroup = (key: string) => {
    setOpenGroups((prev) => {
      const next = { ...prev, [key]: !prev[key] };
      try {
        localStorage.setItem(GROUPS_STORAGE_KEY, JSON.stringify(next));
      } catch {
        /* localStorage ممکن است در حالت خصوصی بسته باشد */
      }
      return next;
    });
  };

  const trimmedQuery = query.trim();

  const filteredSections: NavSection[] = useMemo(() => {
    if (!trimmedQuery) return sections;
    const matches = (label: string) => label.includes(trimmedQuery);
    return sections
      .map((section) => ({
        title: section.title,
        items: section.items.flatMap<NavItem>((item) => {
          if (isGroup(item)) {
            const children = item.children.filter((child) => matches(child.label));
            if (matches(item.label)) return [item];
            return children.length > 0 ? [{ ...item, children }] : [];
          }
          return matches(item.label) ? [item] : [];
        }),
      }))
      .filter((section) => section.items.length > 0);
  }, [sections, trimmedQuery]);

  const isModuleLocked = (leaf: NavLeaf): boolean => !!leaf.module && !enabledModules.includes(leaf.module);

  const renderLeaf = (leaf: NavLeaf, nested = false) => {
    const locked = isModuleLocked(leaf);

    return (
      <Link
        key={leaf.href + leaf.label}
        href={leaf.href}
        className={`side-link${nested ? ' side-link--sub' : ''}${isActive(leaf.href) ? ' active' : ''}${locked ? ' side-link--locked' : ''}`}
        title={locked ? 'این بخش برای مدرسه شما فعال نیست' : undefined}
      >
        <span className="side-icon"><i className={`bi ${leaf.icon}`} aria-hidden="true" /></span>
        <span className="side-label">{leaf.label}</span>
        {locked && <i className="bi bi-lock-fill side-lock-badge" aria-label="غیرفعال" />}
      </Link>
    );
  };

  return (
    <div className="sidebar-body">
      <div className="sidebar-search">
        <i className="bi bi-search" aria-hidden="true" />
        <input
          type="text"
          value={query}
          placeholder="جستجو در منو..."
          onChange={(event) => setQuery(event.target.value)}
          onKeyDown={(event) => { if (event.key === 'Escape') setQuery(''); }}
          aria-label="جستجو در منو"
        />
        {query && (
          <button type="button" className="sidebar-search-clear" aria-label="پاک کردن جستجو" onClick={() => setQuery('')}>
            <i className="bi bi-x-lg" />
          </button>
        )}
      </div>

      <div className="sidebar-nav-wrap">
        <nav
          ref={navRef}
          id="dashboard-sidebar-nav"
          className="sidebar-nav"
          aria-label="منوی اصلی"
          onScroll={handleNavScroll}
        >
          <div ref={navContentRef} className="sidebar-nav-content">
            {filteredSections.length === 0 && (
              <p className="sidebar-empty">موردی یافت نشد.</p>
            )}
            {filteredSections.map((section) => (
              <div className="side-section" key={section.title}>
                <span className="side-kicker">{section.title}</span>
                {section.items.map((item) => {
                  if (!isGroup(item)) return renderLeaf(item);

                  const opened = trimmedQuery !== '' || !!openGroups[item.key];
                  const groupActive = item.children.some((child) => isActive(child.href));

                  return (
                    <div key={item.key} className="side-group">
                      <button
                        type="button"
                        className={`side-link side-group-btn${groupActive ? ' active' : ''}`}
                        aria-expanded={opened}
                        onClick={() => toggleGroup(item.key)}
                      >
                        <span className="side-icon"><i className={`bi ${item.icon}`} aria-hidden="true" /></span>
                        <span className="side-label">{item.label}</span>
                        <i className={`bi bi-chevron-down side-chevron${opened ? ' open' : ''}`} aria-hidden="true" />
                      </button>
                      <AnimatePresence initial={false}>
                        {opened && (
                          <motion.div
                            className="side-children"
                            initial={{ height: 0, opacity: 0 }}
                            animate={{ height: 'auto', opacity: 1 }}
                            exit={{ height: 0, opacity: 0 }}
                            transition={{ duration: 0.22, ease: 'easeOut' }}
                          >
                            {item.children.map((child) => renderLeaf(child, true))}
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </div>
                  );
                })}
              </div>
            ))}
          </div>
        </nav>

        {canScrollDown && (
          <button
            type="button"
            className="sidebar-scroll-down"
            aria-label="نمایش گزینه‌های بیشتر"
            aria-controls="dashboard-sidebar-nav"
            title="گزینه‌های بیشتر"
            onClick={scrollSidebarDown}
          >
            <svg
              className="sidebar-scroll-down-icon"
              viewBox="0 0 32 18"
              fill="none"
              aria-hidden="true"
            >
              <path d="M4 3.5 16 14.5 28 3.5" />
            </svg>
          </button>
        )}
      </div>
    </div>
  );
}
