'use client';

import React, { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import {
  LayoutDashboard,
  Award,
  User,
  CheckSquare,
  BarChart3,
  FilePieChart,
  Building2,
  Megaphone,
  Settings,
  LogOut,
  Menu,
  X,
  Trophy,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  Search,
  CornerDownLeft
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { TSessionUser } from '@/types/auth';

interface AppShellProps {
  children: React.ReactNode;
}

export function AppShell({ children }: AppShellProps) {
  const pathname = usePathname();
  const router = useRouter();
  const [user, setUser] = useState<TSessionUser | null>(null);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [isProfileOpen, setIsProfileOpen] = useState(false);
  const [isDesktopMinimized, setIsDesktopMinimized] = useState(false);
  const [openMenus, setOpenMenus] = useState<Record<string, boolean>>({
    'Prestasi': true,
  });

  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchIndex, setSearchIndex] = useState(0);
  const [isSearchFocused, setIsSearchFocused] = useState(false);
  const searchInputRef = useRef<HTMLInputElement>(null);
  const [isLogoutOpen, setIsLogoutOpen] = useState(false);

  const searchItems = [
    { name: 'Dashboard', href: '/dashboard/admin', category: 'Navigasi' },
    { name: 'Kejuaraan', href: '/dashboard/admin/kejuaraan', category: 'Navigasi' },
    { name: 'Institusi', href: '/dashboard/admin/institusi', category: 'Navigasi' },
    { name: 'Prestasi Belmawa', href: '/dashboard/mahasiswa/belmawa', category: 'Prestasi' },
    { name: 'Prestasi Mandiri', href: '/dashboard/mahasiswa/prestasi-mandiri', category: 'Prestasi' },
    { name: 'Rekognisi', href: '/dashboard/mahasiswa/rekognisi', category: 'Prestasi' },
    { name: 'Sertifikasi', href: '/dashboard/mahasiswa/sertifikasi', category: 'Prestasi' },
    { name: 'Ekspor Laporan', href: '/dashboard/operator/laporan', category: 'Laporan' },
    { name: 'Profil Akun', href: '/dashboard/profil', category: 'Akun' },
  ];

  const filteredSearchItems = searchItems.filter(item =>
    item.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    item.category.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const toggleMenu = (name: string) => {
    setOpenMenus((prev) => ({ ...prev, [name]: !prev[name] }));
  };

  useEffect(() => {
    setSearchIndex(0);
  }, [searchQuery]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        if (typeof window !== 'undefined' && window.innerWidth >= 768) {
          searchInputRef.current?.focus();
          setIsSearchFocused(true);
        } else {
          setIsSearchOpen(prev => !prev);
        }
      }
      if (e.key === '/') {
        if (
          document.activeElement?.tagName !== 'INPUT' &&
          document.activeElement?.tagName !== 'TEXTAREA'
        ) {
          e.preventDefault();
          if (typeof window !== 'undefined' && window.innerWidth >= 768) {
            searchInputRef.current?.focus();
            setIsSearchFocused(true);
          } else {
            setIsSearchOpen(true);
          }
        }
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  const handleSearchKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setSearchIndex(prev => (prev + 1) % Math.max(1, filteredSearchItems.length));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setSearchIndex(prev => (prev - 1 + filteredSearchItems.length) % Math.max(1, filteredSearchItems.length));
    } else if (e.key === 'Enter') {
      e.preventDefault();
      if (filteredSearchItems[searchIndex]) {
        router.push(filteredSearchItems[searchIndex].href);
        setIsSearchFocused(false);
        setIsSearchOpen(false);
        setSearchQuery('');
      }
    } else if (e.key === 'Escape') {
      e.preventDefault();
      setIsSearchFocused(false);
      setIsSearchOpen(false);
      setSearchQuery('');
      searchInputRef.current?.blur();
    }
  };

  useEffect(() => {
    // Read session from cookie
    const getCookie = (name: string) => {
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      if (parts.length === 2) {
        return parts.pop()?.split(';').shift();
      }
      return undefined;
    };

    const userCookie = getCookie('simkatmawa_user');
    if (userCookie) {
      try {
        setUser(JSON.parse(decodeURIComponent(userCookie)) as TSessionUser);
      } catch (e) {
        setUser(null);
      }
    }
  }, []);

  useEffect(() => {
    // Determine page title based on current pathname
    let pageTitle = 'Dashboard';

    if (pathname === '/dashboard/admin' || pathname === '/dashboard/mahasiswa' || pathname === '/dashboard/operator') {
      pageTitle = 'Dashboard';
    } else if (pathname.startsWith('/dashboard/admin/kejuaraan')) {
      pageTitle = 'Kejuaraan';
    } else if (pathname.startsWith('/dashboard/admin/institusi')) {
      pageTitle = 'Institusi';
    } else if (pathname.startsWith('/dashboard/mahasiswa/belmawa')) {
      pageTitle = 'Prestasi Belmawa';
    } else if (pathname.startsWith('/dashboard/mahasiswa/prestasi-mandiri')) {
      pageTitle = 'Prestasi Mandiri';
    } else if (pathname.startsWith('/dashboard/mahasiswa/rekognisi')) {
      pageTitle = 'Rekognisi';
    } else if (pathname.startsWith('/dashboard/mahasiswa/sertifikasi')) {
      pageTitle = 'Sertifikasi';
    } else if (pathname.startsWith('/dashboard/operator/laporan')) {
      pageTitle = 'Ekspor Laporan';
    } else if (pathname.startsWith('/dashboard/profil')) {
      pageTitle = 'Profil Saya';
    }

    document.title = `${pageTitle} | SIMKATMAWA`;
  }, [pathname]);

  const handleLogout = () => {
    // Clear cookie and redirect
    document.cookie = 'simkatmawa_user=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
    router.push('/login');
    router.refresh();
  };

  const getNavigation = () => {
    if (!user) return [];

    if (user.role === 'admin_pusat') {
      return [
        { name: 'Dashboard', href: '/dashboard/admin', icon: LayoutDashboard },
        { name: 'Kejuaraan', href: '/dashboard/admin/kejuaraan', icon: Trophy },
        {
          name: 'Prestasi',
          icon: Award,
          submenu: [
            { name: 'Prestasi Belmawa', href: '/dashboard/mahasiswa/belmawa' },
            { name: 'Prestasi Mandiri', href: '/dashboard/mahasiswa/prestasi-mandiri' },
            { name: 'Rekognisi', href: '/dashboard/mahasiswa/rekognisi' },
            { name: 'Sertifikasi', href: '/dashboard/mahasiswa/sertifikasi' },
          ],
        },
        { name: 'Institusi', href: '/dashboard/admin/institusi', icon: Building2 },
        { name: 'Ekspor Laporan', href: '/dashboard/operator/laporan', icon: FilePieChart },
        { name: 'Profil Akun', href: '/dashboard/profil', icon: User },
      ];
    }
    return [];
  };

  const navigation = getNavigation();
  const displayUserName = user?.name === 'Admin Pusat Kemdiktisaintek' ? 'Admin Pusat' : user?.name || '';

  return (
    <div className="h-screen bg-surface flex flex-col md:flex-row overflow-hidden">
      {/* Mobile Top Bar */}
      <header className="md:hidden bg-card border-b border-text-muted/10 h-16 px-4 flex items-center justify-between sticky top-0 z-40 shadow-sm">
        <div className="flex items-center gap-2">
          <img src="/images/logo_umj.webp" alt="Logo UMJ" className="h-8 w-8 object-contain flex-shrink-0" />
          <span className="font-bold text-text-primary text-sm tracking-wide">SIMKATMAWA</span>
        </div>

        <div className="flex items-center gap-2">
          <button
            type="button"
            title="Cari Halaman"
            onClick={() => setIsSearchOpen(true)}
            className="p-2 rounded-lg text-text-muted hover:bg-surface transition-colors"
          >
            <Search className="h-5 w-5" />
          </button>
          <button
            type="button"
            className="p-2 rounded-lg text-text-muted hover:bg-surface transition-colors"
            onClick={() => setIsSidebarOpen(!isSidebarOpen)}
          >
            {isSidebarOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
          </button>
        </div>
      </header>

      {/* Mobile Sidebar Overlay */}
      {isSidebarOpen && (
        <div
          className="fixed inset-0 z-40 bg-text-primary/45 backdrop-blur-md md:hidden"
          onClick={() => setIsSidebarOpen(false)}
        />
      )}

      {/* Sidebar (Desktop and Mobile drawer) */}
      <aside
        className={cn(
          "fixed md:sticky top-0 z-50 md:z-30 h-screen bg-[#0F172A] text-white flex flex-col justify-between transition-all duration-300 shadow-2xl md:shadow-none border-r border-white/5 relative",
          isSidebarOpen ? "translate-x-0 w-64" : "-translate-x-full md:translate-x-0",
          isDesktopMinimized ? "md:w-20" : "md:w-64"
        )}
      >
        {/* Floating Expand Button for Desktop */}
        <button
          type="button"
          onClick={() => setIsDesktopMinimized(false)}
          className={cn(
            "hidden md:flex absolute top-[32px] -right-3 z-50 h-6 w-6 -translate-y-1/2 items-center justify-center rounded-full border border-slate-200 bg-white text-slate-600 hover:text-slate-800 shadow-md transition-all duration-300 focus:outline-none",
            isDesktopMinimized
              ? "opacity-100 scale-100 pointer-events-auto"
              : "opacity-0 scale-90 pointer-events-none"
          )}
          title="Expand Sidebar"
        >
          <ChevronRight className="h-4 w-4 text-slate-700" />
        </button>

        <div>
          {/* Brand/Logo */}
          <div className={cn("h-16 flex items-center border-b border-white/10 transition-all duration-300", isDesktopMinimized ? "justify-center px-0" : "justify-between px-4")}>
            <Link href="/" className={cn("flex items-center overflow-hidden transition-all duration-300", isDesktopMinimized ? "gap-0" : "gap-3")}>
              <img src="/images/logo_umj.webp" alt="Logo UMJ" className="h-8 w-8 object-contain flex-shrink-0 transition-transform duration-300" />
              <div className={cn("flex flex-col transition-all duration-300 origin-left", isDesktopMinimized ? "w-0 opacity-0 pointer-events-none scale-95" : "w-auto opacity-100 scale-100")}>
                <span className="font-semibold tracking-wide text-sm leading-none whitespace-nowrap text-white">SIMKATMAWA</span>
                <span className="text-[10px] text-slate-400 font-medium mt-1 whitespace-nowrap">Unmuh Jember</span>
              </div>
            </Link>

            {/* Hamburger menu for desktop, close button for mobile */}
            <button
              type="button"
              className={cn(
                "p-1.5 rounded-lg hover:bg-white/10 transition-all duration-300 text-white/70 hover:text-white flex-shrink-0",
                isDesktopMinimized ? "w-0 h-0 p-0 opacity-0 pointer-events-none overflow-hidden" : "w-auto h-auto opacity-100"
              )}
              onClick={() => {
                if (typeof window !== 'undefined' && window.innerWidth >= 768) {
                  setIsDesktopMinimized(true);
                } else {
                  setIsSidebarOpen(false);
                }
              }}
              title="Collapse Sidebar"
            >
              <Menu className="hidden md:block h-5 w-5" />
              <X className="block md:hidden h-5 w-5" />
            </button>
          </div>

          {/* Navigation Links */}
          <nav className="mt-6 px-3 space-y-1.5">
            {navigation.map((item) => {
              const hasSubmenu = !!item.submenu;
              const isMenuOpen = openMenus[item.name];
              const isActive = hasSubmenu
                ? item.submenu?.some(sub => pathname === sub.href || pathname.startsWith(sub.href + '/'))
                : item.name === 'Dashboard'
                  ? pathname === item.href
                  : item.href && (pathname === item.href || pathname.startsWith(item.href + '/'));
              const Icon = item.icon;

              if (hasSubmenu) {
                return (
                  <div key={item.name} className="space-y-1">
                    <button
                      onClick={() => toggleMenu(item.name)}
                      className={cn(
                        "transition-colors duration-150 flex items-center relative focus:outline-none focus:ring-0 focus-visible:ring-0 focus-visible:outline-none text-sm rounded-xl h-11 select-none",
                        isActive
                          ? "bg-white/10 text-white font-medium active:bg-white/10"
                          : "text-slate-400 hover:text-white hover:bg-white/5 font-normal active:bg-white/5",
                        isDesktopMinimized ? "w-11 mx-auto justify-center px-0" : "w-full justify-start px-3 gap-3"
                      )}
                      title={isDesktopMinimized ? item.name : undefined}
                    >
                      <Icon className={cn("h-5 w-5 flex-shrink-0 transition-colors", isActive ? "text-white" : "text-slate-400 group-hover:text-white")} />
                      <span className={cn("transition-all duration-300 whitespace-nowrap overflow-hidden text-left flex-1", isDesktopMinimized ? "w-0 h-0 opacity-0 scale-95 pointer-events-none absolute" : "w-auto h-auto opacity-100 scale-100 relative")}>
                        {item.name}
                      </span>
                      <ChevronDown className={cn("text-slate-400 transition-all duration-300", isMenuOpen && "transform rotate-180", isDesktopMinimized ? "w-0 h-0 opacity-0 scale-95 pointer-events-none absolute" : "h-4 w-4 opacity-100 scale-100 relative")} />
                    </button>

                    <div className={cn(
                      "pl-6 pr-2 space-y-1 transition-all duration-300 overflow-hidden",
                      isMenuOpen && !isDesktopMinimized ? "max-h-40 opacity-100 mt-1" : "max-h-0 opacity-0 pointer-events-none"
                    )}>
                      {item.submenu?.map((sub) => {
                        const isSubActive = pathname === sub.href || pathname.startsWith(sub.href + '/');
                        return (
                          <Link
                            key={sub.name}
                            href={sub.href}
                            onClick={() => setIsSidebarOpen(false)}
                            className={cn(
                              "flex items-center py-2 px-3 rounded-lg text-xs transition-colors duration-150 relative focus:outline-none focus:ring-0 focus-visible:ring-0 focus-visible:outline-none select-none",
                              isSubActive
                                ? "text-white font-semibold active:text-white"
                                : "text-slate-400 hover:text-white hover:bg-white/5 font-normal active:bg-white/5"
                            )}
                          >
                            <span className="text-slate-500 mr-2 font-bold">•</span>
                            <span className="truncate">{sub.name}</span>
                          </Link>
                        );
                      })}
                    </div>
                  </div>
                );
              }

              return (
                <Link
                  key={item.name}
                  href={item.href || '#'}
                  title={isDesktopMinimized ? item.name : undefined}
                  onClick={() => setIsSidebarOpen(false)}
                  className={cn(
                    "transition-colors duration-150 flex items-center relative focus:outline-none focus:ring-0 focus-visible:ring-0 focus-visible:outline-none text-sm rounded-xl h-11 select-none",
                    isActive
                      ? "bg-white/10 text-white font-medium active:bg-white/10"
                      : "text-slate-400 hover:text-white hover:bg-white/5 font-normal active:bg-white/5",
                    isDesktopMinimized ? "w-11 mx-auto justify-center px-0" : "w-full justify-start px-3 gap-3"
                  )}
                >
                  <Icon className={cn("h-5 w-5 flex-shrink-0 transition-colors", isActive ? "text-white" : "text-slate-400 group-hover:text-white")} />
                  <span className={cn("transition-all duration-300 whitespace-nowrap overflow-hidden", isDesktopMinimized ? "w-0 h-0 opacity-0 scale-95 pointer-events-none absolute" : "w-auto h-auto opacity-100 scale-100 relative")}>
                    {item.name}
                  </span>
                </Link>
              );
            })}
          </nav>
        </div>

        {/* User profile footer */}
        {user && (
          <div className="border-t border-white/5 p-4 transition-all duration-300">
            <button
              onClick={() => setIsLogoutOpen(true)}
              className={cn(
                "flex items-center transition-all duration-300 group relative focus:outline-none focus:ring-0 focus-visible:ring-0 focus-visible:outline-none text-sm font-semibold h-11 rounded-xl",
                "bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 hover:border-red-500/40 hover:text-red-300",
                isDesktopMinimized ? "w-11 mx-auto justify-center px-0" : "w-full justify-start px-3 gap-3"
              )}
              title="Log Out"
            >
              <LogOut className="h-4 w-4 flex-shrink-0" />
              <span className={cn("transition-all duration-300 whitespace-nowrap overflow-hidden font-medium", isDesktopMinimized ? "w-0 h-0 opacity-0 scale-95 pointer-events-none absolute" : "w-auto h-auto opacity-100 scale-100 relative")}>
                Log Out
              </span>
            </button>
          </div>
        )}
      </aside>

      {/* Main Content Area */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* Top Header Bar for Desktop */}
        <header className="hidden md:flex bg-card border-b border-text-muted/10 h-16 px-8 items-center justify-between sticky top-0 z-20 shadow-sm transition-all duration-300">
          <div className="flex items-center gap-4">
            <span className="text-xs font-semibold text-text-muted uppercase tracking-wider">
              Sistem Informasi Kinerja & Tata Kelola Kemahasiswaan
            </span>
          </div>

          <div className="flex items-center gap-6">
            {/* Desktop Search Input */}
            <div className="relative flex items-center z-50">
              <div className="flex items-center gap-2 px-3 py-1.5 bg-surface hover:bg-surface/80 rounded-xl border border-text-muted/10 transition-colors focus-within:ring-1 focus-within:ring-primary/30 w-64 md:w-80 lg:w-[400px]">
                <Search className="h-4 w-4 text-text-muted flex-shrink-0" />
                <input
                  ref={searchInputRef}
                  type="text"
                  value={searchQuery}
                  onChange={(e) => {
                    setSearchQuery(e.target.value);
                    setIsSearchFocused(true);
                  }}
                  onFocus={() => setIsSearchFocused(true)}
                  onKeyDown={handleSearchKeyDown}
                  placeholder="Cari halaman..."
                  className="w-full bg-transparent text-xs text-text-primary placeholder-text-muted outline-none"
                />
              </div>

              {/* Search Results Dropdown */}
              {isSearchFocused && (
                <>
                  <div className="fixed inset-0 z-40" onClick={() => setIsSearchFocused(false)} />
                  <div className="absolute top-full mt-2 right-0 w-full bg-card border border-text-muted/10 rounded-xl shadow-2xl z-50 overflow-hidden flex flex-col max-h-[300px] animate-in fade-in slide-in-from-top-2 duration-200">
                    <div className="overflow-y-auto p-2 space-y-0.5">
                      {filteredSearchItems.length > 0 ? (
                        filteredSearchItems.map((item, idx) => {
                          const isHighlighted = idx === searchIndex;
                          return (
                            <div
                              key={item.name}
                              onMouseDown={() => {
                                router.push(item.href);
                                setIsSearchFocused(false);
                                setSearchQuery('');
                              }}
                              onMouseEnter={() => setSearchIndex(idx)}
                              className={cn(
                                "flex items-center justify-between px-3 py-2 rounded-lg cursor-pointer transition-colors text-xs",
                                isHighlighted
                                  ? "bg-primary/10 text-primary font-medium"
                                  : "text-text-primary hover:bg-surface"
                              )}
                            >
                              <div className="flex items-center gap-2">
                                <span className="text-[9px] uppercase font-semibold tracking-wider text-text-muted/60 bg-text-muted/5 border border-text-muted/10 px-1 py-0.5 rounded">
                                  {item.category}
                                </span>
                                <span>{item.name}</span>
                              </div>
                              {isHighlighted && (
                                <CornerDownLeft className="h-3 w-3 text-primary/70" />
                              )}
                            </div>
                          );
                        })
                      ) : (
                        <div className="flex flex-col items-center justify-center py-6 px-4 text-center text-text-muted">
                          <Search className="h-6 w-6 mb-1 opacity-30" />
                          <p className="text-xs font-medium">Halaman tidak ditemukan</p>
                        </div>
                      )}
                    </div>
                  </div>
                </>
              )}
            </div>

            {user && (
              <div className="relative">
                <button
                  onClick={() => setIsProfileOpen(!isProfileOpen)}
                  className="flex items-center gap-3 text-left focus:outline-none"
                >
                  <div className="h-9 w-9 rounded-full bg-primary/10 text-primary flex items-center justify-center font-bold">
                    {displayUserName.charAt(0).toUpperCase()}
                  </div>
                  <div className="hidden lg:flex flex-col">
                    <span className="text-sm font-semibold text-text-primary leading-none">{displayUserName}</span>
                    <span className="text-[11px] text-text-muted mt-0.5 capitalize">
                      {user.role.replace('_', ' ')}
                    </span>
                  </div>
                </button>

                {isProfileOpen && (
                  <>
                    <div
                      className="fixed inset-0 z-40"
                      onClick={() => setIsProfileOpen(false)}
                    />
                    <div className="absolute right-0 mt-2 w-56 rounded-2xl bg-card border border-text-muted/10 shadow-xl py-2 z-50">
                      <div className="px-4 py-2 border-b border-text-muted/10">
                        <p className="text-sm font-semibold text-text-primary">{displayUserName}</p>
                        <p className="text-xs text-text-muted truncate">{user.email}</p>
                      </div>
                      <Link
                        href="/dashboard/profil"
                        onClick={() => setIsProfileOpen(false)}
                        className="block px-4 py-2.5 text-sm text-text-primary hover:bg-surface transition-colors"
                      >
                        Profil Saya
                      </Link>
                      <button
                        onClick={() => {
                          setIsProfileOpen(false);
                          setIsLogoutOpen(true);
                        }}
                        className="w-full text-left px-4 py-2.5 text-sm text-danger hover:bg-danger/5 transition-colors border-t border-text-muted/10"
                      >
                        Keluar Aplikasi
                      </button>
                    </div>
                  </>
                )}
              </div>
            )}
          </div>
        </header>

        {/* Content Body */}
        <main className="flex-1 overflow-y-auto p-4 pb-24 md:p-8 bg-surface">
          {children}
        </main>
      </div>

      {/* Mobile Bottom Navigation Bar */}
      <div className="md:hidden fixed bottom-0 left-0 right-0 bg-card border-t border-text-muted/10 h-16 flex items-center justify-around z-30 shadow-lg px-2">
        {navigation.map((item) => {
          const itemHref = item.href || (item.submenu && item.submenu[0]?.href) || '#';
          const isActive = item.submenu
            ? item.submenu.some(sub => pathname === sub.href || pathname.startsWith(sub.href + '/'))
            : item.name === 'Dashboard'
              ? pathname === item.href
              : item.href && (pathname === item.href || pathname.startsWith(item.href + '/'));
          const Icon = item.icon;
          return (
            <Link
              key={item.name}
              href={itemHref}
              className={cn(
                "flex flex-col items-center justify-center w-16 h-12 rounded-xl text-center gap-1 transition-all duration-200",
                isActive ? "text-primary font-semibold" : "text-text-muted"
              )}
            >
              <Icon className="h-5 w-5" />
              <span className="text-[10px] truncate max-w-full">{item.name}</span>
            </Link>
          );
        })}
      </div>

      {/* Global Search Dialog Modal */}
      {isSearchOpen && (
        <div className="fixed inset-0 z-50 flex items-start justify-center bg-slate-950/60 backdrop-blur-md pt-[15vh] px-4">
          {/* Backdrop click close */}
          <div className="fixed inset-0" onClick={() => { setIsSearchOpen(false); setSearchQuery(''); }} />

          <div className="bg-card border border-text-muted/10 w-full max-w-lg rounded-2xl shadow-2xl overflow-hidden relative z-10 flex flex-col max-h-[50vh] animate-in fade-in zoom-in-95 duration-200">
            {/* Search Input Header */}
            <div className="flex items-center px-4 py-3 border-b border-text-muted/10 gap-3">
              <Search className="h-5 w-5 text-text-muted flex-shrink-0" />
              <input
                autoFocus
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyDown={handleSearchKeyDown}
                placeholder="Ketik nama halaman atau kategori..."
                className="w-full bg-transparent text-text-primary placeholder-text-muted outline-none text-sm"
              />
              <span className="text-[10px] text-text-muted border border-text-muted/20 px-1.5 py-0.5 rounded">ESC</span>
            </div>

            {/* Search Results */}
            <div className="flex-1 overflow-y-auto p-2 space-y-1">
              {filteredSearchItems.length > 0 ? (
                filteredSearchItems.map((item, idx) => {
                  const isHighlighted = idx === searchIndex;
                  return (
                    <div
                      key={item.name}
                      onClick={() => {
                        router.push(item.href);
                        setIsSearchOpen(false);
                        setSearchQuery('');
                      }}
                      onMouseEnter={() => setSearchIndex(idx)}
                      className={cn(
                        "flex items-center justify-between px-3 py-2.5 rounded-xl cursor-pointer transition-colors text-sm",
                        isHighlighted
                          ? "bg-primary/10 text-primary font-medium"
                          : "text-text-primary hover:bg-surface"
                      )}
                    >
                      <div className="flex items-center gap-3">
                        <span className="text-[10px] uppercase font-semibold tracking-wider text-text-muted/60 bg-text-muted/5 border border-text-muted/10 px-1.5 py-0.5 rounded">
                          {item.category}
                        </span>
                        <span>{item.name}</span>
                      </div>
                      {isHighlighted && (
                        <div className="flex items-center gap-1 text-xs text-primary/70">
                          <span>Buka</span>
                          <CornerDownLeft className="h-3 w-3" />
                        </div>
                      )}
                    </div>
                  );
                })
              ) : (
                <div className="flex flex-col items-center justify-center py-10 px-4 text-center text-text-muted">
                  <Search className="h-8 w-8 mb-2 opacity-30" />
                  <p className="text-sm font-medium">Halaman tidak ditemukan</p>
                  <p className="text-xs mt-0.5">Coba gunakan kata kunci lainnya.</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Logout Confirmation Modal */}
      {isLogoutOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 animate-in fade-in duration-300">
          {/* Glassmorphism Backdrop */}
          <div
            className="fixed inset-0 bg-slate-950/65 backdrop-blur-md transition-opacity duration-300"
            onClick={() => setIsLogoutOpen(false)}
          />

          {/* Dialog Content Box */}
          <div className="bg-card border border-text-muted/10 w-full max-w-md rounded-2xl shadow-2xl relative z-10 overflow-hidden transform scale-100 transition-all duration-300 animate-in zoom-in-95">
            <div className="p-6 text-center space-y-6">
              {/* Glowing Red Icon Area */}
              <div className="mx-auto w-14 h-14 rounded-full bg-danger/10 border border-danger/25 flex items-center justify-center text-danger shadow-inner">
                <LogOut className="h-6 w-6 animate-pulse" />
              </div>

              {/* Text Information */}
              <div className="space-y-2">
                <h3 className="text-xl font-bold text-text-primary">
                  Keluar dari Simkatmawa?
                </h3>
                <p className="text-sm text-text-muted leading-relaxed px-2">
                  Apakah Anda yakin ingin keluar? Sesi Anda akan berakhir dan Anda harus masuk kembali untuk mengelola data prestasi kemahasiswaan.
                </p>
              </div>

              {/* Action Buttons */}
              <div className="flex items-center justify-center gap-3 pt-2">
                <button
                  type="button"
                  onClick={() => setIsLogoutOpen(false)}
                  className="w-full py-2.5 px-4 border border-text-muted/10 text-text-primary bg-card hover:bg-surface rounded-xl text-sm font-semibold transition-all hover:scale-[1.02]"
                >
                  Batal
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setIsLogoutOpen(false);
                    handleLogout();
                  }}
                  className="w-full py-2.5 px-4 text-white bg-gradient-to-r from-red-600 to-red-500 hover:from-red-500 hover:to-red-400 rounded-xl text-sm font-semibold shadow-lg shadow-red-500/20 transition-all hover:scale-[1.02]"
                >
                  Ya, Keluar
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
