'use client';

import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import {
  LayoutDashboard,
  Users,
  MessageSquare,
  Target,
  Zap,
  UserPlus,
  Store,
  Wrench,
  BarChart3,
  Settings,
  Shield,
  ChevronLeft,
  ChevronRight,
  LogOut,
  Building2,
  Bell,
  Search,
  Menu,
  X,
  Loader2,
  Sparkles,
  ListChecks,
} from 'lucide-react';
import { useState, useEffect, useRef } from 'react';
import { AuthProvider, useAuth } from '@/lib/hooks/useAuth';
import { RealtimeProvider, useRealtimeContext } from '@/components/realtime/RealtimeProvider';
import { cn } from '@/lib/utils';

const setupNavItems = [
  { href: '/setup', label: 'Setup', icon: ListChecks },
];

const navItems = [
  { href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
  { href: '/control-center', label: 'Control Center', icon: Sparkles },
  { href: '/contacts', label: 'Contacts', icon: Users },
  { href: '/conversations', label: 'Conversations', icon: MessageSquare },
  { href: '/opportunities', label: 'Opportunities', icon: Target },
  { href: '/automations', label: 'Automations', icon: Zap },
  { href: '/leads', label: 'Get Leads', icon: UserPlus },
  { href: '/marketplace', label: 'Marketplace', icon: Store },
  { href: '/tools', label: 'Tools', icon: Wrench },
  { href: '/reporting', label: 'Reporting', icon: BarChart3 },
];

const bottomNavItems = [
  { href: '/settings', label: 'Settings', icon: Settings },
  { href: '/admin', label: 'Admin', icon: Shield, adminOnly: true },
];

// Tooltip component for collapsed sidebar
function Tooltip({ children, content, show }: { children: React.ReactNode; content: string; show: boolean }) {
  if (!show) return <>{children}</>;

  return (
    <div className="relative group">
      {children}
      <div className="absolute left-full ml-2 top-1/2 -translate-y-1/2 px-2 py-1 bg-foreground text-background text-xs rounded-md whitespace-nowrap opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-50 shadow-lg">
        {content}
        <div className="absolute right-full top-1/2 -translate-y-1/2 border-4 border-transparent border-r-foreground" />
      </div>
    </div>
  );
}

// Search Modal Component
function SearchModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
  const [searchQuery, setSearchQuery] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isOpen]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        if (!isOpen) return;
        onClose();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const searchCategories = [
    { label: 'Contacts', icon: Users, shortcut: 'C' },
    { label: 'Conversations', icon: MessageSquare, shortcut: 'V' },
    { label: 'Opportunities', icon: Target, shortcut: 'O' },
    { label: 'Settings', icon: Settings, shortcut: 'S' },
  ];

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center pt-[20vh]">
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm"
        onClick={onClose}
        aria-hidden="true"
      />
      <div
        className="relative w-full max-w-lg mx-4 bg-background rounded-2xl shadow-[8px_8px_16px_#b8bcc5,-8px_-8px_16px_#ffffff] overflow-hidden"
        role="dialog"
        aria-modal="true"
        aria-label="Search"
      >
        <div className="flex items-center gap-3 p-4 border-b border-border/50">
          <Search className="w-5 h-5 text-muted-foreground" />
          <input
            ref={inputRef}
            type="text"
            placeholder="Search contacts, conversations, opportunities..."
            className="flex-1 bg-transparent outline-none text-foreground placeholder:text-muted-foreground"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            aria-label="Search input"
          />
          <kbd className="hidden sm:inline-flex items-center gap-1 px-2 py-1 text-xs text-muted-foreground bg-muted rounded">
            <span>Esc</span>
          </kbd>
        </div>
        <div className="p-2">
          <div className="px-3 py-2 text-xs font-medium text-muted-foreground uppercase tracking-wider">
            Quick Search
          </div>
          <nav role="menu">
            {searchCategories.map(({ label, icon: Icon, shortcut }) => (
              <button
                key={label}
                className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-left text-muted-foreground hover:text-foreground hover:bg-white/50 transition-colors focus:outline-none focus:ring-2 focus:ring-primary/50"
                role="menuitem"
                onClick={() => {
                  onClose();
                }}
              >
                <Icon className="w-4 h-4" />
                <span className="flex-1">{label}</span>
                <kbd className="text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded">{shortcut}</kbd>
              </button>
            ))}
          </nav>
        </div>
        <div className="px-4 py-3 border-t border-border/50 text-xs text-muted-foreground">
          <span className="inline-flex items-center gap-2">
            <kbd className="px-1.5 py-0.5 bg-muted rounded">Tab</kbd> to navigate
            <kbd className="px-1.5 py-0.5 bg-muted rounded">Enter</kbd> to select
          </span>
        </div>
      </div>
    </div>
  );
}

