// app/components/admin/Sidebar.tsx
'use client';

import { useState, useMemo, useCallback, memo, ReactNode } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { usePermissions } from '@/hooks/usePermissions';

interface SidebarProps {
  isOpen: boolean;
  onClose: () => void;
}

interface MenuItem {
  name: string;
  href: string;
  icon: ReactNode;
  permissions?: string[];
  badge?: string;
  badgeColor?: string;
  children?: MenuItem[];
}

const menuStructure: MenuItem[] = [
  {
    name: 'Dashboard',
    href: '/admin/dashboard',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
      </svg>
    ),
  },
  {
    name: 'Website Management',
    href: '/admin/dashboard/websites',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    ),
    permissions: ['websites:read'],
    children: [
      {
        name: 'All Websites',
        href: '/admin/dashboard/websites',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
        ),
        permissions: ['websites:read'],
      },
      {
        name: 'Add Website',
        href: '/admin/dashboard/websites/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
        ),
        permissions: ['websites:create'],
      },
    ],
  },
  {
    name: 'Package Management',
    href: '/admin/dashboard/packages',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
      </svg>
    ),
    permissions: ['packages:read'],
    children: [
      {
        name: 'All Packages',
        href: '/admin/dashboard/packages',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
        ),
        permissions: ['packages:read'],
      },
      {
        name: 'Add Package',
        href: '/admin/dashboard/packages/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
        ),
        permissions: ['packages:create'],
      },
    ],
  },
  {
    name: 'Category',
    href: '/admin/dashboard/categories',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
      </svg>
    ),
    permissions: ['categories:read'],
    children: [
      {
        name: 'All Categories',
        href: '/admin/dashboard/categories',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
          </svg>
        ),
        permissions: ['categories:read'],
      },
      {
        name: 'Add Category',
        href: '/admin/dashboard/categories/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
        ),
        permissions: ['categories:create'],
      },
    ],
  },
  {
    name: 'Audit Leads',
    href: '/admin/dashboard/audit-leads',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
      </svg>
    ),
    permissions: ['leads:view'],
  },
  {
    name: 'Custom Plans',
    href: '/admin/dashboard/custom-plans',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
      </svg>
    ),
    permissions: ['custom_plans:view'],
  },
  {
    name: 'Orders',
    href: '/admin/dashboard/orders',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
      </svg>
    ),
    permissions: ['orders:read'],
  },
  {
    name: 'Support Tickets',
    href: '/admin/dashboard/support',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
      </svg>
    ),
    permissions: ['support:view'],
  },
  {
    name: 'Pages',
    href: '/admin/dashboard/pages',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z" />
      </svg>
    ),
    permissions: ['pages:read'],
    children: [
      {
        name: 'All Pages',
        href: '/admin/dashboard/pages',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
          </svg>
        ),
        permissions: ['pages:read'],
      },
      {
        name: 'Add New Page',
        href: '/admin/dashboard/pages/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
        ),
        permissions: ['pages:create'],
      },
    ],
  },
  {
    name: 'Posts',
    href: '/admin/dashboard/posts',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 12h8M7 8h6" />
      </svg>
    ),
    permissions: ['content:read'],
    children: [
      {
        name: 'All Posts',
        href: '/admin/dashboard/posts',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
          </svg>
        ),
        permissions: ['content:read'],
      },
      {
        name: 'Add New Post',
        href: '/admin/dashboard/posts/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
          </svg>
        ),
        permissions: ['content:create'],
      },
    ],
  },
  {
    name: 'Authors',
    href: '/admin/dashboard/authors',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0z" />
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
      </svg>
    ),
    permissions: ['authors:read'],
    children: [
      {
        name: 'All Authors',
        href: '/admin/dashboard/authors',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0z" />
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
          </svg>
        ),
        permissions: ['authors:read'],
      },
      {
        name: 'Add New Author',
        href: '/admin/dashboard/authors/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0z" />
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 8v4M17 10h4" />
          </svg>
        ),
        permissions: ['authors:create'],
      },
    ],
  },
  {
    name: 'Sidebar Widgets',
    href: '/admin/dashboard/sidebars',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z" />
      </svg>
    ),
    permissions: ['sidebars:read'],
    children: [
      {
        name: 'All Sidebar Widgets',
        href: '/admin/dashboard/sidebars',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM8 10h8M8 14h5" />
          </svg>
        ),
        permissions: ['sidebars:read'],
      },
      {
        name: 'Add New Sidebar Widget',
        href: '/admin/dashboard/sidebars/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
        ),
        permissions: ['sidebars:create'],
      },
    ],
  },
  {
    name: 'Menu',
    href: '/admin/dashboard/menus',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
      </svg>
    ),
    permissions: ['menus:read'],
    children: [
      {
        name: 'All Menus',
        href: '/admin/dashboard/menus',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM8 10h8M8 14h5" />
          </svg>
        ),
        permissions: ['sidebars:read'],
      },
      {
        name: 'Add New Menu',
        href: '/admin/dashboard/menus/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
        ),
        permissions: ['menus:create'],
      },
    ],
  },
  {
    name: 'Employee Management',
    href: '/admin/dashboard/employees',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z" />
      </svg>
    ),
    permissions: ['employees:read'],
    badge: 'New',
    children: [
      {
        name: 'All Employees',
        href: '/admin/dashboard/employees',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
          </svg>
        ),
        permissions: ['employees:read'],
      },
      {
        name: 'Add Employee',
        href: '/admin/dashboard/employees/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
        ),
        permissions: ['employees:create'],
      },
      {
        name: 'Roles',
        href: '/admin/dashboard/employees/roles',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
        ),
        permissions: ['roles:read'],
      },
      {
        name: 'Permissions',
        href: '/admin/dashboard/employees/permissions',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
        ),
      },
    ],
  },
  {
    name: 'Redirects',
    href: '/admin/dashboard/redirects',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
      </svg>
    ),
    permissions: ['redirects:read'],
    children: [
      {
        name: 'All Redirects',
        href: '/admin/dashboard/redirects',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
          </svg>
        ),
        permissions: ['redirects:read'],
      },
      {
        name: 'Add New Redirect',
        href: '/admin/dashboard/redirects/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
        ),
        permissions: ['redirects:create'],
      },
    ],
  },
  {
    name: 'Users',
    href: '/admin/dashboard/users',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
      </svg>
    ),
    permissions: ['users:read'],
    children: [
      {
        name: 'All users',
        href: '/admin/dashboard/users',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
          </svg>
        ),
        permissions: ['users:read'],
      },
      {
        name: 'Add New User',
        href: '/admin/dashboard/users/new',
        icon: (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
        ),
        permissions: ['users:create'],
      },
    ],
  },
  {
    name: 'Audit Logs',
    href: '/admin/dashboard/audit-logs',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
      </svg>
    ),
    permissions: ['audit:read'],
  },
  {
    name: 'Profile Settings',
    href: '/admin/dashboard/profile',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
      </svg>
    ),
    permissions: ['profile:read'],
  },
  {
    name: 'General Settings',
    href: '/admin/dashboard/settings',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
      </svg>
    ),
    permissions: ['settings:read'],
  },
];

