'use client';

import { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { LayoutDashboard, ShoppingBag, CalendarDays, CalendarCheck, Bot, MessageSquare, MessageCircle, BarChart3, Settings, Users, BookOpen, UserCircle, GitBranch, LayoutGrid, Store, CreditCard, Cpu, LineChart, Headphones, Shield, Database, Phone, KeyRound, LogOut, ExternalLink, ChevronUp, Zap, Code2, LogIn, Loader2, Paintbrush, Globe, Mail, FileText, Inbox, Lock, QrCode, Megaphone, Send, Award, Gift, Ticket } from 'lucide-react';
import AppLogo from '@client/components/ui/AppLogo';
import { useAuth } from '@client/contexts/AuthContext';
import { useLiveCounts } from '@client/contexts/LiveCountsContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import LanguageSwitcher from '@client/components/ui/LanguageSwitcher';
import { useBranding } from '@client/contexts/BrandingContext';
import { usePlanFeatures } from '@client/contexts/PlanFeaturesContext';

interface NavItem {
  label: string;
  icon: React.ReactNode;
  href: string;
  badge?: number;
  badgeVariant?: 'danger' | 'warning' | 'info';
  /** When true, the item is rendered but visually locked and routes to the
   *  upgrade/settings page instead of its real destination. */
  locked?: boolean;
  /**
   * Permission section key (e.g. `ai_config`, `telephone`).
   * When set and the user is a non-owner staff member, the item is hidden
   * if they lack `read` permission for this section.
   */
  section?: string;
}

/** Where a locked sidebar entry should send the user. */
const UPGRADE_HREF = '/restaurant-settings?tab=plan';

interface NavGroup {
  label: string;
  items: NavItem[];
}

interface SidebarProps {
  isCollapsed: boolean;
  onToggle: () => void;
  isAdminMode?: boolean;
  onToggleAdminMode?: () => void;
  impersonatingName?: string;
  onExitImpersonation?: () => void;
  exitingImpersonation?: boolean;
}

/** Roles that bypass section-level permission checks in the sidebar. */
const BYPASS_ROLES = new Set(['owner', 'superadmin', 'support']);

export default function Sidebar({ isCollapsed, onToggle, isAdminMode = false, onToggleAdminMode, impersonatingName, onExitImpersonation, exitingImpersonation }: SidebarProps) {
  const pathname = usePathname();
  const { userRecord, signOut } = useAuth();
  const { t } = useLanguage();
  const { branding } = useBranding();
  const restaurantLogoUrl = userRecord?.restaurants?.logo_url || null;
  const { pendingOrders, pendingBookings, needsAgentCount } = useLiveCounts();
  const { hasFeature, planName, planStatus } = usePlanFeatures();
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  const profileMenuRef = useRef<HTMLDivElement>(null);
  const [websiteUrl, setWebsiteUrl] = useState<string>('/');
  useEffect(() => {
    if (typeof window !== 'undefined') {
      setWebsiteUrl(window.location.origin);
    }
  }, []);

  const adminNavGroups: NavGroup[] = [
    {
      label: t('admin.title', 'Admin'),
      items: [
        { label: t('nav.dashboard', 'Dashboard'), icon: <LayoutGrid size={18} />, href: '/admin/dashboard' },
        { label: t('nav.restaurants', 'Restaurants'), icon: <Store size={18} />, href: '/admin/restaurants' },
        { label: t('nav.adminOrders', 'Orders'), icon: <ShoppingBag size={18} />, href: '/admin/orders' },
        { label: t('nav.adminBookings', 'Table Bookings'), icon: <CalendarCheck size={18} />, href: '/admin/bookings' },
        { label: t('nav.billing', 'Billing'), icon: <CreditCard size={18} />, href: '/admin/billing' },
      ],
    },
    {
      label: t('admin.platform', 'Platform'),
      items: [
        { label: t('nav.platformKeys', 'Platform Keys'), icon: <Cpu size={18} />, href: '/admin/ai-settings' },
        { label: t('nav.analytics', 'Analytics'), icon: <LineChart size={18} />, href: '/admin/platform-analytics' },
        { label: t('nav.support', 'Support Tools'), icon: <Headphones size={18} />, href: '/admin/support' },
        { label: t('nav.branding', 'Branding'), icon: <Paintbrush size={18} />, href: '/admin/branding' },
        { label: t('nav.languages', 'Languages'), icon: <Globe size={18} />, href: '/admin/languages' },
        { label: t('nav.emailSettings', 'Email (SMTP)'), icon: <Mail size={18} />, href: '/admin/email-settings' },
        { label: t('nav.emailTemplates', 'Email Templates'), icon: <FileText size={18} />, href: '/admin/email-templates' },
        { label: t('nav.emailLog', 'Email Log'), icon: <Inbox size={18} />, href: '/admin/email-log' },
      ],
    },
  ];

  const restaurantNavGroups: NavGroup[] = [
    {
      label: t('nav.overview', 'Overview'),
      items: [
        { label: t('nav.agentOverview', 'Agent Overview'), icon: <LayoutDashboard size={18} />, href: '/restaurant-dashboard', section: 'dashboard' },
      ],
    },
    {
      label: t('nav.operations', 'Operations'),
      items: [
        { label: t('nav.orders', 'Orders'), icon: <ShoppingBag size={18} />, href: '/order-management', badge: pendingOrders > 0 ? pendingOrders : undefined, badgeVariant: 'danger', section: 'orders' },
        { label: t('nav.reservations', 'Reservations'), icon: <CalendarDays size={18} />, href: '/table-booking-management', badge: pendingBookings > 0 ? pendingBookings : undefined, badgeVariant: 'info', section: 'reservations' },
      ],
    },
    {
      label: t('nav.aiAgent', 'AI Agent'),
      items: [
        { label: t('nav.aiConfiguration', 'AI Configuration'), icon: <Bot size={18} />, href: '/ai-agent-config', locked: !hasFeature('chat_agent'), section: 'ai_config' },
        { label: t('nav.knowledgeBase', 'Knowledge Base'), icon: <Database size={18} />, href: '/knowledge-base', locked: !hasFeature('knowledge_base'), section: 'knowledge_base' },
        { label: t('nav.conversations', 'Conversations'), icon: <MessageSquare size={18} />, href: '/conversations', badge: needsAgentCount > 0 ? needsAgentCount : undefined, badgeVariant: 'warning', section: 'conversations' },
        { label: t('nav.chatWidget', 'Chat Widget'), icon: <Code2 size={18} />, href: '/widget-settings', section: 'chat_widget' },
      ],
    },
    {
      label: t('nav.channels', 'Channels'),
      items: [
        { label: t('nav.telephone', 'Telephone'), icon: <Phone size={18} />, href: '/telephone', locked: !hasFeature('voice_agent'), section: 'telephone' },
        { label: t('nav.whatsapp', 'WhatsApp'), icon: <MessageCircle size={18} />, href: '/whatsapp', locked: !hasFeature('whatsapp_agent'), section: 'whatsapp' },
      ],
    },
    {
      label: t('nav.restaurant', 'Restaurant'),
      items: [
        { label: t('nav.menuManagement', 'Menu Management'), icon: <BookOpen size={18} />, href: '/menu-management', section: 'menu' },
        { label: t('nav.customers', 'Customers'), icon: <UserCircle size={18} />, href: '/customers', section: 'customers' },
        { label: t('nav.loyalty', 'Loyalty Program'), icon: <Award size={18} />, href: '/loyalty', locked: !hasFeature('loyalty'), section: 'loyalty' },
        { label: t('nav.storefront', 'QR Storefront'), icon: <QrCode size={18} />, href: '/storefront', locked: !hasFeature('storefront'), section: 'storefront' },
      ],
    },
    {
      label: t('nav.growth', 'Growth'),
      items: [
        { label: t('nav.audiences', 'Audiences'), icon: <Users size={18} />, href: '/marketing/audiences', locked: !hasFeature('marketing'), section: 'marketing' },
        { label: t('nav.campaigns', 'Campaigns'), icon: <Megaphone size={18} />, href: '/marketing/campaigns', locked: !hasFeature('marketing'), section: 'marketing' },
        { label: t('nav.giftCards', 'Gift Cards'), icon: <Gift size={18} />, href: '/gift-cards', locked: !hasFeature('gift_cards'), section: 'gift_cards' },
        { label: t('nav.coupons', 'Coupons'), icon: <Ticket size={18} />, href: '/coupons', locked: !hasFeature('coupons'), section: 'coupons' },
      ],
    },
    {
      label: t('nav.manage', 'Manage'),
      items: [
        { label: t('nav.staff', 'Staff & Team'), icon: <Users size={18} />, href: '/staff', section: 'staff' },
        { label: t('nav.branches', 'Branches'), icon: <GitBranch size={18} />, href: '/branch-management', locked: !hasFeature('multi_branch'), section: 'branches' },
        { label: t('nav.analytics', 'Analytics'), icon: <BarChart3 size={18} />, href: '/analytics', locked: !hasFeature('analytics'), section: 'analytics' },
        { label: t('nav.settings', 'Settings'), icon: <Settings size={18} />, href: '/restaurant-settings', section: 'settings' },
      ],
    },
  ];

  // Determine whether this user's section access needs to be checked.
  // Owners and platform roles see everything; non-owner staff are filtered
  // by their staff.permissions JSON.
  const userRole = userRecord?.role ?? null;
  const staffPerms = userRecord?.staff_permissions ?? null;
  const isBypassRole = BYPASS_ROLES.has(userRole ?? '');

  /**
   * Returns true if the nav item should be visible to the current user.
   * - Bypass roles (owner/superadmin/support): always visible.
   * - Items without a `section` key: always visible (no permission gate).
   * - Non-bypass users with a missing/null permissions object: fail-closed —
   *   any section-gated item is hidden until the server confirms access.
   *   This prevents a transient "all items visible" flash when the staff
   *   row is absent or the permissions payload hasn't loaded yet.
   */
  function isItemVisible(item: NavItem): boolean {
    if (isBypassRole) return true;
    if (!item.section) return true;
    if (!staffPerms) return false;
    return staffPerms[item.section]?.read === true;
  }

  const navGroups = isAdminMode ? adminNavGroups : restaurantNavGroups;

  const userName = userRecord?.name || t('sidebar.defaultUserName', 'User');
  const userEmail = userRecord?.email || '';
  const isAdminRole = userRecord?.role === 'superadmin' || userRecord?.role === 'support';
  const userRoleLabel = isAdminRole ? t('auth.platformAdmin', 'Platform Admin') : t('auth.restaurantOwner', 'Restaurant Owner');
  const userInitials = userName.split(' ').map((n: string) => n[0]).join('').toUpperCase().slice(0, 2) || 'MK';

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (profileMenuRef.current && !profileMenuRef.current.contains(e.target as Node)) {
        setShowProfileMenu(false);
      }
    };
    if (showProfileMenu) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [showProfileMenu]);

  useEffect(() => { setShowProfileMenu(false); }, [pathname]);

  const restaurantName = userRecord?.restaurants?.name || t('sidebar.defaultRestaurantName', 'My Restaurant');
  const siteTitle = branding.site_title;

  const getBadgeClass = (variant?: 'danger' | 'warning' | 'info') => {
    switch (variant) {
      case 'danger': return 'bg-danger text-white';
      case 'warning': return 'bg-warning text-white';
      case 'info': return 'bg-info text-white';
      default: return 'bg-primary text-white';
    }
  };

  return (
    <aside
      className="flex flex-col h-full relative"
      style={{
        width: isCollapsed ? '64px' : '240px',
        transition: 'width 300ms ease',
        backgroundColor: isAdminMode ? 'hsl(231, 40%, 10%)' : 'hsl(var(--surface))',
        borderRight: '1px solid hsl(var(--border))',
        overflow: 'hidden',
      }}
    >
      <div className="flex items-center h-16 px-4 shrink-0" style={{ borderBottom: `1px solid ${isAdminMode ? 'rgba(255,255,255,0.1)' : 'hsl(var(--border))'}` }}>
        <div className="flex items-center gap-2.5 min-w-0">
          <AppLogo
              src={isAdminMode
                ? (branding.site_logo_url || undefined)
                : (restaurantLogoUrl || branding.site_logo_url || undefined)}
              size={32}
            />
          {!isCollapsed && (
            <div className="flex flex-col min-w-0 overflow-hidden" style={{ animation: 'fadeIn 0.2s ease-out' }}>
              <span className="font-bold text-base tracking-tight whitespace-nowrap" style={{ color: isAdminMode ? 'white' : 'hsl(var(--foreground))' }}>
                {isAdminMode ? siteTitle : restaurantName}
              </span>
              <span className="text-xs whitespace-nowrap truncate" style={{ color: isAdminMode ? 'rgba(255,255,255,0.5)' : 'hsl(var(--muted-foreground))' }}>
                {isAdminMode ? t('admin.adminPanel', 'Admin Panel') : userRoleLabel}
              </span>
            </div>
          )}
        </div>
      </div>

      {impersonatingName && onExitImpersonation && (
        <div
          className="shrink-0"
          style={{ borderBottom: `1px solid hsl(var(--border))`, backgroundColor: 'hsl(25 95% 53% / 0.12)' }}
        >
          {isCollapsed ? (
            <div className="flex justify-center py-2">
              <button
                onClick={onExitImpersonation}
                disabled={exitingImpersonation}
                title={`${t('admin.impersonating', 'Impersonating')}: ${impersonatingName} — ${t('common.exit', 'Exit')}`}
                className="w-9 h-9 flex items-center justify-center rounded-lg transition-all"
                style={{ backgroundColor: 'hsl(var(--warning))', color: 'white', opacity: exitingImpersonation ? 0.7 : 1 }}
              >
                {exitingImpersonation ? <Loader2 size={14} className="animate-spin" /> : <LogIn size={14} />}
              </button>
            </div>
          ) : (
            <div className="px-3 py-2 flex flex-col gap-1.5">
              <p className="text-xs font-semibold truncate" style={{ color: 'hsl(var(--warning))' }}>
                {t('admin.impersonating', 'Impersonating')}: {impersonatingName}
              </p>
              <button
                onClick={onExitImpersonation}
                disabled={exitingImpersonation}
                className="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-all"
                style={{ backgroundColor: 'hsl(var(--warning))', color: 'white', opacity: exitingImpersonation ? 0.7 : 1 }}
              >
                {exitingImpersonation ? <Loader2 size={11} className="animate-spin" /> : <LogIn size={11} />}
                {t('admin.exitImpersonation', 'Exit & Return to Admin')}
              </button>
            </div>
          )}
        </div>
      )}

      {!isCollapsed && onToggleAdminMode && (
        <div className="px-3 py-2" style={{ borderBottom: `1px solid ${isAdminMode ? 'rgba(255,255,255,0.1)' : 'hsl(var(--border))'}` }}>
          {isAdminMode ? (
            <Link
              href="/admin/restaurants"
              className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-semibold transition-all"
              style={{ backgroundColor: 'rgba(255,255,255,0.1)', color: 'rgba(255,255,255,0.8)' }}
            >
              <Shield size={13} />
              {t('admin.switchToRestaurant', 'Switch to Restaurant')}
            </Link>
          ) : (
            <button
              onClick={onToggleAdminMode}
              className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-semibold transition-all"
              style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
            >
              <Shield size={13} />
              {t('admin.switchToAdmin', 'Switch to Admin Panel')}
            </button>
          )}
        </div>
      )}

      <nav className="flex-1 overflow-y-auto overflow-x-hidden scrollbar-thin py-3 px-2">
        {navGroups.map((group) => {
          const visibleItems = isAdminMode ? group.items : group.items.filter(isItemVisible);
          if (visibleItems.length === 0) return null;
          return (
            <div key={group.label} className="mb-4">
              {!isCollapsed && (
                <p className="section-label px-3 mb-1.5" style={{ color: isAdminMode ? 'rgba(255,255,255,0.35)' : undefined }}>{group.label}</p>
              )}
              {isCollapsed && <div className="mb-1 mt-1 mx-3 border-t" style={{ borderColor: isAdminMode ? 'rgba(255,255,255,0.1)' : 'hsl(var(--border))' }} />}
              <ul className="space-y-0.5">
                {visibleItems.map((item) => {
                  const targetHref = item.href;
                  const isActive = !item.locked && (pathname === item.href || (item.href !== '/ai-agent-config' && pathname?.startsWith(item.href + '/')));
                  const activeStyle = isAdminMode
                    ? { backgroundColor: 'rgba(255,255,255,0.12)', color: 'white' }
                    : { backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' };
                  const lockedStyle = { color: isAdminMode ? 'rgba(255,255,255,0.35)' : 'hsl(var(--foreground-secondary))', opacity: 0.65 };
                  const inactiveStyle = item.locked
                    ? lockedStyle
                    : { color: isAdminMode ? 'rgba(255,255,255,0.6)' : 'hsl(var(--foreground-secondary))' };
                  const hoverStyle = isAdminMode ? 'hover:bg-white/10' : '';

                  return (
                    <li key={item.href}>
                      <Link
                        href={targetHref}
                        className={`sidebar-nav-item flex flex-row items-center gap-3 ${isCollapsed ? 'justify-center !px-0 mx-auto w-10 h-10' : ''} ${hoverStyle}`}
                        style={isActive ? activeStyle : inactiveStyle}
                        title={isCollapsed
                          ? (item.locked ? `${item.label} — ${t('nav.upgradeRequired', 'upgrade required')}` : item.label)
                          : (item.locked ? t('nav.upgradeRequired', 'upgrade required') : undefined)}
                      >
                        <span className="shrink-0">{item.icon}</span>
                        {!isCollapsed && <span className="truncate flex-1">{item.label}</span>}
                        {!isCollapsed && item.locked && (
                          <Lock size={12} className="shrink-0" style={{ color: isAdminMode ? 'rgba(255,255,255,0.4)' : 'hsl(var(--muted-foreground))' }} />
                        )}
                        {!isCollapsed && !item.locked && item.badge !== undefined && item.badge > 0 && (
                          <span className={`text-xs px-1.5 py-0.5 rounded-full font-semibold ${getBadgeClass(item.badgeVariant)}`}>{item.badge}</span>
                        )}
                        {isCollapsed && !item.locked && item.badge !== undefined && item.badge > 0 && (
                          <span className={`absolute top-0 right-0 text-xs w-4 h-4 flex items-center justify-center rounded-full font-bold ${getBadgeClass(item.badgeVariant)}`} style={{ fontSize: '10px' }}>
                            {item.badge}
                          </span>
                        )}
                        {isCollapsed && item.locked && (
                          <span className="absolute -top-0.5 -right-0.5 w-4 h-4 flex items-center justify-center rounded-full" style={{ backgroundColor: isAdminMode ? 'rgba(255,255,255,0.15)' : 'hsl(var(--surface))', border: `1px solid ${isAdminMode ? 'rgba(255,255,255,0.2)' : 'hsl(var(--border))'}` }}>
                            <Lock size={9} style={{ color: isAdminMode ? 'rgba(255,255,255,0.6)' : 'hsl(var(--muted-foreground))' }} />
                          </span>
                        )}
                      </Link>
                    </li>
                  );
                })}
              </ul>
            </div>
          );
        })}
      </nav>

      {!isCollapsed && (
        <div className="px-3 py-3 shrink-0 relative" ref={profileMenuRef} style={{ borderTop: `1px solid ${isAdminMode ? 'rgba(255,255,255,0.1)' : 'hsl(var(--border))'}` }}>
          <button
            onClick={() => setShowProfileMenu(!showProfileMenu)}
            className="w-full flex items-center gap-2.5 px-2 py-2 rounded-lg transition-colors hover:bg-black/5"
            style={isAdminMode ? { color: 'white' } : {}}
          >
            <div className="w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold shrink-0" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
              {userInitials}
            </div>
            <div className="flex-1 min-w-0 text-left">
              <p className="text-xs font-semibold truncate" style={{ color: isAdminMode ? 'white' : 'hsl(var(--foreground))' }}>{userName}</p>
              <p className="text-xs truncate" style={{ color: isAdminMode ? 'rgba(255,255,255,0.4)' : 'hsl(var(--muted-foreground))' }}>{userRoleLabel}</p>
            </div>
            <ChevronUp size={14} className="shrink-0 transition-transform" style={{ color: isAdminMode ? 'rgba(255,255,255,0.4)' : 'hsl(var(--muted-foreground))', transform: showProfileMenu ? 'rotate(0deg)' : 'rotate(180deg)' }} />
          </button>

          {showProfileMenu && (
            <div
              className="absolute bottom-full left-3 right-3 mb-2 rounded-xl shadow-xl z-50 fade-in"
              style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))', boxShadow: 'var(--shadow-xl)' }}
            >
              <div className="px-4 py-3" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                <p className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{userName}</p>
                {userEmail && <p className="text-xs mt-0.5 truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>{userEmail}</p>}
              </div>

              {!isAdminRole && (
                <div className="px-3 py-2" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                  <Link
                    href="/billing"
                    onClick={() => setShowProfileMenu(false)}
                    className="flex items-center gap-2.5 px-2 py-2 rounded-lg transition-colors hover:opacity-90"
                    style={{ backgroundColor: 'hsl(var(--primary-light))' }}
                  >
                    <div className="w-7 h-7 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--primary))', color: 'white' }}>
                      <Zap size={13} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-bold truncate" style={{ color: 'hsl(var(--primary))' }}>
                        {planName ?? t('billing.plan', 'Plan')}
                      </p>
                      <p className="text-xs capitalize" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {planStatus === 'trial'
                          ? t('billing.status.trial', 'Trial')
                          : planStatus === 'active'
                            ? t('common.active', 'Active')
                            : planStatus === 'suspended'
                              ? t('billing.status.suspended', 'Suspended')
                              : planStatus === 'past_due'
                                ? t('billing.status.pastDue', 'Past due')
                                : planStatus === 'cancelled'
                                  ? t('billing.status.cancelled', 'Cancelled')
                                  : planStatus
                                    ? planStatus
                                    : t('billing.status.noplan', 'No plan')}
                      </p>
                    </div>
                  </Link>
                </div>
              )}

              <div className="py-1">
                <Link
                  href={isAdminMode ? '/admin/branding' : '/restaurant-settings'}
                  className="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-black/5 text-sm"
                  style={{ color: 'hsl(var(--foreground))' }}
                  onClick={() => setShowProfileMenu(false)}
                >
                  <Settings size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />
                  {t('nav.settings', 'Settings')}
                </Link>
                <Link href={isAdminMode ? '/admin/change-password' : '/change-password'} className="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-black/5 text-sm" style={{ color: 'hsl(var(--foreground))' }} onClick={() => setShowProfileMenu(false)}>
                  <KeyRound size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />
                  {t('settings.changePassword', 'Change Password')}
                </Link>
                <a href={websiteUrl} target="_blank" rel="noopener noreferrer" className="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-black/5 text-sm" style={{ color: 'hsl(var(--foreground))' }}>
                  <ExternalLink size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />
                  {t('common.website', 'Website')}
                </a>
                <LanguageSwitcher variant="sidebar" />
              </div>

              <div className="py-1" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                <button onClick={() => { setShowProfileMenu(false); signOut(); }} className="w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-black/5 text-sm" style={{ color: 'hsl(var(--danger))' }}>
                  <LogOut size={15} />
                  {t('auth.logOut', 'Log Out')}
                </button>
              </div>
            </div>
          )}
        </div>
      )}
    </aside>
  );
}
