import React, { useState, useEffect } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { useLanguage } from '../contexts/LanguageContext';
import { useSidebarLayout } from '../contexts/SidebarLayoutContext';
import { useTranslation } from 'react-i18next';
import { 
  LayoutDashboard,
  Package,
  Box,
  Menu,
  X,
  ClipboardList,
  Calendar,
  CalendarCheck,
  Map,
  Users,
  ShoppingCart,
  FileText,
  HelpCircle,
  UserCircle,
  Trash2,
  FolderOpen,
  Building2

} from 'lucide-react';

import { FaChevronDown, FaChevronUp, FaClipboardCheck } from 'react-icons/fa';

interface SidebarLink {
  id: string;
  title: string;
  icon: React.ReactNode;
  path: string;
  visible: boolean;
}

interface SidebarProps {
  userEmail?: string;
}

// ✅ Role definitions
const ADMIN_ROLES = [
  'System Manager',
  'Contractor Supervisor',
  'Contractor Manager',
  'Work Control',
  'Contractor Engineer'
];

const TECHNICIAN_ROLE = 'Technician';
const END_USER_ROLE = 'End User';

/** True when viewport is lg (1024px) or wider — desktop sidebar in-flow */
function useLgUp(): boolean {
  const [lg, setLg] = useState(() =>
    typeof window !== 'undefined' ? window.matchMedia('(min-width: 1024px)').matches : false
  );
  useEffect(() => {
    const mq = window.matchMedia('(min-width: 1024px)');
    const onChange = () => setLg(mq.matches);
    mq.addEventListener('change', onChange);
    return () => mq.removeEventListener('change', onChange);
  }, []);
  return lg;
}