interface MenuItemProps {
  item: MenuItem;
  isActive: boolean;
  isExpanded: boolean;
  isCollapsed: boolean;
  filteredChildren: MenuItem[];
  onToggle: (name: string) => void;
  onClose: () => void;
  pathname: string;
}

const MenuItemComponent = memo(function MenuItemComponent({
  item,
  isActive,
  isExpanded,
  isCollapsed,
  filteredChildren,
  onToggle,
  onClose,
  pathname,
}: MenuItemProps) {
  const hasChildren = filteredChildren.length > 0;

  if (isCollapsed) {
    return (
      <div className="relative group/tooltip">
        <Link
          href={item.href}
          onClick={onClose}
          title={item.name}
          className={`
            flex items-center justify-center w-10 h-10 mx-auto rounded-xl transition-all duration-200
            ${isActive
              ? 'bg-var-primary text-white shadow-var-card'
              : 'text-var-sidebar-icon hover:bg-var-sidebar-item-hover hover:text-var-sidebar-icon-active'
            }
          `}
        >
          {item.icon}
        </Link>
        <div className="absolute left-full ml-3 top-1/2 -translate-y-1/2 z-50 pointer-events-none opacity-0 group-hover/tooltip:opacity-100 transition-opacity duration-150">
          <div className="bg-var-surface text-var-text text-xs font-medium px-2.5 py-1.5 rounded-lg whitespace-nowrap shadow-var-modal border border-var-border">
            {item.name}
            <div className="absolute right-full top-1/2 -translate-y-1/2 border-4 border-transparent border-r-var-surface" />
          </div>
        </div>
      </div>
    );
  }

  if (!hasChildren) {
    return (
      <Link
        href={item.href}
        onClick={onClose}
        className={`
          group flex items-center justify-between px-3 py-2 text-sm font-medium rounded-xl transition-all duration-200
          ${isActive
            ? 'bg-var-primary text-white shadow-var-card'
            : 'text-var-sidebar-item-text hover:bg-var-sidebar-item-hover hover:text-var-sidebar-item-text-hover'
          }
        `}
      >
        <div className="flex items-center space-x-3 flex-1 min-w-0">
          <div className={`shrink-0 ${isActive ? 'text-white' : 'text-var-sidebar-icon group-hover:text-var-sidebar-icon-active'}`}>
            {item.icon}
          </div>
          <span className="truncate" style={{ color: isActive ? 'white' : 'var(--sidebar-item-text)' }}>{item.name}</span>
        </div>
        {item.badge && (
          <span className={`text-xs px-2 py-0.5 rounded-full shrink-0 ${isActive ? 'bg-white/20 text-white' : 'bg-var-primary-muted text-var-primary-text'}`}>
            {item.badge}
          </span>
        )}
      </Link>
    );
  }

  return (
    <div>
      <button
        type="button"
        onClick={() => onToggle(item.name)}
        className={`
          w-full group flex items-center justify-between px-3 py-2 text-sm font-medium rounded-xl transition-all duration-200
          ${isActive
            ? 'bg-var-primary text-white shadow-var-card'
            : 'text-var-sidebar-item-text hover:bg-var-sidebar-item-hover hover:text-var-sidebar-item-text-hover'
          }
        `}
      >
        <div className="flex items-center space-x-3 flex-1 min-w-0">
          <div className={`shrink-0 ${isActive ? 'text-white' : 'text-var-sidebar-icon group-hover:text-var-sidebar-icon-active'}`}>
            {item.icon}
          </div>
          <span className="truncate" style={{ color: isActive ? 'white' : 'var(--sidebar-item-text)' }}>{item.name}</span>
        </div>
        <div className="flex items-center space-x-2 shrink-0">
          {item.badge && (
            <span className={`text-xs px-2 py-0.5 rounded-full ${isActive ? 'bg-white/20 text-white' : 'bg-var-primary-muted text-var-primary-text'}`}>
              {item.badge}
            </span>
          )}
          <motion.svg
            className={`w-4 h-4 ${isActive ? 'text-white' : 'text-var-text-muted'}`}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
            animate={{ rotate: isExpanded ? 180 : 0 }}
            transition={{ duration: 0.2 }}
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </motion.svg>
        </div>
      </button>

      <AnimatePresence initial={false}>
        {isExpanded && (
          <motion.div
            key="children"
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            transition={{ duration: 0.2, ease: 'easeInOut' }}
            className="overflow-hidden"
          >
            <div className="mt-1 ml-4 space-y-1 border-l-2 border-var-border pl-2">
              {filteredChildren.map((child) => {
                const childActive = pathname === child.href;
                return (
                  <Link
                    key={child.href}
                    href={child.href}
                    onClick={onClose}
                    className={`
                      group flex items-center space-x-3 px-3 py-2 text-sm rounded-lg transition-all duration-200
                      ${childActive
                        ? 'bg-var-primary-muted text-var-sidebar-child-text-active font-medium'
                        : 'text-var-sidebar-child-text hover:bg-var-sidebar-item-hover hover:text-var-sidebar-item-text-hover'
                      }
                    `}
                  >
                    <div className={`shrink-0 ${childActive ? 'text-var-primary' : 'text-var-sidebar-icon group-hover:text-var-sidebar-icon-active'}`}>
                      {child.icon}
                    </div>
                    <span style={{ color: childActive ? 'var(--sidebar-child-text-active)' : 'var(--sidebar-child-text)' }}>
                      {child.name}
                    </span>
                  </Link>
                );
              })}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
});

interface SidebarContentProps {
  filteredMenuItems: MenuItem[];
  expandedItems: Set<string>;
  onToggle: (name: string) => void;
  onClose: () => void;
  isCollapsed: boolean;
  onCollapseToggle?: () => void;
  pathname: string;
  searchQuery: string;
  onSearchChange: (v: string) => void;
  getFilteredChildren: (children?: MenuItem[]) => MenuItem[];
}

const SidebarContent = memo(function SidebarContent({
  filteredMenuItems,
  expandedItems,
  onToggle,
  onClose,
  isCollapsed,
  onCollapseToggle,
  pathname,
  searchQuery,
  onSearchChange,
  getFilteredChildren,
}: SidebarContentProps) {
  const isItemActive = (item: MenuItem) => {
    if (pathname === item.href) return true;
    return item.children?.some((c) => pathname === c.href) ?? false;
  };

  return (
    <div className="flex flex-col flex-1 min-h-0 bg-var-sidebar border-r border-var-sidebar-border shadow-var-card h-full">
      <div className={`flex items-center h-20 shrink-0 px-4 bg-var-primary shadow-var-card ${isCollapsed ? 'justify-center' : 'justify-between'}`}>
        <div className="flex items-center space-x-3">
          <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center backdrop-blur-sm shrink-0">
            <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
          </div>
          {!isCollapsed && (
            <div>
              <div className="text-white text-xl font-bold">AdminHub</div>
              <div className="text-var-primary-light text-xs font-medium">Admin Panel</div>
            </div>
          )}
        </div>
        {onCollapseToggle && (
          <button
            onClick={onCollapseToggle}
            title={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}
            className="text-white/70 hover:text-white transition-colors p-1.5 hover:bg-white/10 rounded-lg"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              {isCollapsed ? (
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 5l7 7-7 7M5 5l7 7-7 7" />
              ) : (
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 19l-7-7 7-7m8 14l-7-7 7-7" />
              )}
            </svg>
          </button>
        )}
      </div>

      {!isCollapsed && (
        <div className="p-4 border-b border-var-sidebar-border">
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg className="h-4 w-4 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
            </div>
            <input
              type="text"
              name="sidebar-search"
              placeholder="Search menu..."
              value={searchQuery}
              onChange={(e) => onSearchChange(e.target.value)}
              autoComplete="off"
              className="block w-full pl-10 pr-8 py-2.5 border border-var-border rounded-xl bg-var-surface focus:ring-2 focus:ring-var-primary focus:border-var-primary text-var-text text-sm transition-all duration-200 placeholder-var-input"
            />
            {searchQuery && (
              <button
                onClick={() => onSearchChange('')}
                className="absolute inset-y-0 right-0 pr-3 flex items-center"
              >
                <svg className="h-4 w-4 text-var-text-muted hover:text-var-text" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            )}
          </div>
        </div>
      )}

      <div className="flex-1 overflow-y-auto">
        <nav className={`py-4 space-y-1 ${isCollapsed ? 'px-2' : 'px-4'}`}>
          {filteredMenuItems.length > 0 ? (
            filteredMenuItems.map((item) => (
              <MenuItemComponent
                key={item.name}
                item={item}
                isActive={isItemActive(item)}
                isExpanded={expandedItems.has(item.name)}
                isCollapsed={isCollapsed}
                filteredChildren={getFilteredChildren(item.children)}
                onToggle={onToggle}
                onClose={onClose}
                pathname={pathname}
              />
            ))
          ) : (
            <div className="text-center py-8">
              <svg className="w-12 h-12 text-var-text-muted mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <p className="text-var-text-secondary text-sm">No menu items found</p>
              <p className="text-var-text-muted text-xs mt-1">Try adjusting your search</p>
            </div>
          )}
        </nav>
      </div>
    </div>
  );
});

export default function Sidebar({ isOpen, onClose }: SidebarProps) {
  const pathname = usePathname();
  const [searchQuery, setSearchQuery] = useState('');
  const [isCollapsed, setIsCollapsed] = useState(false);
  const { hasAnyPermission } = usePermissions();

  const [expandedItems, setExpandedItems] = useState<Set<string>>(() => {
    const initial = new Set<string>();
    menuStructure.forEach((item) => {
      if (item.children?.some((c) => pathname === c.href)) {
        initial.add(item.name);
      }
    });
    return initial;
  });

  const getFilteredChildren = useCallback(
    (children: MenuItem[] = []) =>
      children.filter((c) => !c.permissions || hasAnyPermission(c.permissions)),
    [hasAnyPermission]
  );

  const filteredMenuItems = useMemo(() => {
    return menuStructure.filter((item) => {
      if (item.permissions && !hasAnyPermission(item.permissions)) return false;
      if (searchQuery) {
        const q = searchQuery.toLowerCase();
        const nameMatch = item.name.toLowerCase().includes(q);
        const childMatch = item.children?.some((c) => c.name.toLowerCase().includes(q));
        if (!nameMatch && !childMatch) return false;
      }
      return true;
    });
  }, [searchQuery, hasAnyPermission]);

  const toggleExpanded = useCallback((itemName: string) => {
    setExpandedItems((prev) => {
      const next = new Set(prev);
      if (next.has(itemName)) {
        next.delete(itemName);
      } else {
        next.add(itemName);
      }
      return next;
    });
  }, []);

  const handleCollapseToggle = useCallback(() => {
    setIsCollapsed((v) => !v);
  }, []);

  const sharedProps: Omit<SidebarContentProps, 'isCollapsed' | 'onCollapseToggle'> = {
    filteredMenuItems,
    expandedItems,
    onToggle: toggleExpanded,
    onClose,
    pathname,
    searchQuery,
    onSearchChange: setSearchQuery,
    getFilteredChildren,
  };

  return (
    <>
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-40 bg-black/50 lg:hidden"
            onClick={onClose}
          />
        )}
      </AnimatePresence>

      <div className="hidden lg:flex lg:shrink-0">
        <motion.div
          animate={{ width: isCollapsed ? 72 : 320 }}
          transition={{ duration: 0.25, ease: 'easeInOut' }}
          className="flex flex-col overflow-hidden"
        >
          <SidebarContent
            {...sharedProps}
            isCollapsed={isCollapsed}
            onCollapseToggle={handleCollapseToggle}
          />
        </motion.div>
      </div>

      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ x: -320 }}
            animate={{ x: 0 }}
            exit={{ x: -320 }}
            transition={{ type: 'spring', damping: 30, stiffness: 300 }}
            className="lg:hidden fixed inset-y-0 left-0 z-50 w-80"
          >
            <div className="h-full relative">
              <button
                onClick={onClose}
                className="absolute top-5 right-4 z-10 text-white/80 hover:text-white transition-colors p-2 hover:bg-white/10 rounded-xl"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
              <SidebarContent
                {...sharedProps}
                isCollapsed={false}
              />
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}