"use client";

import React, { useState, useRef, useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  Home,
  BookOpen,
  Users,
  UserCheck,
  CalendarCheck,
  Award,
  FileSpreadsheet,
  Shield,
  Settings,
  Search,
  Menu,
  X,
  LogOut,
  ChevronDown,
  Bell,
  Calendar,
  GraduationCap,
  Layers,
  FileText,
  Hash,
  CalendarHeart,
  Building2,
  BarChart3,
  Clock,
  PieChart,
  UserPlus,
  UploadCloud,
  CalendarDays,
  KeyRound,
  Repeat,
  History,
  AlertTriangle,
  HeartPulse,
  DoorOpen,
  AlertCircle,
  TrendingUp,
  ShieldCheck,
  ScrollText,
  Sliders,
  FlaskConical,
  Atom,
  Lock,
  CheckCircle2,
  CheckSquare,
  Gauge,
  FileCheck,
  FileCheck2,
  RefreshCw,
  SlidersHorizontal,
  Database,
  UtensilsCrossed,
  Sparkles,
  Command,
  HelpCircle,
  ExternalLink,
} from "lucide-react";
import { RouteGuard } from "@/components/auth/route-guard";
import { useAuth } from "@/context/auth-context";
import { SidebarBuildingFooter } from "@/components/layout/sidebar-building-footer";
import { cn } from "@/lib/utils";
import { toast } from "sonner";

interface SubmenuItem {
  title: string;
  href: string;
  icon?: React.ElementType;
}

interface NavItem {
  label: string;
  href: string;
  icon: React.ElementType;
  badge?: string;
  submenus?: SubmenuItem[];
}

