
import React from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { base44 } from "@/api/base44Client";
import { useQuery } from "@tanstack/react-query";
import {
  Users, LayoutDashboard, UserPlus, Calendar, Briefcase, FileText,
  DollarSign, Award, HelpCircle, BarChart3, Activity, Menu, MessageSquare,
  Package, TrendingUp, Clipboard, LogOut, Shield, MapPin, Bell, CloudOff,
  RefreshCw, User, Search, ShoppingCart, Home, Settings as SettingsIcon, MoreVertical,
  Building2, Sparkles, CheckSquare, UserCheck, Store, GraduationCap, ArrowLeft
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Sheet,
  SheetContent,
  SheetTrigger,
} from "@/components/ui/sheet";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";

import ChatBubble from "@/components/chat/ChatBubble";
import RoleSwitcher from "@/components/dev/RoleSwitcher";
import NotificationPanel from "@/components/notifications/NotificationPanel";
import { NotificationEngine } from "@/components/notifications/NotificationEngine";
import { Toaster } from "@/components/ui/toaster";

// Navigation items for each role
const roleNavigationMap = {
  admin: [
    { title: "Home", url: createPageUrl("Dashboard"), icon: LayoutDashboard },
    { title: "Orders", url: createPageUrl("Events"), icon: Calendar },
    { title: "Schedule", url: createPageUrl("Schedule"), icon: Calendar },
    { title: "Staff Availability", url: createPageUrl("StaffAvailability"), icon: Users },
    { title: "Enterprises", url: createPageUrl("EnterpriseManagement"), icon: Building2 },
    { title: "Sectors", url: createPageUrl("SectorManagement"), icon: MapPin },
    { title: "Partners", url: createPageUrl("PartnerManagement"), icon: Briefcase },
    { title: "Vendors", url: createPageUrl("VendorManagement"), icon: Package },
    { title: "Workforce", url: createPageUrl("StaffDirectory"), icon: Users },
    { title: "Onboarding", url: createPageUrl("StaffOnboarding"), icon: GraduationCap },
    { title: "Teams", url: createPageUrl("Teams"), icon: UserCheck },
    { title: "Task Board", url: createPageUrl("TaskBoard"), icon: CheckSquare },
    { title: "Messages", url: createPageUrl("Messages"), icon: MessageSquare },
    { title: "Invoices", url: createPageUrl("Invoices"), icon: FileText },
    { title: "Payroll", url: createPageUrl("Payroll"), icon: DollarSign },
    { title: "Certifications", url: createPageUrl("Certification"), icon: Award },
    { title: "Tutorials", url: createPageUrl("Tutorials"), icon: Sparkles },
    { title: "Reports", url: createPageUrl("Reports"), icon: BarChart3 },
    { title: "User Management", url: createPageUrl("UserManagement"), icon: Users },
    { title: "Permissions", url: createPageUrl("Permissions"), icon: Shield },
    { title: "Settings", url: createPageUrl("Settings"), icon: SettingsIcon },
    { title: "Activity Log", url: createPageUrl("ActivityLog"), icon: Activity },
  ],
  procurement: [
    { title: "Home", url: createPageUrl("ProcurementDashboard"), icon: LayoutDashboard },
    { title: "Orders", url: createPageUrl("Events"), icon: Calendar },
    { title: "Enterprises", url: createPageUrl("EnterpriseManagement"), icon: Building2 },
    { title: "Sectors", url: createPageUrl("SectorManagement"), icon: MapPin },
    { title: "Partners", url: createPageUrl("PartnerManagement"), icon: Briefcase },
    { title: "Vendors", url: createPageUrl("VendorManagement"), icon: Package },
    { title: "Teams", url: createPageUrl("Teams"), icon: UserCheck },
    { title: "Task Board", url: createPageUrl("TaskBoard"), icon: CheckSquare },
    { title: "Compliance", url: createPageUrl("WorkforceCompliance"), icon: Shield },
    { title: "Rate Matrix", url: createPageUrl("VendorRateCard"), icon: DollarSign },
    { title: "Messages", url: createPageUrl("Messages"), icon: MessageSquare },
    { title: "Invoices", url: createPageUrl("Invoices"), icon: FileText },
    { title: "Reports", url: createPageUrl("Reports"), icon: BarChart3 },
  ],
  operator: [
    { title: "Home", url: createPageUrl("OperatorDashboard"), icon: LayoutDashboard },
    { title: "Orders", url: createPageUrl("Events"), icon: Calendar },
    { title: "My Sectors", url: createPageUrl("SectorManagement"), icon: MapPin },
    { title: "Partners", url: createPageUrl("PartnerManagement"), icon: Briefcase },
    { title: "Vendors", url: createPageUrl("VendorManagement"), icon: Package },
    { title: "Clients", url: createPageUrl("Business"), icon: Users },
    { title: "Workforce", url: createPageUrl("StaffDirectory"), icon: Users },
    { title: "Teams", url: createPageUrl("Teams"), icon: UserCheck },
    { title: "Task Board", url: createPageUrl("TaskBoard"), icon: CheckSquare },
    { title: "Messages", url: createPageUrl("Messages"), icon: MessageSquare },
    { title: "Invoices", url: createPageUrl("Invoices"), icon: FileText },
    { title: "Reports", url: createPageUrl("Reports"), icon: BarChart3 },
  ],
  sector: [
    { title: "Home", url: createPageUrl("OperatorDashboard"), icon: LayoutDashboard },
    { title: "Orders", url: createPageUrl("Events"), icon: Calendar },
    { title: "Partners", url: createPageUrl("PartnerManagement"), icon: Briefcase },
    { title: "Vendors", url: createPageUrl("VendorManagement"), icon: Package },
    { title: "Clients", url: createPageUrl("Business"), icon: Users },
    { title: "Workforce", url: createPageUrl("StaffDirectory"), icon: Users },
    { title: "Teams", url: createPageUrl("Teams"), icon: UserCheck },
    { title: "Task Board", url: createPageUrl("TaskBoard"), icon: CheckSquare },
    { title: "Messages", url: createPageUrl("Messages"), icon: MessageSquare },
    { title: "Invoices", url: createPageUrl("Invoices"), icon: FileText },
    { title: "Reports", url: createPageUrl("Reports"), icon: BarChart3 },
  ],
  client: [
    { title: "Home", url: createPageUrl("ClientDashboard"), icon: LayoutDashboard },
    { title: "My Orders", url: createPageUrl("ClientOrders"), icon: Clipboard },
    { title: "New Order", url: createPageUrl("CreateEvent"), icon: UserPlus },
    { title: "Vendor Marketplace", url: createPageUrl("VendorMarketplace"), icon: Store },
    { title: "Compare Rates", url: createPageUrl("VendorRateCard"), icon: DollarSign },
    { title: "Teams", url: createPageUrl("Teams"), icon: UserCheck },
    { title: "Task Board", url: createPageUrl("TaskBoard"), icon: CheckSquare },
    { title: "Messages", url: createPageUrl("Messages"), icon: MessageSquare },
    { title: "Invoices", url: createPageUrl("Invoices"), icon: FileText },
    { title: "Tutorials", url: createPageUrl("Tutorials"), icon: Sparkles },
    { title: "Reports", url: createPageUrl("Reports"), icon: BarChart3 },
    { title: "Support", url: createPageUrl("Support"), icon: HelpCircle },
  ],
  vendor: [
    { title: "Home", url: createPageUrl("VendorDashboard"), icon: LayoutDashboard },
    { title: "Orders", url: createPageUrl("VendorOrders"), icon: FileText },
    { title: "Service Rates", url: createPageUrl("VendorRates"), icon: DollarSign },
    { title: "Invoices", url: createPageUrl("Invoices"), icon: Clipboard },
    { title: "Schedule", url: createPageUrl("Schedule"), icon: Calendar },
    { title: "Staff Availability", url: createPageUrl("StaffAvailability"), icon: Users },
    { title: "Workforce", url: createPageUrl("StaffDirectory"), icon: Users },
    { title: "Onboard Staff", url: createPageUrl("StaffOnboarding"), icon: GraduationCap },
    { title: "Team", url: createPageUrl("Teams"), icon: UserCheck },
    { title: "Task Board", url: createPageUrl("TaskBoard"), icon: CheckSquare },
    { title: "Compliance", url: createPageUrl("VendorCompliance"), icon: Shield },
    { title: "Communications", url: createPageUrl("Messages"), icon: MessageSquare },
    { title: "Leads", url: createPageUrl("Business"), icon: UserCheck },
    { title: "Business", url: createPageUrl("Business"), icon: Briefcase },
    { title: "Reports", url: createPageUrl("Reports"), icon: BarChart3 },
    { title: "Audit Trail", url: createPageUrl("ActivityLog"), icon: Activity },
    { title: "Performance", url: createPageUrl("VendorPerformance"), icon: TrendingUp },
  ],
  workforce: [
    { title: "Home", url: createPageUrl("WorkforceDashboard"), icon: LayoutDashboard },
    { title: "Shift Requests", url: createPageUrl("WorkerShiftProposals"), icon: Calendar },
    { title: "Onboard Staff", url: createPageUrl("StaffOnboarding"), icon: GraduationCap },
    { title: "My Shifts", url: createPageUrl("WorkforceShifts"), icon: Calendar },
    { title: "Teams", url: createPageUrl("Teams"), icon: UserCheck },
    { title: "Task Board", url: createPageUrl("TaskBoard"), icon: CheckSquare },
    { title: "Messages", url: createPageUrl("Messages"), icon: MessageSquare },
    { title: "Certifications", url: createPageUrl("Certification"), icon: Award },
    { title: "Earnings", url: createPageUrl("WorkforceEarnings"), icon: DollarSign },
    { title: "Reports", url: createPageUrl("Reports"), icon: BarChart3 },
    { title: "Profile", url: createPageUrl("WorkforceProfile"), icon: Users },
  ],
};