// Helper function to get user initials
function getUserInitials(user: { firstName?: string; lastName?: string; email?: string } | null): string {
  if (!user) return 'U';

  const first = user.firstName?.[0]?.toUpperCase() || '';
  const last = user.lastName?.[0]?.toUpperCase() || '';

  if (first && last) return `${first}${last}`;
  if (first) return first;
  if (user.email) return user.email[0].toUpperCase();
  return 'U';
}

// Helper function to get user role display
function getUserRoleDisplay(user: { role?: string; brokerage?: string } | null): string {
  if (!user) return 'User';

  if (user.brokerage) return user.brokerage;

  switch (user.role?.toLowerCase()) {
    case 'admin':
      return 'Administrator';
    case 'agent':
      return 'Real Estate Agent';
    case 'broker':
      return 'Broker';
    case 'manager':
      return 'Team Manager';
    default:
      return user.role || 'User';
  }
}

function NavLink({ item, collapsed, isActive }: { item: typeof navItems[0]; collapsed: boolean; isActive: boolean }) {
  const Icon = item.icon;

  const linkContent = (
    <Link
      href={item.href}
      className={cn(
        'group relative flex items-center gap-3.5 px-4 py-3.5 rounded-xl font-medium transition-all duration-200',
        'text-muted-foreground',
        'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2',
        isActive
          ? 'bg-background text-primary shadow-[3px_3px_6px_#c5c8cf,-3px_-3px_6px_#ffffff] border-l-3 border-primary'
          : 'hover:bg-white/60 hover:text-foreground hover:shadow-[2px_2px_4px_#c5c8cf,-2px_-2px_4px_#ffffff] active:shadow-[inset_2px_2px_4px_#c5c8cf,inset_-2px_-2px_4px_#ffffff]',
        collapsed && 'justify-center px-3'
      )}
      aria-label={item.label}
      aria-current={isActive ? 'page' : undefined}
    >
      <Icon className={cn(
        'w-5 h-5 shrink-0 transition-all duration-200',
        isActive ? 'text-primary' : 'text-muted-foreground group-hover:text-foreground group-hover:scale-110'
      )} />
      {!collapsed && (
        <span className={cn(
          'transition-colors duration-200 overflow-hidden whitespace-nowrap',
          isActive ? 'text-primary font-semibold' : ''
        )}>
          {item.label}
        </span>
      )}
    </Link>
  );

  return (
    <Tooltip content={item.label} show={collapsed}>
      {linkContent}
    </Tooltip>
  );
}