const Sidebar: React.FC<SidebarProps> = ({ userEmail }) => {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isProjectsExpanded, setIsProjectsExpanded] = useState(true);
  const location = useLocation();
  const navigate = useNavigate();
  const isLgUp = useLgUp();

  const { isRTL } = useLanguage();
  const { t } = useTranslation();
  const { mobileSidebarOpen, closeMobileSidebar } = useSidebarLayout();

  const afterNav = () => {
    if (!isLgUp) closeMobileSidebar();
  };

  const edgeBorderClass = isRTL
    ? 'border-l border-gray-200 dark:border-gray-700'
    : 'border-r border-gray-200 dark:border-gray-700';

  const activeEdgeBorderClass = isRTL ? 'border-r-4 border-white' : 'border-l-4 border-white';
  
  // ✅ Role-based state
  const [userRoles, setUserRoles] = useState<{
    isAdmin: boolean;
    isTechnician: boolean;
    isEndUser: boolean;
    isLoading: boolean;
  }>({
    isAdmin: false,
    isTechnician: false,
    isEndUser: false,
    isLoading: true
  });

  const [userFullName, setUserFullName] = useState<string>('');

  // Get base URL for assets (handles both dev and production)
  // BASE_URL in Vite already includes trailing slash in production, but not in dev
  const baseUrl = import.meta.env.BASE_URL || '/';
  // Add cache-busting query parameter to force browser to reload updated images
  // Version is automatically updated by build script based on file modification time
  const imageVersion = import.meta.env.DEV 
    ? `?v=${Date.now()}` 
    : `?v=1774269853`; // Auto-updated by build script
  const logoVersion = import.meta.env.DEV 
    ? `?v=${Date.now()}` 
    : `?v=1774269853`; // Auto-updated by build script
  const backgroundImageUrl = baseUrl.endsWith('/') 
    ? `${baseUrl}sidebar-background.jpg${imageVersion}`
    : `${baseUrl}/sidebar-background.jpg${imageVersion}`;

  // ✅ Fetch user roles on mount
  useEffect(() => {
    const fetchUserRoles = async () => {
      try {
        // Check for admin roles
        const adminResponse = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            roles: ADMIN_ROLES.join(',')
          })
        });
        const adminData = await adminResponse.json();
        const isAdmin = adminData.message?.has_role || false;

        // Check for technician role
        const techResponse = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            roles: TECHNICIAN_ROLE
          })
        });
        const techData = await techResponse.json();
        const isTechnician = techData.message?.has_role || false;

        // Check for end user role
        const endUserResponse = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            roles: END_USER_ROLE
          })
        });
        const endUserData = await endUserResponse.json();
        const isEndUser = endUserData.message?.has_role || false;

        setUserRoles({
          isAdmin,
          isTechnician,
          isEndUser,
          isLoading: false
        });

        console.log('User roles:', { isAdmin, isTechnician, isEndUser });
      } catch (error) {
        console.error('Error fetching user roles:', error);
        // Default to showing minimal items on error
        setUserRoles({
          isAdmin: false,
          isTechnician: false,
          isEndUser: true, // Default to end user (minimal access)
          isLoading: false
        });
      }
    };

    fetchUserRoles();
  }, []);

  // ✅ Fetch user full name on mount
  useEffect(() => {
    const fetchUserFullName = async () => {
      try {
        // First get the logged-in user
        const userResponse = await fetch('/api/method/frappe.auth.get_logged_user', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
          credentials: 'include'
        });
        const userData = await userResponse.json();
        const userEmail = userData.message;

        if (userEmail) {
          // Then fetch the user's full name
          const fullNameResponse = await fetch(`/api/resource/User/${encodeURIComponent(userEmail)}?fields=["full_name"]`, {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
            credentials: 'include'
          });
          const fullNameData = await fullNameResponse.json();
          
          if (fullNameData.data?.full_name) {
            setUserFullName(fullNameData.data.full_name);
          } else {
            // Fallback to email if full name not found
            setUserFullName(userEmail);
          }
        }
      } catch (error) {
        console.error('Error fetching user full name:', error);
        // Fallback to email prop if API fails
        if (userEmail) {
          setUserFullName(userEmail);
        }
      }
    };

    fetchUserFullName();
  }, [userEmail]);

  // ✅ Visibility logic based on roles
  // Admin: sees everything
  // Technician: Work Order, Inspection, Procurement, Support, Active Map
  // End User: Work Order, Support
  // If user has multiple roles, they see the union of all permissions

  const getVisibility = (linkId: string): boolean => {
    const { isAdmin, isTechnician, isEndUser, isLoading } = userRoles;

    // While loading, show nothing or minimal
    if (isLoading) {
      return false;
    }

    // Admin sees everything
    if (isAdmin) {
      return true;
    }

    // Define what each role can see
    const endUserLinks = ['work-orders', 'support', 'assets', 'inventory', 'projects'];
    const technicianLinks = ['work-orders', 'inspections', 'procurement', 'support', 'active-map', 'assets', 'inventory', 'projects'];

    // Check visibility based on roles (union of permissions)
    let canSee = false;

    if (isEndUser && endUserLinks.includes(linkId)) {
      canSee = true;
    }

    if (isTechnician && technicianLinks.includes(linkId)) {
      canSee = true;
    }

    // If user has no recognized role, show minimal access (end user)
    if (!isAdmin && !isTechnician && !isEndUser) {
      canSee = endUserLinks.includes(linkId);
    }

    return canSee;
  };

  // Role-based visibility logic (keeping old code commented)
  // const isMaintenanceManagerKASH = userEmail === 'maintenancemanager-kash@gmail.com';
  // const isMaintenanceManagerTH = userEmail === 'maintenancemanager-th@gmail.com';
  // const isMaintenanceManagerDAJH = userEmail === 'maintenancemanager-dajh@gmail.com';
  // const isFinanceManager = userEmail === 'financemanager@gmail.com';
  // const isEndUser = userEmail && (
  //   userEmail.startsWith('enduser1-kash') || 
  //   userEmail.startsWith('enduser1-dajh') || 
  //   userEmail.startsWith('enduser1-th')
  // );
  // const isTechnician = userEmail && (
  //   userEmail.startsWith('technician1-kash') || 
  //   userEmail.startsWith('technician1-dajh') || 
  //   userEmail.startsWith('technician1-th')
  // );

  // const showAsset = !isFinanceManager && !isEndUser;
  // const showInventory = !isFinanceManager && !isEndUser;
  // const showPreventiveMaintenance = !isFinanceManager && !isEndUser;
  // const showGeneralWO = !isFinanceManager && !isEndUser;
  // const showAMTeam = !isFinanceManager && !isEndUser;
  // const showProjectDashboard = !isMaintenanceManagerKASH && !isMaintenanceManagerTH && !isMaintenanceManagerDAJH && !isFinanceManager && !isEndUser && !isTechnician;
  // const showSiteDashboards = !isFinanceManager && !isEndUser;
  // const showSupplierDashboard = !isFinanceManager && !isEndUser;
  // const showSLA = !isFinanceManager && !isEndUser && !isTechnician;
  // const showSiteInfo = !isFinanceManager && !isEndUser;

  const links: SidebarLink[] = [
    {
      id: 'dashboard',
      title: t('common.dashboard'),
      icon: <LayoutDashboard size={20} />,
      path: '/dashboard',
      visible: userRoles.isAdmin // Only admin sees dashboard
    },
    {
      id: 'assets',
      title: t('common.assets'),
      icon: <Package size={20} />,
      path: '/assets',
      visible: getVisibility('assets')
    },
    {
      id: 'inventory',
      title: t('sidebar.inventory'),
      icon: <Box size={20} />,
      path: '/inventory',
      visible: getVisibility('inventory')
    },
    {
      id: 'projects',
      title: t('sidebar.projects'),
      icon: <FolderOpen size={20} />,
      path: '/projects',
      visible: getVisibility('projects')
    },
    {
      id: 'work-orders',
      title: t('common.workOrders'),
      icon: <ClipboardList size={20} />,
      path: '/work-orders',
      visible: getVisibility('work-orders')
    },
    {
      id: 'inspections',
      title: t('sidebar.inspection'),
      icon: <FaClipboardCheck size={20} />,
      path: '/inspections',
      visible: getVisibility('inspections')
    },
    {
      id: 'sfda-entries',
      title: t('sidebar.sfdaEntries'),
      icon: <FileText size={20} />,
      path: '/sfda-entries',
      visible: userRoles.isAdmin
    },
    // {
    //   id: 'maintenance',
    //   title: t('common.maintenance'),
    //   icon: <Wrench size={20} />,
    //   path: '/maintenance',
    //   visible: showPreventiveMaintenance
    // },
    // {
    //   id: 'ppm',
    //   title: t('common.ppm'),
    //   icon: <Calendar size={20} />,
    //   path: '/ppm',
    //   visible: showPreventiveMaintenance
    // },
    {
      id: 'ppm-planner',
      title: t('sidebar.ppmPlanner'),
      icon: <CalendarCheck size={20} />,
      path: '/ppm-planner',
      visible: userRoles.isAdmin
    },
    {
      id: 'maintenance-calendar',
      title: t('sidebar.maintenanceCalendar'),
      icon: <Calendar size={20} />,
      path: '/maintenance-calendar',
      visible: userRoles.isAdmin
    },
    {
      id: 'active-map',
      title: t('sidebar.activeMap'),
      icon: <Map size={20} />,
      path: '/active-map',
      visible: getVisibility('active-map')
    },
    {
      id: 'maintenance-teams',
      title: t('sidebar.maintenanceTeam'),
      icon: <Users size={20} />,
      path: '/maintenance-teams',
      visible: userRoles.isAdmin // Only admin
    },
    {
      id: 'facility-management',
      title: 'Facility Management',
      icon: <Building2 size={20} />,
      path: '/facility-management-external',
      visible: userRoles.isAdmin
    },
    {
      id: 'procurement',
      title: t('sidebar.procurement'),
      icon: <ShoppingCart size={20} />,
      path: '/procurement',
      visible: getVisibility('procurement')
    },
    {
      id: 'sla',
      title: t('sidebar.sla'),
      icon: <FileText size={20} />,
      path: '/sla',
      visible: userRoles.isAdmin // Only admin
    },
    {
      id: 'support',
      title: t('sidebar.support'),
      icon: <HelpCircle size={20} />,
      path: '/support',
      visible: getVisibility('support')
    },

    // {
    //   id: 'delete-requests',
    //   title: t('sidebar.deleteRequests'),
    //   icon: <Trash2 size={20} />,
    //   path: '/delete-requests',
    //   visible: userRoles.isAdmin // Only admin sees delete requests
    // },
    
    // {
    //   id: 'vendors',
    //   title: 'Vendors',
    //   icon: <Truck size={20} />,
    //   path: '/vendors',
    //   visible: showSupplierDashboard
    // },
    // {
    //   id: 'dashboard-view',
    //   title: 'Dashboard',
    //   icon: <BarChart3 size={20} />,
    //   path: '/dashboard-view',
    //   visible: showProjectDashboard
    // },
    // {
    //   id: 'sites',
    //   title: 'Sites',
    //   icon: <Building2 size={20} />,
    //   path: '/sites',
    //   visible: showSiteDashboards
    // },
    // {
    //   id: 'active-map',
    //   title: 'Active Map',
    //   icon: <MapPin size={20} />,
    //   path: '/active-map',
    //   visible: showSiteInfo
    // },
    // {
    //   id: 'users',
    //   title: 'Users',
    //   icon: <Users size={20} />,
    //   path: '/users',
    //   visible: showAMTeam
    // },
    // {
    //   id: 'account',
    //   title: 'Account',
    //   icon: <FileText size={20} />,
    //   path: '/account',
    //   visible: showSLA
    // }
  ];

  const projectsLink = links.find(l => l.id === 'projects');
  const visibleLinks = links.filter(link => link.visible && link.id !== 'projects');

  const isActive = (path: string) => {
    return location.pathname === path;
  };

  const isProjectsActive = location.pathname === '/projects' || location.pathname.startsWith('/projects/');

  useEffect(() => {
    closeMobileSidebar();
  }, [location.pathname, closeMobileSidebar]);

  // ✅ Handle User Profile click
  const handleUserProfileClick = () => {
    navigate('/user-profile');
  };

  const mobileDrawerShell = isRTL
    ? `
    fixed inset-y-0 right-0 z-50 h-screen
    transition-transform duration-300 ease-in-out
    ${mobileSidebarOpen ? 'translate-x-0' : 'translate-x-full'}
    lg:relative lg:inset-auto lg:right-auto lg:z-auto lg:translate-x-0
  `
    : `
    fixed inset-y-0 left-0 z-50 h-screen
    transition-transform duration-300 ease-in-out
    ${mobileSidebarOpen ? 'translate-x-0' : '-translate-x-full'}
    lg:relative lg:inset-auto lg:left-auto lg:z-auto lg:translate-x-0
  `;

  // ✅ Show loading state while fetching roles
  if (userRoles.isLoading) {
    return (
      <>
        {mobileSidebarOpen && (
          <button
            type="button"
            className="asm-app-sidebar-backdrop fixed inset-0 z-40 bg-black/50 lg:hidden"
            onClick={closeMobileSidebar}
            aria-label={t('common.close', { defaultValue: 'Close menu' })}
          />
        )}
        <div
          className={`
            asm-app-sidebar
            flex
            h-screen
            w-64
            flex-col
            items-center
            justify-center
            shadow-xl
            ${edgeBorderClass}
            ${mobileDrawerShell}
          `}
          style={{
            backgroundImage: `url(${backgroundImageUrl})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            backgroundRepeat: 'no-repeat',
          }}
        >
          <div className="absolute inset-0 z-0 bg-black/60 dark:bg-black/70" />
          <div className="relative z-10 text-white">
            <div className="mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-white" />
            <p className="mt-2 text-sm">{t('common.loading')}</p>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      {mobileSidebarOpen && (
        <button
          type="button"
          className="asm-app-sidebar-backdrop fixed inset-0 z-40 bg-black/50 lg:hidden"
          onClick={closeMobileSidebar}
          aria-label={t('common.close', { defaultValue: 'Close menu' })}
        />
      )}
      <div
        className={`
        asm-app-sidebar
        h-screen
        transition-all
        duration-300
        ease-in-out
        flex
        flex-col
        shadow-xl
        ${edgeBorderClass}
        ${isCollapsed ? 'w-16' : 'w-64'}
        ${mobileDrawerShell}
      `}
      style={{
        backgroundImage: `url(${backgroundImageUrl})`, 
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }}
    >
      {/* Black Overlay */}
      <div className="absolute inset-0 bg-black/60 dark:bg-black/70 z-0"></div>
      
      {/* Content Container - Above Overlay */}
      <div className="relative z-10 flex flex-col h-full bg-white/0 dark:bg-white/0">
      {/* Sidebar Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200/30 dark:border-gray-700/30">
        {!isCollapsed && (
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 flex items-center justify-center bg-white/20 dark:bg-white/20 rounded-lg p-1 backdrop-blur-sm">
              {/* Seera Arabia Logo */}
              <img 
                src={`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}seera-logo.png${logoVersion}`}
                alt="SEERA-ASM" 
                className="w-full h-full object-contain"
                onError={(e) => {
                  // Fallback to SVG if image not found
                  e.currentTarget.style.display = 'none';
                  e.currentTarget.nextElementSibling?.classList.remove('hidden');
                }}
              />
              <svg className="w-6 h-6 hidden" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 2L2 7L12 12L22 7L12 2Z" fill="#6366F1" fillOpacity="0.9"/>
                <path d="M2 17L12 22L22 17V12L12 17L2 12V17Z" fill="#8B5CF6" fillOpacity="0.7"/>
                <path d="M12 12V17" stroke="#A855F7" strokeWidth="2" strokeLinecap="round"/>
              </svg>
            </div>
            <h1 className="text-white dark:text-white text-lg font-semibold drop-shadow-lg">{t('sidebar.title')}</h1>
          </div>
        )}
        {isCollapsed && (
          <div className="w-8 h-8 flex items-center justify-center bg-white dark:bg-gray-700 rounded-lg p-1">
            <img 
              src={`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}seera-logo.png?v=1765198405${logoVersion}`}
              alt="SEERA-ASM" 
              className="w-full h-full object-contain"
              onError={(e) => {
                e.currentTarget.style.display = 'none';
                e.currentTarget.nextElementSibling?.classList.remove('hidden');
              }}
            />
            <svg className="w-5 h-5 hidden" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 2L2 7L12 12L22 7L12 2Z" fill="#6366F1" fillOpacity="0.9"/>
              <path d="M2 17L12 22L22 17V12L12 17L2 12V17Z" fill="#8B5CF6" fillOpacity="0.7"/>
              <path d="M12 12V17" stroke="#A855F7" strokeWidth="2" strokeLinecap="round"/>
            </svg>
          </div>
        )}
        <button
          type="button"
          onClick={() => {
            if (isLgUp) setIsCollapsed(!isCollapsed);
            else closeMobileSidebar();
          }}
          className="text-white dark:text-white hover:bg-white/20 dark:hover:bg-white/20 p-2 rounded-lg transition-colors"
          aria-label={
            isLgUp
              ? isCollapsed
                ? t('common.expandSidebar', { defaultValue: 'Expand sidebar' })
                : t('common.collapseSidebar', { defaultValue: 'Collapse sidebar' })
              : t('common.closeMenu', { defaultValue: 'Close menu' })
          }
        >
          {isLgUp ? (isCollapsed ? <Menu size={20} /> : <X size={20} />) : <X size={20} />}
        </button>
      </div>

      {/* Navigation Links */}
      <nav className="flex-1 overflow-y-auto py-4">
        {visibleLinks.map((link) => (
          <React.Fragment key={link.id}>
            {link.id === 'facility-management' ? (
              
              <a
              href="/space-management/?from=asm"
              target="_self"
              onClick={afterNav}
              className={`
                flex 
                items-center 
                px-4 
                py-3 
                text-white dark:text-white 
                hover:bg-white/20 dark:hover:bg-white/20 
                hover:text-white dark:hover:text-white 
                transition-all 
                duration-200
                ${isCollapsed ? 'justify-center' : ''}
              `}
              title={isCollapsed ? link.title : ''}
            >
              <span>{link.icon}</span>
              {!isCollapsed && (
                <span className={`${isRTL ? 'mr-4' : 'ml-4'} font-medium`}>{link.title}</span>
              )}
            </a>
          ) : (
            <Link
              to={link.path}
              onClick={afterNav}
              className={`
                flex 
                items-center 
                px-4 
                py-3 
                text-white dark:text-white 
                hover:bg-white/20 dark:hover:bg-white/20 
                hover:text-white dark:hover:text-white 
                transition-all 
                duration-200
                ${isActive(link.path) ? `bg-white/30 dark:bg-white/30 text-white dark:text-white ${activeEdgeBorderClass}` : ''}
                ${isCollapsed ? 'justify-center' : ''}
              `}
              title={isCollapsed ? link.title : ''}
            >
              <span>{link.icon}</span>
              {!isCollapsed && (
                <span className={`${isRTL ? 'mr-4' : 'ml-4'} font-medium`}>{link.title}</span>
              )}
            </Link>
          )}

            {/* Insert Project Management right after Inventory */}
            {link.id === 'inventory' && projectsLink?.visible && (
              <div>
            <button
              type="button"
              onClick={() => {
                if (isCollapsed) {
                  navigate('/projects');
                  afterNav();
                  return;
                }
                setIsProjectsExpanded((v) => !v);
              }}
              className={`
                w-full
                flex
                items-center
                px-4
                py-3
                text-white dark:text-white
                hover:bg-white/20 dark:hover:bg-white/20
                transition-all duration-200
                ${isProjectsActive ? `bg-white/30 dark:bg-white/30 text-white dark:text-white ${activeEdgeBorderClass}` : ''}
                ${isCollapsed ? 'justify-center' : ''}
              `}
              title={isCollapsed ? projectsLink.title : ''}
            >
              <span>{projectsLink.icon}</span>
              {!isCollapsed && (
                <>
                  <span className={`${isRTL ? 'mr-4' : 'ml-4'} font-medium flex-1 text-left`}>{projectsLink.title}</span>
                  <span className="opacity-80">
                    {isProjectsExpanded ? <FaChevronUp size={12} /> : <FaChevronDown size={12} />}
                  </span>
                </>
              )}
            </button>

            {!isCollapsed && isProjectsExpanded && (
              <div className={`${isRTL ? 'pr-6' : 'pl-6'} pb-2`}>
                <Link
                  to="/projects"
                  onClick={afterNav}
                  className={`
                    flex items-center gap-2 px-4 py-2 text-white/90 hover:text-white
                    hover:bg-white/15 rounded-lg transition-colors
                    ${location.pathname === '/projects' ? 'bg-white/20' : ''}
                  `}
                >
                  <span className="w-1.5 h-1.5 rounded-full bg-white/70" />
                  <span className="text-sm font-medium">Projects</span>
                </Link>
                <Link
                  to="/projects/reports"
                  onClick={afterNav}
                  className={`
                    flex items-center gap-2 px-4 py-2 text-white/90 hover:text-white
                    hover:bg-white/15 rounded-lg transition-colors
                    ${location.pathname.startsWith('/projects/reports') ? 'bg-white/20' : ''}
                  `}
                >
                  <span className="w-1.5 h-1.5 rounded-full bg-white/70" />
                  <span className="text-sm font-medium">Dashboard</span>
                </Link>
              </div>
            )}
          </div>
            )}
            </React.Fragment>
        ))}
      </nav>

      {/* User Info & Version (Bottom) */}
      {/* <div className={`${isCollapsed ? 'p-2' : 'p-4'} border-t border-white/10 backdrop-blur-sm bg-white/5 space-y-3 relative z-10`}> */}
      <div className={`${isCollapsed ? 'p-1' : 'p-2'} border-t border-white/10 backdrop-blur-sm bg-white/5 relative z-10`}>
        {/* {!isCollapsed && (userFullName || userEmail) && (
        <div>
          <div className="text-white/80 dark:text-white/80 text-xs truncate">
            {t('sidebar.loggedInAs')}
          </div>
          <div className="text-white dark:text-white text-sm font-medium truncate">
            {userFullName || userEmail}
          </div>
                        
        
            <button
              onClick={handleUserProfileClick}
              className={`
                mt-3 w-full flex items-center justify-center gap-2 
                px-3 py-2 
                bg-white/20 hover:bg-white/30 
                text-white 
                rounded-lg 
                transition-all duration-200
                text-sm font-medium
                ${isActive('/user-profile') ? 'bg-white/40 border border-white/50' : ''}
              `}
            >
              <UserCircle size={18} />
              <span>{t('sidebar.userProfile')}</span>
            </button>

          </div>
        )} */}

                {/* Collapsed state - just show icon button */}
        {/* {isCollapsed && (
          <button
            onClick={handleUserProfileClick}
            className={`
              w-full flex items-center justify-center
              p-2
              bg-white/20 hover:bg-white/30 
              text-white 
              rounded-lg 
              transition-all duration-200
              ${isActive('/user-profile') ? 'bg-white/40 border border-white/50' : ''}
            `}
            title={t('sidebar.userProfile')}
          >
            <UserCircle size={20} />
          </button>
        )} */}
        

        
        {!isCollapsed && (
          <div className="text-[10px] text-white/50 dark:text-white/50 text-center leading-none">
            {t('sidebar.version')}
          </div>
        )}
      </div>
      </div>
    </div>
    </>
  );
};

export default Sidebar;