const getRoleName = (role) => {
  const names = {
    admin: "KROW Admin",
    procurement: "Procurement Manager",
    operator: "Operator",
    sector: "Sector Manager",
    client: "Client",
    vendor: "Vendor Partner",
    workforce: "Staff Member"
  };
  return names[role] || "User";
};

const getRoleDescription = (role) => {
  const descriptions = {
    admin: "Platform Administrator",
    procurement: "Connects Operators, Sectors & Vendors",
    operator: "Manages Multiple Sectors",
    sector: "Branch Location Manager",
    client: "Service Requester",
    vendor: "Workforce Provider",
    workforce: "Service Professional"
  };
  return descriptions[role] || "";
};

const getDashboardUrl = (role) => {
  const dashboardMap = {
    admin: "Dashboard",
    procurement: "ProcurementDashboard",
    operator: "OperatorDashboard",
    sector: "OperatorDashboard",
    client: "ClientDashboard",
    vendor: "VendorDashboard",
    workforce: "WorkforceDashboard"
  };
  return createPageUrl(dashboardMap[role] || "Dashboard");
};

const getLayerName = (role) => {
  const layers = {
    admin: "KROW Admin",
    procurement: "Procurement",
    operator: "Operator",
    sector: "Sector",
    client: "Client",
    vendor: "Vendor",
    workforce: "Workforce"
  };
  return layers[role] || "User";
};