function SidebarContent({ collapsed, setCollapsed, onMobileClose }: {
  collapsed: boolean;
  setCollapsed: (v: boolean) => void;
  onMobileClose?: () => void;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const { user, logout } = useAuth();
  const { isConnected } = useRealtimeContext();
  const [isLoggingOut, setIsLoggingOut] = useState(false);

  const handleLogout = async () => {
    setIsLoggingOut(true);
    try {
      await logout();
      router.push('/login');
    } finally {
      setIsLoggingOut(false);
    }
  };

  // Check if user is admin
  const isAdmin = user?.role?.toLowerCase() === 'admin';

  // Filter bottom nav items based on user role
  const filteredBottomNavItems = bottomNavItems.filter(
    (item) => !item.adminOnly || isAdmin
  );

  return (
    <div className="flex flex-col h-full bg-background border-r border-border/50">
      {/* Logo */}
      <div className={cn(
        'flex items-center px-4 py-3 border-b border-border/50 transition-all duration-300',
        collapsed ? 'justify-center' : 'justify-between'
      )}>
        <Link
          href="/dashboard"
          className="flex items-center gap-3 group focus:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-lg"
          aria-label="CRESync Dashboard Home"
        >
          <div className="w-9 h-9 clay-avatar shadow-[4px_4px_8px_#c5c8cf,-4px_-4px_8px_#ffffff] group-hover:shadow-[5px_5px_10px_#c5c8cf,-5px_-5px_10px_#ffffff] transition-shadow shrink-0">
            <Building2 className="w-5 h-5" />
          </div>
          <div className={cn(
            'flex flex-col transition-all duration-300 overflow-hidden',
            collapsed ? 'w-0 opacity-0' : 'w-auto opacity-100'
          )}>
            <span className="text-lg font-bold text-foreground tracking-tight whitespace-nowrap">CRESync</span>
            <span className="text-[10px] text-muted-foreground font-medium -mt-0.5 whitespace-nowrap">Real Estate CRM</span>
          </div>
        </Link>
        <div className={cn(
          'flex items-center gap-2 transition-all duration-300',
          collapsed ? 'w-0 opacity-0 overflow-hidden' : 'w-auto opacity-100'
        )}>
          {onMobileClose && (
            <button
              onClick={onMobileClose}
              className="lg:hidden clay-icon-btn w-8 h-8 hover:bg-white/60 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
              aria-label="Close sidebar"
            >
              <X className="w-4 h-4" />
            </button>
          )}
          <button
            onClick={() => setCollapsed(true)}
            className="hidden lg:flex clay-icon-btn w-8 h-8 hover:bg-white/60 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
            aria-label="Collapse sidebar"
          >
            <ChevronLeft className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Connection Status */}
      <div className={cn(
        'border-b border-border/50 transition-all duration-300 overflow-hidden',
        collapsed ? 'max-h-0 py-0 px-0 opacity-0' : 'max-h-20 px-4 py-2 opacity-100'
      )}>
        <div className="flex items-center gap-2 text-xs">
          {isConnected ? (
            <>
              <span className="w-2 h-2 rounded-full bg-emerald-500 shadow-[0_0_6px_rgba(16,185,129,0.6)]" />
              <span className="text-emerald-600 font-medium">Connected</span>
            </>
          ) : (
            <>
              <Loader2 className="w-3 h-3 text-muted-foreground animate-spin" />
              <span className="text-muted-foreground">Connecting...</span>
            </>
          )}
        </div>
      </div>

      {/* Setup Section */}
      <div className="px-3 pt-4 pb-2">
        <div className={cn(
          'px-3 mb-3 transition-all duration-300 overflow-hidden',
          collapsed ? 'max-h-0 opacity-0' : 'max-h-10 opacity-100'
        )}>
          <span className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap">Setup</span>
        </div>
        <nav className="space-y-1" role="navigation" aria-label="Setup navigation">
          {setupNavItems.map((item) => (
            <NavLink key={item.href} item={item} collapsed={collapsed} isActive={pathname === item.href} />
          ))}
        </nav>
      </div>

      {/* Main Navigation */}
      <div className="flex-1 px-3 py-2 overflow-y-auto">
        <div className={cn(
          'px-3 mb-3 transition-all duration-300 overflow-hidden',
          collapsed ? 'max-h-0 opacity-0' : 'max-h-10 opacity-100'
        )}>
          <span className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap">Main Menu</span>
        </div>
        <nav className="space-y-1" role="navigation" aria-label="Main navigation">
          {navItems.map((item) => (
            <NavLink key={item.href} item={item} collapsed={collapsed} isActive={pathname === item.href} />
          ))}
        </nav>
      </div>

      {/* System Section */}
      <div className="px-3 pb-2">
        <div className={cn(
          'px-3 mb-2 transition-all duration-300 overflow-hidden',
          collapsed ? 'max-h-0 opacity-0' : 'max-h-10 opacity-100'
        )}>
          <span className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider whitespace-nowrap">System</span>
        </div>
        <nav role="navigation" aria-label="System navigation">
          {filteredBottomNavItems.map((item) => (
            <NavLink key={item.href} item={item} collapsed={collapsed} isActive={pathname === item.href} />
          ))}
        </nav>
      </div>

      {/* User Section */}
      <div className="p-3 space-y-1 border-t border-border/50">
        {/* User Menu */}
        <div className={cn(
          'flex items-center gap-3 p-3 rounded-xl bg-background/50 shadow-[inset_2px_2px_4px_#c5c8cf,inset_-2px_-2px_4px_#ffffff] transition-all duration-300',
          collapsed && 'justify-center p-2'
        )}>
          <Tooltip content={user?.firstName ? `${user.firstName} ${user.lastName}` : 'User'} show={collapsed}>
            <div
              className="w-10 h-10 clay-avatar text-sm ring-2 ring-white/50 shadow-[3px_3px_6px_#c5c8cf,-3px_-3px_6px_#ffffff] shrink-0"
              aria-label={`User avatar: ${user?.firstName || 'User'}`}
            >
              {getUserInitials(user)}
            </div>
          </Tooltip>
          <div className={cn(
            'flex-1 min-w-0 transition-all duration-300 overflow-hidden',
            collapsed ? 'w-0 opacity-0' : 'w-auto opacity-100'
          )}>
            <p className="text-sm font-semibold text-foreground truncate">
              {user?.firstName} {user?.lastName}
            </p>
            <p className="text-xs text-muted-foreground truncate">{user?.email}</p>
          </div>
          <div className={cn(
            'transition-all duration-300 overflow-hidden',
            collapsed ? 'w-0 opacity-0' : 'w-auto opacity-100'
          )}>
            <button
              onClick={handleLogout}
              disabled={isLoggingOut}
              className={cn(
                'clay-icon-btn w-9 h-9 transition-all duration-200',
                'text-muted-foreground',
                'hover:text-destructive hover:bg-destructive/10 hover:shadow-[2px_2px_4px_#c5c8cf,-2px_-2px_4px_#ffffff]',
                'active:shadow-[inset_2px_2px_4px_#c5c8cf,inset_-2px_-2px_4px_#ffffff]',
                'focus:outline-none focus-visible:ring-2 focus-visible:ring-destructive',
                'disabled:opacity-50 disabled:cursor-not-allowed'
              )}
              aria-label="Log out"
            >
              {isLoggingOut ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <LogOut className="w-4 h-4" />
              )}
            </button>
          </div>
        </div>

        {/* Logout button when collapsed */}
        {collapsed && (
          <div className="mt-2">
            <Tooltip content="Log out" show={collapsed}>
              <button
                onClick={handleLogout}
                disabled={isLoggingOut}
                className={cn(
                  'w-full clay-icon-btn h-9 transition-all duration-200',
                  'text-muted-foreground',
                  'hover:text-destructive hover:bg-destructive/10',
                  'focus:outline-none focus-visible:ring-2 focus-visible:ring-destructive',
                  'disabled:opacity-50 disabled:cursor-not-allowed'
                )}
                aria-label="Log out"
              >
                {isLoggingOut ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <LogOut className="w-4 h-4" />
                )}
              </button>
            </Tooltip>
          </div>
        )}
      </div>

      {/* Expand Button (when collapsed) */}
      {collapsed && (
        <div className="p-3 border-t border-border/50">
          <Tooltip content="Expand sidebar" show={collapsed}>
            <button
              onClick={() => setCollapsed(false)}
              className="w-full clay-icon-btn h-9 hover:bg-white/60 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
              aria-label="Expand sidebar"
            >
              <ChevronRight className="w-4 h-4" />
            </button>
          </Tooltip>
        </div>
      )}
    </div>
  );
}