// 12 Institutional Primary Modules Matching the Comprehensive Academic System
const adminNavigation: NavItem[] = [
  {
    label: "Dashboard",
    href: "/admin/dashboard",
    icon: Home,
  },
  {
    label: "Academic Management",
    href: "/admin/academic/sessions",
    icon: BookOpen,
    submenus: [
      { title: "Academic Sessions", href: "/admin/academic/sessions", icon: Calendar },
      { title: "Courses & Programs", href: "/admin/academic/courses", icon: GraduationCap },
      { title: "Semesters", href: "/admin/academic/semesters", icon: Layers },
      { title: "Subjects", href: "/admin/academic/subjects", icon: FileText },
      { title: "Subject Codes", href: "/admin/academic/subject-codes", icon: Hash },
      { title: "Student Groups", href: "/admin/academic/groups", icon: Users },
      { title: "Holiday Calendar", href: "/admin/holidays", icon: CalendarHeart },
    ],
  },
  {
    label: "Student Management",
    href: "/admin/people/students",
    icon: Users,
    submenus: [
      { title: "All Students Roster", href: "/admin/people/students", icon: Users },
      { title: "Student Registration", href: "/admin/people/students/register", icon: UserPlus },
      { title: "Student Profiles", href: "/admin/people/students/profiles", icon: UserCheck },
      { title: "Academic Records", href: "/admin/people/students/records", icon: Award },
      { title: "Bulk CSV Import", href: "/admin/people/students/import", icon: UploadCloud },
    ],
  },
  {
    label: "Faculty Management",
    href: "/admin/people/faculty",
    icon: UserCheck,
    submenus: [
      { title: "Faculty Directory", href: "/admin/people/faculty", icon: Users },
      { title: "Faculty Registration", href: "/admin/people/faculty/register", icon: UserPlus },
      { title: "Faculty Profiles", href: "/admin/people/faculty/profiles", icon: UserCheck },
      { title: "Faculty Schedule", href: "/admin/people/faculty/schedule", icon: CalendarDays },
      { title: "Faculty Workload", href: "/admin/people/faculty/workload", icon: Clock },
      { title: "Faculty Allocation", href: "/admin/people/faculty/allocations", icon: CalendarDays },
      { title: "Faculty Credentials", href: "/admin/people/faculty/accounts", icon: KeyRound },
    ],
  },
  {
    label: "Timetable Management",
    href: "/admin/timetable",
    icon: Clock,
    submenus: [
      { title: "Master Weekly Timetable", href: "/admin/timetable", icon: CalendarDays },
      { title: "Semester Timetable", href: "/admin/timetable/semester", icon: Clock },
      { title: "Theory Schedule", href: "/admin/timetable/theory", icon: BookOpen },
      { title: "Practical Schedule", href: "/admin/timetable/practical", icon: FlaskConical },
      { title: "Kitchen Practical Schedule", href: "/admin/timetable/kitchen", icon: UtensilsCrossed },
      { title: "Laboratory Schedule", href: "/admin/timetable/laboratory", icon: Atom },
      { title: "Classroom Allocation", href: "/admin/timetable/classrooms", icon: DoorOpen },
      { title: "Faculty Timetable", href: "/admin/people/faculty/schedule", icon: UserCheck },
      { title: "Subject-wise Schedule", href: "/admin/timetable/subject-wise", icon: FileText },
      { title: "Room Allocation", href: "/admin/academic/rooms", icon: Building2 },
    ],
  },
  {
    label: "Attendance Management",
    href: "/admin/sessions/generator",
    icon: CalendarCheck,
    submenus: [
      { title: "Daily Attendance Session", href: "/admin/sessions/generator", icon: CalendarCheck },
      { title: "Theory Attendance", href: "/admin/attendance/theory", icon: BookOpen },
      { title: "Practical Attendance", href: "/admin/attendance/practical", icon: FlaskConical },
      { title: "Monthly Attendance Register", href: "/admin/reports/monthly-matrix", icon: History },
      { title: "Attendance Modification", href: "/admin/sessions/substitutions", icon: Repeat },
      { title: "Attendance Lock / Unlock", href: "/admin/attendance/lock", icon: Lock },
      { title: "Holiday Declaration", href: "/admin/holidays", icon: CalendarHeart },
      { title: "Attendance Audit Trail", href: "/admin/attendance/audit", icon: ShieldCheck },
    ],
  },
  {
    label: "Medical & Condonation",
    href: "/admin/adjustments/medical",
    icon: HeartPulse,
    submenus: [
      { title: "Medical Adjustment Requests", href: "/admin/adjustments/medical", icon: HeartPulse },
      { title: "Medical Certificate Reference", href: "/admin/adjustments/medical/certificates", icon: FileCheck2 },
      { title: "Medical Approvals", href: "/admin/adjustments/medical/approvals", icon: CheckCircle2 },
      { title: "Configurable Medical %", href: "/admin/adjustments/medical/policy", icon: Sliders },
      { title: "Condonation Requests", href: "/admin/adjustments/condonation", icon: FileText },
      { title: "Condonation Approvals", href: "/admin/adjustments/condonation/approvals", icon: CheckSquare },
      { title: "Approved Attendance Hours", href: "/admin/adjustments/approved", icon: Award },
      { title: "Attendance Recalculation", href: "/admin/adjustments/recalculation", icon: RefreshCw },
      { title: "Medical Adjustment History", href: "/admin/adjustments/history", icon: History },
      { title: "Approval Audit Trail", href: "/admin/adjustments/audit-trail", icon: ShieldCheck },
    ],
  },
  {
    label: "Attendance Rules & Defaulters",
    href: "/admin/defaulters",
    icon: AlertTriangle,
    submenus: [
      { title: "Attendance Rules", href: "/admin/attendance/rules", icon: Sliders },
      { title: "Threshold Configuration", href: "/admin/attendance/thresholds", icon: Gauge },
      { title: "Medical Attendance Ceiling", href: "/admin/attendance/medical-ceiling", icon: HeartPulse },
      { title: "Condonation Rules", href: "/admin/attendance/condonation-rules", icon: FileCheck },
      { title: "Defaulters List", href: "/admin/defaulters", icon: AlertTriangle },
      { title: "Alerts / Warnings", href: "/admin/attendance/alerts", icon: Bell },
    ],
  },
  {
    label: "APR Generation",
    href: "/admin/apr",
    icon: FileSpreadsheet,
    submenus: [
      { title: "Generate APR", href: "/admin/apr", icon: Award },
      { title: "Monthly APR", href: "/admin/apr/monthly", icon: Calendar },
      { title: "Semester APR", href: "/admin/examinations/semester", icon: Layers },
      { title: "Faculty-wise APR", href: "/admin/apr/faculty", icon: UserCheck },
      { title: "Subject-wise APR", href: "/admin/apr/subject", icon: BookOpen },
      { title: "Student-wise APR", href: "/admin/apr/student", icon: GraduationCap },
    ],
  },
  {
    label: "Reports & Analytics",
    href: "/admin/reports/monthly-matrix",
    icon: BarChart3,
    submenus: [
      { title: "Daily Attendance Register", href: "/admin/reports/daily-register", icon: CalendarDays },
      { title: "Monthly Attendance Register", href: "/admin/reports/monthly-matrix", icon: FileSpreadsheet },
      { title: "Subject-wise Attendance Report", href: "/admin/reports/subject-wise", icon: FileText },
      { title: "Semester-wise Attendance Report", href: "/admin/reports/semester-wise", icon: Layers },
      { title: "Student Attendance History", href: "/admin/reports/student-history", icon: History },
      { title: "Faculty Attendance Report", href: "/admin/reports/faculty-report", icon: UserCheck },
      { title: "Attendance Defaulter List", href: "/admin/defaulters", icon: AlertCircle },
      { title: "Condonation Report", href: "/admin/reports/condonation", icon: FileCheck },
      { title: "Medical Adjustment Report", href: "/admin/reports/medical", icon: HeartPulse },
      { title: "Holiday Report", href: "/admin/reports/holidays", icon: CalendarHeart },
      { title: "APR Report", href: "/admin/apr", icon: TrendingUp },
      { title: "Attendance Percentage Report", href: "/admin/reports/percentage", icon: PieChart },
    ],
  },
  {
    label: "Users & Roles",
    href: "/admin/roles",
    icon: Shield,
    submenus: [
      { title: "User Directory", href: "/admin/people/faculty/accounts", icon: Users },
      { title: "Security Roles", href: "/admin/roles", icon: ShieldCheck },
      { title: "Access Permissions", href: "/admin/roles/permissions", icon: KeyRound },
      { title: "Activity Audit Logs", href: "/admin/audit-logs", icon: ScrollText },
    ],
  },
  {
    label: "System Settings",
    href: "/admin/policies",
    icon: Settings,
    submenus: [
      { title: "Institution Profile", href: "/admin/settings/institution", icon: Building2 },
      { title: "Academic Configuration", href: "/admin/academic/sessions", icon: BookOpen },
      { title: "Attendance Settings", href: "/admin/settings/attendance", icon: CalendarCheck },
      { title: "Notification Settings", href: "/admin/settings/notifications", icon: Bell },
      { title: "Security & Audit", href: "/admin/audit-logs", icon: Shield },
      { title: "Session Settings", href: "/admin/settings/sessions", icon: Sliders },
      { title: "Backup & Restore", href: "/admin/settings/backup", icon: Database },
      { title: "Global Configuration", href: "/admin/settings/global", icon: SlidersHorizontal },
    ],
  },
];

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const { user, logout } = useAuth();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [openCategory, setOpenCategory] = useState<string | null>("Academic Management");

  // Topbar dropdown states
  const [notifOpen, setNotifOpen] = useState(false);
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const [searchVal, setSearchVal] = useState("");

  const notifRef = useRef<HTMLDivElement>(null);
  const userMenuRef = useRef<HTMLDivElement>(null);

  // Close popovers on click outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (notifRef.current && !notifRef.current.contains(event.target as Node)) {
        setNotifOpen(false);
      }
      if (userMenuRef.current && !userMenuRef.current.contains(event.target as Node)) {
        setUserMenuOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Calculate single active category and single active submenu
  let activeCategoryLabel = "";
  let activeSubmenuTitle = "";

  // 1. Exact submenu match first
  for (const item of adminNavigation) {
    if (item.submenus) {
      for (const sub of item.submenus) {
        if (pathname === sub.href) {
          activeCategoryLabel = item.label;
          activeSubmenuTitle = sub.title;
          break;
        }
      }
    }
    if (activeCategoryLabel) break;
  }

  // 2. Exact main module href match if not matched by submenu
  if (!activeCategoryLabel) {
    for (const item of adminNavigation) {
      if (pathname === item.href) {
        activeCategoryLabel = item.label;
        break;
      }
    }
  }

  // 3. Fallback prefix match for nested routes
  if (!activeCategoryLabel) {
    let longestMatchLen = 0;
    for (const item of adminNavigation) {
      if (item.submenus) {
        for (const sub of item.submenus) {
          if (pathname.startsWith(sub.href + "/") && sub.href.length > longestMatchLen) {
            activeCategoryLabel = item.label;
            activeSubmenuTitle = sub.title;
            longestMatchLen = sub.href.length;
          }
        }
      }
      if (pathname.startsWith(item.href + "/") && item.href.length > longestMatchLen) {
        activeCategoryLabel = item.label;
        longestMatchLen = item.href.length;
      }
    }
  }

  // Automatically keep active category open on initial load and route changes (closing any others)
  useEffect(() => {
    if (activeCategoryLabel) {
      setOpenCategory(activeCategoryLabel);
    }
  }, [activeCategoryLabel, pathname]);

  // SINGLE ACCORDION TOGGLE:
  // When opening one category, automatically close any previously open category!
  // If clicking an already open category's chevron, collapse it.
  const handleToggleCategory = (categoryLabel: string) => {
    setOpenCategory((prev) => (prev === categoryLabel ? null : categoryLabel));
  };

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!searchVal.trim()) return;
    toast.info(`Searching for "${searchVal}" across institutional records...`);
  };

  return (
    <RouteGuard allowedRoles={["SUPER_ADMIN", "ACADEMIC_ADMIN"]}>
      <div className="min-h-screen flex bg-[#F8FAFC] text-[#334155] font-sans selection:bg-[#F4B400] selection:text-[#081A2E]">
        {/* Mobile Sidebar Backdrop */}
        {sidebarOpen && (
          <div
            onClick={() => setSidebarOpen(false)}
            className="fixed inset-0 bg-[#081A2E]/70 z-40 lg:hidden backdrop-blur-2xs animate-in fade-in duration-200"
          />
        )}

        {/* ============================================================ */}
        {/* DEEP NAVY INSTITUTIONAL STICKY SIDEBAR (#081A2E) - 220px     */}
        {/* ============================================================ */}
        <aside
          className={cn(
            "fixed inset-y-0 left-0 z-50 w-[220px] h-screen bg-[#081A2E] text-[#F5F7FA] flex flex-col justify-between transition-transform duration-200 ease-in-out lg:sticky lg:top-0 lg:h-screen lg:shrink-0 lg:translate-x-0 shadow-xl border-r border-[#0d2238]",
            sidebarOpen ? "translate-x-0" : "-translate-x-full"
          )}
        >
          {/* Top Brand with Golden Crest */}
          <div className="shrink-0 p-3.5 border-b border-white/10 flex items-center justify-between">
            <Link href="/admin/dashboard" className="flex items-center gap-2.5 group">
              <div className="w-9 h-9 rounded-full border border-[#D99A24] bg-[#05111F] flex items-center justify-center shrink-0 shadow-sm transition-transform group-hover:scale-105">
                <Award className="w-4.5 h-4.5 text-[#D99A24]" />
              </div>
              <div className="leading-tight">
                <span className="text-[9px] font-bold tracking-[0.16em] uppercase text-[#CBD5E1] block">
                  INSTITUTE OF
                </span>
                <span className="text-[11px] font-extrabold tracking-wide uppercase text-white block">
                  HOTEL MANAGEMENT
                </span>
                <span className="text-[9px] font-bold tracking-[0.2em] uppercase text-[#D99A24] block">
                  KOLKATA
                </span>
              </div>
            </Link>

            <button
              onClick={() => setSidebarOpen(false)}
              className="lg:hidden p-1 text-slate-400 hover:text-white rounded cursor-pointer"
              aria-label="Close sidebar"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Navigation Links Scrollable List */}
          <div className="flex-1 overflow-y-auto min-h-0 px-2 py-2 space-y-0.5 text-sm [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden no-scrollbar pb-3">
            {/* Academic Portal Header Tag */}
            <div className="px-2.5 pt-1.5 pb-1 flex items-center justify-between">
              <span className="text-[10px] font-extrabold tracking-[0.2em] uppercase text-[#8FA3B8] font-sans">
                ACADEMIC PORTAL
              </span>
              <span className="inline-flex items-center px-1.5 py-0.2 rounded text-[9px] font-bold bg-[#133252] text-[#D99A24] border border-[#1d4773]">
                NCHMCT
              </span>
            </div>

            {adminNavigation.map((item) => {
              const Icon = item.icon;
              const hasSubmenus = item.submenus && item.submenus.length > 0;
              const isExpanded = openCategory === item.label;
              const isActive = item.label === activeCategoryLabel;

              return (
                <div key={item.label} className="space-y-0.5">
                  <div
                    className={cn(
                      "flex items-center justify-between rounded-lg transition-all group",
                      isActive
                        ? "bg-[#F4B400] text-[#081A2E] font-semibold shadow-xs"
                        : "text-[#F5F7FA] hover:bg-white/5 hover:text-white font-medium"
                    )}
                  >
                    <Link
                      href={item.href}
                      onClick={() => {
                        setOpenCategory(item.label);
                        if (!hasSubmenus) setSidebarOpen(false);
                      }}
                      className="flex items-center gap-2.5 px-2.5 py-1.5 flex-1 min-w-0"
                    >
                      <Icon
                        className={cn(
                          "w-4 h-4 shrink-0 transition-colors",
                          isActive
                            ? "text-[#081A2E]"
                            : "text-[#E2E8F0] group-hover:text-white"
                        )}
                      />
                      <span className="truncate text-[12.5px] font-sans">{item.label}</span>
                    </Link>

                    {hasSubmenus && (
                      <button
                        type="button"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleToggleCategory(item.label);
                        }}
                        className={cn(
                          "p-1.5 mr-1 transition-colors rounded cursor-pointer",
                          isActive
                            ? "text-[#081A2E] hover:bg-[#E0A400]/40"
                            : "text-[#8FA3B8] hover:text-white hover:bg-white/10"
                        )}
                        title={isExpanded ? "Collapse submenu" : "Expand submenu"}
                      >
                        <ChevronDown
                          className={cn(
                            "w-3.5 h-3.5 transition-transform duration-200",
                            isExpanded ? "rotate-0" : "-rotate-90"
                          )}
                        />
                      </button>
                    )}
                  </div>

                  {/* Collapsible Submenus List */}
                  {hasSubmenus && isExpanded && (
                    <div className="pl-2 pr-0.5 py-0.5 space-y-0.5 ml-2.5 my-0.5 font-sans border-l border-white/10 animate-in fade-in slide-in-from-top-1 duration-150">
                      {item.submenus?.map((sub) => {
                        const isSubActive = isActive && sub.title === activeSubmenuTitle;
                        const SubIcon = sub.icon;
                        return (
                          <Link
                            key={sub.title}
                            href={sub.href}
                            onClick={() => setSidebarOpen(false)}
                            className={cn(
                              "flex items-center gap-2 px-2.5 py-1.5 rounded-[6px] text-xs transition-colors truncate group",
                              isSubActive
                                ? "bg-[#17385A] text-white font-semibold shadow-xs"
                                : "text-[#8FA3B8] font-medium hover:text-[#F5F7FA] hover:bg-white/5"
                            )}
                          >
                            {SubIcon && (
                              <SubIcon
                                className={cn(
                                  "w-3.5 h-3.5 shrink-0 transition-colors",
                                  isSubActive
                                    ? "text-[#D99A24]"
                                    : "text-[#8FA3B8] group-hover:text-[#F5F7FA]"
                                )}
                              />
                            )}
                            <span className="truncate">{sub.title}</span>
                          </Link>
                        );
                      })}
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          {/* ============================================================ */}
          {/* BOTTOM SIDEBAR IHM KOLKATA ARCHITECTURAL BRANDING FOOTER    */}
          {/* ============================================================ */}
          <SidebarBuildingFooter />
        </aside>

        {/* ============================================================ */}
        {/* MAIN WORKSPACE AREA                                         */}
        {/* ============================================================ */}
        <div className="flex-1 flex flex-col min-w-0">
          {/* Topbar Header (Pure White, clean institutional elevation) */}
          <header className="h-16 border-b border-[#E5EAF0] bg-white flex items-center justify-between px-5 sticky top-0 z-30 shadow-2xs">
            {/* Left: Mobile Toggle & Global Omni-Search */}
            <div className="flex items-center gap-3 flex-1 max-w-lg">
              <button
                onClick={() => setSidebarOpen(true)}
                className="lg:hidden p-1.5 rounded-lg border border-[#E5EAF0] text-[#334155] hover:bg-slate-50 transition-colors cursor-pointer shrink-0"
                aria-label="Open sidebar"
              >
                <Menu className="w-5 h-5" />
              </button>

              <form onSubmit={handleSearchSubmit} className="relative w-full">
                <Search className="w-4 h-4 text-[#94A3B8] absolute left-3 top-1/2 -translate-y-1/2" />
                <input
                  type="text"
                  value={searchVal}
                  onChange={(e) => setSearchVal(e.target.value)}
                  placeholder="Search students, faculty, timetables, sessions..."
                  className="h-10 w-full rounded-lg border border-[#E1E8F0] bg-[#F8FAFC] pl-9 pr-12 text-xs sm:text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:bg-white focus:border-[#1769E8] focus:ring-2 focus:ring-[#1769E8]/20 focus:outline-none transition-all font-sans"
                />
                <div className="hidden sm:flex items-center gap-0.5 absolute right-2.5 top-1/2 -translate-y-1/2 px-1.5 py-0.5 rounded border border-[#E2E8F0] bg-white text-[10px] text-[#94A3B8] font-mono shadow-2xs">
                  <span>Ctrl</span>
                  <span>K</span>
                </div>
              </form>
            </div>

            {/* Right: Academic Status Badge, Notifications & Profile */}
            <div className="flex items-center gap-2 sm:gap-3.5">
              {/* Institutional Term Status Indicator */}
              <div className="hidden md:flex items-center gap-2 px-2.5 py-1 rounded-full bg-[#EFF6FF] border border-[#BFDBFE] text-xs font-semibold text-[#1E40AF]">
                <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                <span>Session 2026–2027</span>
                <span className="text-blue-300">•</span>
                <span className="text-[#3B82F6]">Autumn Term</span>
              </div>

              {/* Notification Popover */}
              <div className="relative" ref={notifRef}>
                <button
                  type="button"
                  onClick={() => setNotifOpen(!notifOpen)}
                  className="relative p-2 rounded-lg text-[#64748B] hover:text-[#0F172A] hover:bg-slate-100 transition-colors cursor-pointer"
                  title="Notifications"
                >
                  <Bell className="w-4 h-4 text-[#64748B]" />
                  <span className="absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-[#DC2626] text-white font-bold text-[9px] flex items-center justify-center ring-2 ring-white">
                    4
                  </span>
                </button>

                {/* Notifications Dropdown Card */}
                {notifOpen && (
                  <div className="absolute right-0 mt-2 w-80 bg-white rounded-xl border border-[#E5EAF0] shadow-xl p-3 z-50 animate-in fade-in zoom-in-95 duration-100 text-xs">
                    <div className="flex items-center justify-between pb-2 mb-2 border-b border-[#E5EAF0]">
                      <span className="font-heading font-bold text-xs text-[#071A4D]">
                        Institutional Alerts
                      </span>
                      <span className="text-[10px] font-semibold text-[#1769E8] cursor-pointer hover:underline">
                        Mark All Read
                      </span>
                    </div>
                    <div className="space-y-2">
                      <div className="p-2 rounded-lg bg-[#EFF6FF] border border-[#DBEAFE] text-[11px]">
                        <div className="font-bold text-[#1E40AF]">Faculty Schedule Updated</div>
                        <div className="text-slate-600 mt-0.5">Chef Rajesh Sharma schedule adjusted for BTK practicals.</div>
                      </div>
                      <div className="p-2 rounded-lg bg-amber-50 border border-amber-200 text-[11px]">
                        <div className="font-bold text-amber-800">Condonation Approvals Pending</div>
                        <div className="text-slate-600 mt-0.5">3 student medical requests require administrative signoff.</div>
                      </div>
                      <div className="p-2 rounded-lg bg-emerald-50 border border-emerald-200 text-[11px]">
                        <div className="font-bold text-emerald-800">Biometric Sync Complete</div>
                        <div className="text-slate-600 mt-0.5">Morning session logs synchronized with NCHMCT server.</div>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              {/* Settings Direct Shortcut */}
              <Link
                href="/admin/policies"
                className="p-2 rounded-lg text-[#64748B] hover:text-[#0F172A] hover:bg-slate-100 transition-colors"
                title="System Settings"
              >
                <Settings className="w-4 h-4 text-[#64748B]" />
              </Link>

              {/* User Profile Dropdown Pill */}
              <div className="relative" ref={userMenuRef}>
                <button
                  type="button"
                  onClick={() => setUserMenuOpen(!userMenuOpen)}
                  className="flex items-center gap-2 pl-2 sm:pl-3 border-l border-[#E5EAF0] cursor-pointer group"
                >
                  <div className="w-8 h-8 rounded-full overflow-hidden bg-[#081A2E] text-[#D99A24] font-bold text-xs flex items-center justify-center border border-[#D99A24] shadow-xs shrink-0 font-sans group-hover:ring-2 group-hover:ring-[#1769E8]/30 transition-all">
                    <span>
                      {user?.name
                        ? user.name
                          .split(" ")
                          .filter(Boolean)
                          .map((n) => n[0])
                          .slice(0, 2)
                          .join("")
                        : "SA"}
                    </span>
                  </div>
                  <div className="hidden sm:block text-left leading-tight font-sans">
                    <span className="text-xs font-bold text-[#071A4D] block group-hover:text-[#1769E8] transition-colors">
                      {user?.name || "Administrator"}
                    </span>
                    <span className="text-[10px] text-[#64748B] block font-medium">
                      {user?.role === "DEPARTMENT_ADMIN"
                        ? `Dept. Admin (${user?.department || "HOD"})`
                        : user?.role === "ACADEMIC_ADMIN"
                          ? "Academic Administrator"
                          : "Super Administrator"}
                    </span>
                  </div>
                  <ChevronDown className="w-3 h-3 text-[#94A3B8] hidden sm:block" />
                </button>

                {/* Profile Dropdown Menu */}
                {userMenuOpen && (
                  <div className="absolute right-0 mt-2 w-56 bg-white rounded-xl border border-[#E5EAF0] shadow-xl p-2 z-50 animate-in fade-in zoom-in-95 duration-100 text-xs">
                    <div className="p-2 border-b border-[#E5EAF0] mb-1">
                      <div className="font-bold text-[#071A4D]">{user?.name || "Administrator"}</div>
                      <div className="text-[11px] text-[#64748B]">{user?.email || ""}</div>
                    </div>
                    <Link
                      href="/admin/people/faculty/accounts"
                      onClick={() => setUserMenuOpen(false)}
                      className="flex items-center gap-2 px-2.5 py-2 rounded-lg text-[#334155] hover:bg-slate-50 font-medium transition-colors"
                    >
                      <UserCheck className="w-3.5 h-3.5 text-[#1769E8]" />
                      <span>Security &amp; Accounts</span>
                    </Link>
                    <Link
                      href="/admin/settings/institution"
                      onClick={() => setUserMenuOpen(false)}
                      className="flex items-center gap-2 px-2.5 py-2 rounded-lg text-[#334155] hover:bg-slate-50 font-medium transition-colors"
                    >
                      <Building2 className="w-3.5 h-3.5 text-[#1769E8]" />
                      <span>Institution Profile</span>
                    </Link>
                    <Link
                      href="/admin/audit-logs"
                      onClick={() => setUserMenuOpen(false)}
                      className="flex items-center gap-2 px-2.5 py-2 rounded-lg text-[#334155] hover:bg-slate-50 font-medium transition-colors"
                    >
                      <ScrollText className="w-3.5 h-3.5 text-[#1769E8]" />
                      <span>Activity Logs</span>
                    </Link>
                    <div className="border-t border-[#E5EAF0] my-1" />
                    <button
                      onClick={() => {
                        setUserMenuOpen(false);
                        logout();
                      }}
                      className="w-full flex items-center gap-2 px-2.5 py-2 rounded-lg text-rose-600 hover:bg-rose-50 font-semibold transition-colors cursor-pointer text-left"
                    >
                      <LogOut className="w-3.5 h-3.5" />
                      <span>Sign Out</span>
                    </button>
                  </div>
                )}
              </div>
            </div>
          </header>

          {/* Main Content Viewport */}
          <main className="flex-1 p-3 sm:p-5 lg:p-6 xl:p-8 max-w-[1600px] w-full mx-auto">
            {children}
          </main>
        </div>
      </div>
    </RouteGuard>
  );
}