const getLayerColor = (role) => {
  const colors = {
    admin: "from-red-500 to-red-700",
    procurement: "from-[#0A39DF] to-[#1C323E]",
    operator: "from-emerald-500 to-emerald-700",
    sector: "from-purple-500 to-purple-700",
    client: "from-green-500 to-green-700",
    vendor: "from-amber-500 to-amber-700",
    workforce: "from-slate-500 to-slate-700"
  };
  return colors[role] || "from-blue-500 to-blue-700";
};

function NavigationMenu({ location, userRole, closeSheet }) {
  const navigationItems = roleNavigationMap[userRole] || roleNavigationMap.admin;

  return (
    <nav className="space-y-1">
      <div className="px-4 py-2 text-xs font-semibold text-slate-400 uppercase tracking-wider">
        Main Menu
      </div>
      {navigationItems.map((item) => {
        const isActive = location.pathname === item.url;
        return (
          <Link
            key={item.title}
            to={item.url}
            onClick={closeSheet}
            className={`flex items-center gap-3 px-4 py-2.5 rounded-lg transition-all duration-200 ${
              isActive
                ? 'bg-[#0A39DF] text-white shadow-md font-medium'
                : 'text-slate-600 hover:bg-slate-100 hover:text-[#1C323E]'
            }`}
          >
            <item.icon className="w-5 h-5" />
            <span className="text-sm">{item.title}</span>
          </Link>
        );
      })}
    </nav>
  );
}