function AppLayoutContent({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const [collapsed, setCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const { user, loading } = useAuth();

  // Placeholder notification count
  const notificationCount = 3;

  // Handle Cmd/Ctrl+K for search
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setSearchOpen((prev) => !prev);
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, []);

  if (loading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <div className="flex flex-col items-center gap-4">
          <div className="w-12 h-12 border-4 border-primary/30 border-t-primary rounded-full animate-spin" />
          <p className="text-muted-foreground">Loading...</p>
        </div>
      </div>
    );
  }

  const currentPage = [...setupNavItems, ...navItems, ...bottomNavItems].find((item) => pathname === item.href)?.label || 'CRESync';

  return (
    <div className="flex min-h-screen bg-background gap-0">
      {/* Search Modal */}
      <SearchModal isOpen={searchOpen} onClose={() => setSearchOpen(false)} />

      {/* Desktop Sidebar */}
      <aside
        className={cn(
          'hidden lg:flex flex-col shrink-0 h-screen sticky top-0 transition-all duration-300 ease-in-out overflow-visible',
          collapsed ? 'w-[80px]' : 'w-[260px]'
        )}
        role="navigation"
        aria-label="Main sidebar"
      >
        <SidebarContent collapsed={collapsed} setCollapsed={setCollapsed} />
      </aside>

      {/* Mobile Sidebar Overlay */}
      {mobileOpen && (
        <div className="lg:hidden fixed inset-0 z-50" role="dialog" aria-modal="true" aria-label="Mobile navigation">
          <div
            className="absolute inset-0 bg-black/50 backdrop-blur-sm"
            onClick={() => setMobileOpen(false)}
            aria-hidden="true"
          />
          <aside className="absolute left-0 top-0 h-full w-[260px] animate-fade-in-up shadow-[8px_0_24px_rgba(0,0,0,0.1)]">
            <SidebarContent
              collapsed={false}
              setCollapsed={() => {}}
              onMobileClose={() => setMobileOpen(false)}
            />
          </aside>
        </div>
      )}

      {/* Main Content Area */}
      <div className="flex-1 flex flex-col min-w-0 relative z-0 max-h-screen">
        {/* Mobile Header */}
        <header className="lg:hidden sticky top-0 h-16 bg-background border-b border-border/50 z-30 flex items-center justify-between px-4 shadow-[0_4px_12px_#b8bcc5]">
          <div className="flex items-center gap-3">
            <button
              onClick={() => setMobileOpen(true)}
              className={cn(
                'clay-icon-btn w-10 h-10',
                'hover:bg-white/60 transition-colors',
                'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary'
              )}
              aria-label="Open navigation menu"
              aria-expanded={mobileOpen}
              aria-controls="mobile-sidebar"
            >
              <Menu className="w-5 h-5" />
            </button>
            <div className="flex items-center gap-3">
              <div className="w-9 h-9 clay-avatar shadow-[3px_3px_6px_#c5c8cf,-3px_-3px_6px_#ffffff]">
                <Building2 className="w-5 h-5" />
              </div>
              <span className="font-bold text-lg text-foreground tracking-tight">CRESync</span>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setSearchOpen(true)}
              className={cn(
                'clay-icon-btn w-9 h-9',
                'hover:bg-white/60 hover:scale-105 transition-all',
                'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary'
              )}
              aria-label="Search"
            >
              <Search className="w-4 h-4" />
            </button>
            <button
              className={cn(
                'clay-icon-btn w-9 h-9 relative',
                'hover:bg-white/60 hover:scale-105 transition-all',
                'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary'
              )}
              aria-label={`Notifications${notificationCount > 0 ? `, ${notificationCount} unread` : ''}`}
            >
              <Bell className="w-4 h-4" />
              {notificationCount > 0 && (
                <span className="absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] bg-primary text-primary-foreground text-[10px] font-bold rounded-full ring-2 ring-background flex items-center justify-center px-1">
                  {notificationCount > 99 ? '99+' : notificationCount}
                </span>
              )}
            </button>
          </div>
        </header>

        {/* Main Content */}
        <main className="flex-1 flex flex-col min-h-0" id="main-content">
        {/* Top Bar (Desktop) */}
        <header className="hidden lg:flex h-16 bg-background border-b border-border/50 items-center justify-between px-6 sticky top-0 z-20 shadow-[0_4px_12px_#b8bcc5]">
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-3">
              <div className="w-1.5 h-6 bg-gradient-to-b from-primary to-primary/60 rounded-full" aria-hidden="true" />
              <h1 className="text-xl font-bold text-foreground tracking-tight">{currentPage}</h1>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2 p-1 rounded-xl bg-background/50">
              <button
                onClick={() => setSearchOpen(true)}
                className={cn(
                  'clay-icon-btn w-10 h-10 transition-all duration-200',
                  'hover:scale-105 hover:bg-white/60 hover:shadow-[3px_3px_6px_#c5c8cf,-3px_-3px_6px_#ffffff]',
                  'active:scale-95 active:shadow-[inset_2px_2px_4px_#c5c8cf,inset_-2px_-2px_4px_#ffffff]',
                  'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2'
                )}
                aria-label="Search (Cmd+K)"
              >
                <Search className="w-5 h-5" />
              </button>
              <button
                className={cn(
                  'clay-icon-btn w-10 h-10 relative transition-all duration-200',
                  'hover:scale-105 hover:bg-white/60 hover:shadow-[3px_3px_6px_#c5c8cf,-3px_-3px_6px_#ffffff]',
                  'active:scale-95 active:shadow-[inset_2px_2px_4px_#c5c8cf,inset_-2px_-2px_4px_#ffffff]',
                  'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2'
                )}
                aria-label={`Notifications${notificationCount > 0 ? `, ${notificationCount} unread` : ''}`}
              >
                <Bell className="w-5 h-5" />
                {notificationCount > 0 && (
                  <span className="absolute -top-0.5 -right-0.5 min-w-[20px] h-[20px] bg-primary text-primary-foreground text-[10px] font-bold rounded-full ring-2 ring-background flex items-center justify-center px-1 animate-pulse">
                    {notificationCount > 99 ? '99+' : notificationCount}
                  </span>
                )}
              </button>
            </div>
            <div className="w-px h-10 bg-gradient-to-b from-transparent via-border to-transparent mx-2" aria-hidden="true" />
            <button
              className={cn(
                'flex items-center gap-3 p-2 rounded-xl transition-all duration-200',
                'hover:bg-white/50 hover:shadow-[2px_2px_4px_#c5c8cf,-2px_-2px_4px_#ffffff]',
                'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2',
                'cursor-pointer'
              )}
              aria-label={`User profile: ${user?.firstName} ${user?.lastName}`}
            >
              <div className="w-10 h-10 clay-avatar text-sm shadow-[3px_3px_6px_#c5c8cf,-3px_-3px_6px_#ffffff]">
                {getUserInitials(user)}
              </div>
              <div className="hidden xl:block text-left">
                <p className="text-sm font-semibold text-foreground">{user?.firstName} {user?.lastName}</p>
                <p className="text-xs text-muted-foreground">{getUserRoleDisplay(user)}</p>
              </div>
            </button>
          </div>
        </header>

          {/* Page Content */}
          <div className="flex-1 p-6 lg:p-8 min-h-0 overflow-auto">{children}</div>
        </main>
      </div>

      {/* Skip to main content link for accessibility */}
      <a
        href="#main-content"
        className="sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4 focus:z-[100] focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded-lg"
      >
        Skip to main content
      </a>
    </div>
  );
}

export default function AppLayout({ children }: { children: React.ReactNode }) {
  return (
    <AuthProvider>
      <RealtimeProvider>
        <AppLayoutContent>{children}</AppLayoutContent>
      </RealtimeProvider>
    </AuthProvider>
  );
}