export default function Layout({ children }) {
  const location = useLocation();
  const navigate = useNavigate();
  const [showNotifications, setShowNotifications] = React.useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = React.useState(false);

  const { data: user } = useQuery({
    queryKey: ['current-user-layout'],
    queryFn: () => base44.auth.me(),
  });

  const sampleAvatar = "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=400&h=400&fit=crop";
  const userAvatar = user?.profile_picture || sampleAvatar;

  const { data: unreadCount = 0 } = useQuery({
    queryKey: ['unread-notifications', user?.id],
    queryFn: async () => {
      if (!user?.id) return 0;
      
      const notifications = await base44.entities.ActivityLog.filter({
        userId: user?.id,
        isRead: false
      });
      return notifications.length;
    },
    enabled: !!user?.id,
    initialData: 0,
    refetchInterval: 10000,
  });

  const userRole = user?.user_role || user?.role || "admin";
  const userName = user?.full_name || user?.email || "User";
  const userInitial = userName.charAt(0).toUpperCase();

  const handleLogout = () => {
    base44.auth.logout();
  };

  const handleRefresh = () => {
    window.location.reload();
  };

  return (
    <div className="min-h-screen flex flex-col w-full bg-slate-50">
      <style>{`
        :root {
          --primary: 10 57 223;
          --primary-foreground: 255 255 255;
          --secondary: 200 219 220;
          --accent: 28 50 62;
          --muted: 241 245 249;
        }
        
        .rdp * { border-color: transparent !important; }
        .rdp-day { font-size: 0.875rem !important; min-width: 36px !important; height: 36px !important; border-radius: 50% !important; transition: all 0.2s ease !important; font-weight: 500 !important; position: relative !important; }
        .rdp-day button { width: 100% !important; height: 100% !important; border-radius: 50% !important; background-color: transparent !important; }
        .rdp-day_range_start, .rdp-day_range_start > button { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important; color: white !important; font-weight: 700 !important; border-radius: 50% !important; box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3) !important; }
        .rdp-day_range_end, .rdp-day_range_end > button { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important; color: white !important; font-weight: 700 !important; border-radius: 50% !important; box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3) !important; }
        .rdp-day_selected:not(.rdp-day_range_start):not(.rdp-day_range_end), .rdp-day_selected:not(.rdp-day_range_start):not(.rdp-day_range_end) > button { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important; color: white !important; font-weight: 700 !important; border-radius: 50% !important; box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3) !important; }
        .rdp-day_selected, .rdp-day_selected > button { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important; color: white !important; font-weight: 700 !important; border-radius: 50% !important; box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3) !important; }
        .rdp-day_range_middle, .rdp-day_range_middle > button { background-color: #dbeafe !important; background: #dbeafe !important; color: #2563eb !important; font-weight: 600 !important; border-radius: 0 !important; box-shadow: none !important; }
        .rdp-day_range_start.rdp-day_range_end, .rdp-day_range_start.rdp-day_range_end > button { border-radius: 50% !important; background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%) !important; }
        .rdp-day:hover:not(.rdp-day_selected):not(.rdp-day_disabled):not(.rdp-day_range_start):not(.rdp-day_range_end):not(.rdp-day_range_middle) > button { background-color: #eff6ff !important; background: #eff6ff !important; color: #2563eb !important; border-radius: 50% !important; }
        .rdp-day_today:not(.rdp-day_selected):not(.rdp-day_range_start):not(.rdp-day_range_end)::after { content: '' !important; position: absolute !important; bottom: 4px !important; left: 50% !important; transform: translateX(-50%) !important; width: 4px !important; height: 4px !important; background-color: #ec4899 !important; border-radius: 50% !important; z-index: 10 !important; }
        .rdp-day_today.rdp-day_selected, .rdp-day_today.rdp-day_range_start, .rdp-day_today.rdp-day_range_end { color: white !important; }
        .rdp-day_today.rdp-day_selected > button, .rdp-day_today.rdp-day_range_start > button, .rdp-day_today.rdp-day_range_end > button { color: white !important; }
        .rdp-day_outside, .rdp-day_outside > button { color: #cbd5e1 !important; opacity: 0.5 !important; }
        .rdp-day_disabled, .rdp-day_disabled > button { opacity: 0.3 !important; cursor: not-allowed !important; }
        .rdp-day_selected, .rdp-day_range_start, .rdp-day_range_end, .rdp-day_range_middle { opacity: 1 !important; visibility: visible !important; z-index: 5 !important; }
        .rdp-day.has-events:not(.rdp-day_selected):not(.rdp-day_range_start):not(.rdp-day_range_end)::before { content: '' !important; position: absolute !important; top: 4px !important; right: 4px !important; width: 4px !important; height: 4px !important; background-color: #2563eb !important; border-radius: 50% !important; }
        .rdp-day_selected.has-events::before, .rdp-day_range_start.has-events::before, .rdp-day_range_end.has-events::before { background-color: white !important; }
        .rdp-day_range_middle.has-events::before { background-color: #2563eb !important; }
        .rdp-head_cell { color: #64748b !important; font-weight: 600 !important; font-size: 0.75rem !important; text-transform: uppercase !important; padding: 8px 0 !important; }
        .rdp-caption_label { font-size: 1rem !important; font-weight: 700 !important; color: #0f172a !important; }
        .rdp-nav_button { width: 32px !important; height: 32px !important; border-radius: 6px !important; transition: all 0.2s ease !important; }
        .rdp-nav_button:hover { background-color: #eff6ff !important; color: #2563eb !important; }
        .rdp-months { gap: 2rem !important; }
        .rdp-month { padding: 0.75rem !important; }
        .rdp-table { border-spacing: 0 !important; margin-top: 1rem !important; }
        .rdp-cell { padding: 2px !important; }
        .rdp-day[style*="background"] { background: transparent !important; }
      `}</style>

      <header className="bg-white border-b border-slate-200 shadow-sm sticky top-0 z-30">
        <div className="px-4 md:px-6 py-3 flex items-center justify-between gap-4">
          <div className="flex items-center gap-4 flex-1">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => navigate(-1)}
              className="hover:bg-slate-100"
              title="Go back"
            >
              <ArrowLeft className="w-5 h-5 text-slate-600" />
            </Button>

            <Sheet open={mobileMenuOpen} onOpenChange={setMobileMenuOpen}>
              <SheetTrigger asChild>
                <Button variant="ghost" size="icon" className="lg:hidden hover:bg-slate-100">
                  <Menu className="w-5 h-5 text-[#1C323E]" />
                </Button>
              </SheetTrigger>
              <SheetContent side="left" className="w-64 p-0 bg-white border-slate-200">
                <div className="border-b border-slate-200 p-6">
                  <Link to={getDashboardUrl(userRole)} className="flex items-center gap-3 mb-4" onClick={() => setMobileMenuOpen(false)}>
                    <div className="w-8 h-8 flex items-center justify-center">
                      <img src="https://qtrypzzcjebvfcihiynt.supabase.co/storage/v1/object/public/base44-prod/public/68fc6cf01386035c266e7a5d/3ba390829_KROWlogo.png" alt="KROW Logo" className="w-full h-full object-contain" />
                    </div>
                    <h2 className="font-bold text-[#1C323E]">KROW</h2>
                  </Link>
                  <div className="flex items-center gap-3 bg-slate-50 p-3 rounded-lg">
                    <Avatar className="w-10 h-10">
                      <AvatarImage src={userAvatar} alt={userName} />
                      <AvatarFallback className="bg-[#0A39DF] text-white font-bold">{userInitial}</AvatarFallback>
                    </Avatar>
                    <div className="flex-1 min-w-0">
                      <p className="font-semibold text-[#1C323E] text-sm truncate">{userName}</p>
                      <p className="text-xs text-slate-500 truncate">{getRoleName(userRole)}</p>
                    </div>
                  </div>
                </div>
                <div className="p-3">
                  <NavigationMenu location={location} userRole={userRole} closeSheet={() => setMobileMenuOpen(false)} />
                </div>
                <div className="p-3 border-t border-slate-200">
                  <Button variant="ghost" className="w-full justify-start text-red-600 hover:text-red-700 hover:bg-red-50" onClick={() => {handleLogout(); setMobileMenuOpen(false);}}>
                    <LogOut className="w-4 h-4 mr-2" />Logout
                  </Button>
                </div>
              </SheetContent>
            </Sheet>

            <Link to={getDashboardUrl(userRole)} className="flex items-center gap-2 hover:opacity-80 transition-opacity">
              <div className="w-8 h-8 flex items-center justify-center">
                <img src="https://qtrypzzcjebvfcihiynt.supabase.co/storage/v1/object/public/base44-prod/public/68fc6cf01386035c266e7a5d/3ba390829_KROWlogo.png" alt="KROW Logo" className="w-full h-full object-contain" />
              </div>
              <div className="hidden sm:block">
                <h1 className="text-base font-bold text-[#1C323E]">KROW Workforce Control Tower</h1>
              </div>
            </Link>

            <div className="hidden md:flex flex-1 max-w-xl">
              <div className="relative w-full">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400" />
                <input type="text" placeholder="Find employees, menu items, settings, and more..." className="w-full pl-10 pr-4 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#0A39DF] focus:border-transparent" />
              </div>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <button onClick={handleRefresh} className="flex items-center gap-2 px-3 py-2 text-slate-500 hover:text-[#0A39DF] hover:bg-blue-50 rounded-lg transition-all group" title="Unpublished changes - Click to refresh">
              <CloudOff className="w-5 h-5 group-hover:animate-pulse" />
              <span className="hidden lg:inline text-sm font-medium">Unpublished changes</span>
            </button>

            <Button variant="ghost" size="icon" className="md:hidden hover:bg-slate-100" title="Search">
              <Search className="w-5 h-5 text-slate-600" />
            </Button>

            <button onClick={() => setShowNotifications(true)} className="relative p-2 hover:bg-slate-100 rounded-lg transition-colors" title="Notifications">
              <Bell className="w-5 h-5 text-slate-600" />
              {unreadCount > 0 && (
                <span className="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center">
                  {unreadCount > 9 ? '9+' : unreadCount}
                </span>
              )}
            </button>

            <Link to={getDashboardUrl(userRole)} title="Home">
              <Button variant="ghost" size="icon" className="hover:bg-slate-100">
                <Home className="w-5 h-5 text-slate-600" />
              </Button>
            </Link>

            <Link to={createPageUrl("Messages")} title="Messages">
              <Button variant="ghost" size="icon" className="hover:bg-slate-100">
                <MessageSquare className="w-5 h-5 text-slate-600" />
              </Button>
            </Link>

            <Link to={createPageUrl("Support")} title="Help & Support">
              <Button variant="ghost" size="icon" className="hover:bg-slate-100">
                <HelpCircle className="w-5 h-5 text-slate-600" />
              </Button>
            </Link>

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="icon" className="hover:bg-slate-100" title="More options">
                  <MoreVertical className="w-5 h-5 text-slate-600" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-56">
                <DropdownMenuItem onClick={() => window.location.href = createPageUrl("NotificationSettings")}>
                  <Bell className="w-4 h-4 mr-2" />Notification Settings
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => window.location.href = createPageUrl("Settings")}>
                  <SettingsIcon className="w-4 h-4 mr-2" />Settings
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => window.location.href = createPageUrl("Reports")}>
                  <FileText className="w-4 h-4 mr-2" />Reports
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => window.location.href = createPageUrl("ActivityLog")}>
                  <Activity className="w-4 h-4 mr-2" />Activity Log
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={handleLogout} className="text-red-600">
                  <LogOut className="w-4 h-4 mr-2" />Logout
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button className="flex items-center gap-2 hover:bg-slate-100 rounded-lg p-1.5 transition-colors" title={`${userName} - ${getRoleName(userRole)}`}>
                  <Avatar className="w-8 h-8">
                    <AvatarImage src={userAvatar} alt={userName} />
                    <AvatarFallback className="bg-gradient-to-br from-[#0A39DF] to-[#1C323E] text-white font-bold text-sm">{userInitial}</AvatarFallback>
                  </Avatar>
                  <span className="hidden lg:block text-sm font-medium text-slate-700">{userName.split(' ')[0]}</span>
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-56">
                <DropdownMenuLabel>
                  <div>
                    <p className="font-semibold">{userName}</p>
                    <p className="text-xs text-slate-500">{user?.email}</p>
                    <p className="text-xs text-slate-500 mt-1">{getRoleName(userRole)}</p>
                  </div>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => window.location.href = getDashboardUrl(userRole)}>
                  <Home className="w-4 h-4 mr-2" />Dashboard
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => window.location.href = createPageUrl("WorkforceProfile")}>
                  <User className="w-4 h-4 mr-2" />My Profile
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={handleLogout} className="text-red-600 focus:text-red-600">
                  <LogOut className="w-4 h-4 mr-2" />
                  <span>Logout</span>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </header>

      <div className="flex flex-1 overflow-hidden">
        <aside className="hidden lg:flex lg:flex-col w-64 bg-white border-r border-slate-200 shadow-sm overflow-y-auto">
          <div className="p-3">
            <NavigationMenu location={location} userRole={userRole} closeSheet={() => {}} />
          </div>
        </aside>

        <main className="flex-1 overflow-auto pb-16">
          {children}
        </main>
      </div>

      <div className="fixed bottom-0 left-0 right-0 z-20 bg-white border-t-2 border-slate-200 shadow-lg">
        <div className="px-4 py-2 flex items-center justify-center gap-3">
          <span className="text-xs text-slate-500 font-medium">Current:</span>
          <div className={`px-4 py-1.5 rounded-full bg-gradient-to-r ${getLayerColor(userRole)} text-white font-bold text-sm shadow-md`}>
            {getLayerName(userRole)}
          </div>
        </div>
      </div>

      <NotificationPanel isOpen={showNotifications} onClose={() => setShowNotifications(false)} />
      <NotificationEngine />
      <ChatBubble />
      <RoleSwitcher />
      <Toaster />
    </div>
  );
}
