"use client";

import { useEffect, useRef, useState, type UIEvent } from "react";
import { createPortal } from "react-dom";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  AlertCircle,
  ArrowDownLeft,
  ArrowUpRight,
  Bell,
  Building2,
  CheckCircle2,
  ChevronDown,
  FileText,
  Info,
  LayoutDashboard,
  Lock,
  LogOut,
  Menu,
  Receipt,
  Search,
  Send,
  ShieldCheck,
  TrendingUp,
  UserCheck,
  UserCircle,
  Users,
  X,
} from "lucide-react";
import { Container } from "@/components/common/Container";
import { LogoutConfirmModal } from "@/components/app/LogoutConfirmModal";
import { ThemeToggle } from "@/components/theme/ThemeToggle";
import { LanguageDropdown } from "@/components/i18n/LanguageDropdown";
import { useAgentAuth } from "@/hooks/useAgentAuth";
import { useTranslation } from "@/hooks/useTranslation";
import { useAgentNotifications } from "@/hooks/queries/useAgentNotifications";
import { useAgentNotificationState, notifKey } from "@/hooks/useAgentNotificationState";
import { cn } from "@/lib/utils";

// Mirrors the /agent/notifications page so a notification wears the same icon
// and color in the header drawer as it does on the full page.
function getNotificationStyles(message: string) {
  const m = message.toLowerCase();
  if (m.includes("money in"))
    return { icon: ArrowDownLeft, colorClass: "bg-emerald-50 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400", dotClass: "bg-emerald-500" };
  if (m.includes("money out") || m.includes("send remittance"))
    return { icon: ArrowUpRight, colorClass: "bg-brand-50 text-brand-600 dark:bg-brand-500/10 dark:text-brand-400", dotClass: "bg-brand-500" };
  if (m.includes("success"))
    return { icon: CheckCircle2, colorClass: "bg-emerald-50 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400", dotClass: "bg-emerald-500" };
  if (m.includes("fail") || m.includes("error") || m.includes("cancel"))
    return { icon: AlertCircle, colorClass: "bg-rose-50 text-rose-600 dark:bg-rose-500/10 dark:text-rose-400", dotClass: "bg-rose-500" };
  return { icon: Info, colorClass: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400", dotClass: "bg-slate-400" };
}

const AGENT_NAV_ROUTES = [
  { href: "/agent/dashboard", labelKey: "agent.sidebar.dashboard", fallback: "Dashboard", icon: LayoutDashboard },
  { href: "/agent/send-remittance", labelKey: "agent.sidebar.sendRemittance", fallback: "Send Remittance", icon: Send },
  { href: "/agent/my-recipients", labelKey: "agent.sidebar.myRecipients", fallback: "My Recipients", icon: UserCheck },
  { href: "/agent/my-senders", labelKey: "agent.sidebar.mySenders", fallback: "My Senders", icon: Users },
  { href: "/agent/money-in", labelKey: "agent.sidebar.moneyIn", fallback: "Money In", icon: ArrowDownLeft },
  { href: "/agent/money-out", labelKey: "agent.sidebar.moneyOut", fallback: "Money Out", icon: ArrowUpRight },
  { href: "/agent/transactions", labelKey: "agent.sidebar.transactions", fallback: "Transactions", icon: Receipt },
  { href: "/agent/statements", labelKey: "agent.sidebar.statements", fallback: "Statements", icon: FileText },
  { href: "/agent/profit-log", labelKey: "agent.sidebar.profitLog", fallback: "Profit Log", icon: TrendingUp },
  { href: "/agent/notifications", labelKey: "agent.sidebar.notifications", fallback: "Notifications", icon: Bell },
  { href: "/agent/profile", labelKey: "agent.sidebar.profile", fallback: "Profile", icon: UserCircle },
  { href: "/agent/security", labelKey: "agent.sidebar.security", fallback: "Security Settings", icon: Lock },
  { href: "/agent/kyc", labelKey: "agent.sidebar.kyc", fallback: "KYC Verification", icon: ShieldCheck },
];

interface Props {
  sidebarOpen: boolean;
  onMenuClick: () => void;
}

export function AgentHeader({ sidebarOpen, onMenuClick }: Props) {
  const { user, signOut } = useAgentAuth();
  const { t } = useTranslation();
  const { data: notifData, isLoading: notifLoading } = useAgentNotifications();
  const { markRead, markAllRead, markAllUnread, isRead } = useAgentNotificationState();
  const router = useRouter();

  const [userOpen, setUserOpen] = useState(false);
  const [logoutOpen, setLogoutOpen] = useState(false);
  const userRef = useRef<HTMLDivElement>(null);

  const [notifOpen, setNotifOpen] = useState(false);
  const notifRef = useRef<HTMLDivElement>(null);
  const notifDesktopRef = useRef<HTMLDivElement>(null);
  const notifMobileRef = useRef<HTMLDivElement>(null);

  const NOTIF_PAGE_SIZE = 8;
  const [visibleCount, setVisibleCount] = useState(NOTIF_PAGE_SIZE);
  // Mobile-only list filter. Desktop dropdown never mutates it, so it stays
  // "all" there and the filter is a mobile-drawer affordance only.
  const [notifFilter, setNotifFilter] = useState<"all" | "unread" | "read">("all");

  const [searchQuery, setSearchQuery] = useState("");
  const [searchOpenDesktop, setSearchOpenDesktop] = useState(false);
  const [searchOpenMobile, setSearchOpenMobile] = useState(false);
  const searchDesktopRef = useRef<HTMLDivElement>(null);
  const mobileSearchInputRef = useRef<HTMLInputElement>(null);

  const filteredRoutes = AGENT_NAV_ROUTES.filter((r) => {
    const label = t(r.labelKey) || r.fallback;
    return (
      label.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.href.toLowerCase().includes(searchQuery.toLowerCase())
    );
  });

  const initials = user
    ? `${user.firstName.charAt(0)}${user.lastName.charAt(0)}`.toUpperCase() || user.email.charAt(0).toUpperCase()
    : "A";

  useEffect(() => {
    function onOutside(e: MouseEvent) {
      const target = e.target as Node;
      if (userRef.current && !userRef.current.contains(target)) setUserOpen(false);
      if (searchDesktopRef.current && !searchDesktopRef.current.contains(target)) setSearchOpenDesktop(false);
      // Mobile: the notification drawer is a full-screen modal — only its own
      // close (X) button dismisses it, not an outside tap.
      if (window.matchMedia("(max-width: 1023px)").matches) return;
      if (
        notifRef.current && !notifRef.current.contains(target) &&
        !notifDesktopRef.current?.contains(target) &&
        !notifMobileRef.current?.contains(target)
      ) {
        setNotifOpen(false);
      }
    }
    function onEscape(e: KeyboardEvent) {
      if (e.key === "Escape") { setUserOpen(false); setNotifOpen(false); setSearchOpenDesktop(false); setSearchOpenMobile(false); }
    }
    document.addEventListener("mousedown", onOutside);
    document.addEventListener("keydown", onEscape);
    return () => {
      document.removeEventListener("mousedown", onOutside);
      document.removeEventListener("keydown", onEscape);
    };
  }, []);

  useEffect(() => {
    if (searchOpenMobile) {
      mobileSearchInputRef.current?.focus();
    }
  }, [searchOpenMobile]);

  // Lock page scroll while the mobile notification drawer is open — the
  // desktop dropdown (lg:) isn't a full-screen overlay, so it's left scrollable.
  useEffect(() => {
    if (!notifOpen || !window.matchMedia("(max-width: 1023px)").matches) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, [notifOpen]);

  function handleSignOutRequest() {
    setUserOpen(false);
    setLogoutOpen(true);
  }

  function handleSignOut() {
    signOut();
    router.push("/agent/login");
  }

  const allNotifs  = notifData?.notifications ?? [];
  const notifCount = allNotifs.length;
  const unreadCount = allNotifs.filter((n) => !isRead(notifKey(n.message))).length;

  const searchPlaceholder =
    t("agent.header.searchPlaceholder") !== "agent.header.searchPlaceholder"
      ? t("agent.header.searchPlaceholder")
      : "Search navigation routes, transactions, recipients...";

  return (
    <>
      <header className="sticky top-0 z-30 h-16 border-b border-slate-200/70 bg-white/85 backdrop-blur-xl dark:border-slate-800/70 dark:bg-slate-950/85">
      <Container className="flex h-full items-center gap-3">

        {/* Left: hamburger on mobile/tablet; lang + theme + store name on desktop */}
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={onMenuClick}
            aria-label={t("agent.header.openNav")}
            className={cn(
              "btn-icon text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-700 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-slate-200",
              "min-[1440px]:hidden",
              sidebarOpen && "hidden",
            )}
          >
            <Menu className="icon-lg" />
          </button>
          <div className="hidden items-center rounded-xl border border-slate-200/70 dark:border-slate-800/60 xl:flex">
            <LanguageDropdown />
          </div>
          <div className="hidden items-center justify-center rounded-xl border border-slate-200/70 dark:border-slate-800/60 xl:flex">
            <ThemeToggle />
          </div>
        </div>

        {/* Center — search navigation routes (tablet/desktop) */}
        <div className="relative hidden flex-1 max-w-xl mx-auto md:block px-2" ref={searchDesktopRef}>
          <Search className="pointer-events-none absolute start-5 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
          <input
            type="search"
            value={searchQuery}
            onChange={(e) => {
              setSearchQuery(e.target.value);
              setSearchOpenDesktop(true);
            }}
            onFocus={() => setSearchOpenDesktop(true)}
            placeholder={searchPlaceholder}
            aria-label={t("common.search") || "Search routes"}
            className="h-10 w-full rounded-full border border-slate-200 bg-slate-50/70 ps-10 pe-4 text-sm outline-none focus:outline-none focus:ring-0 focus:shadow-none [-webkit-appearance:none] transition focus:border-brand-500 focus:bg-white dark:border-slate-700 dark:bg-slate-900/50 dark:text-white dark:focus:border-brand-400 dark:focus:bg-slate-900"
          />

          {searchOpenDesktop && (
            <div className="absolute left-0 right-0 top-14 z-50 max-h-80 overflow-y-auto scrollbar-hide rounded-2xl border border-slate-200/80 bg-white/95 p-2 shadow-elevated backdrop-blur-xl animate-scale-in dark:border-slate-700/80 dark:bg-slate-900/95">
              <div className="px-3 py-1.5 text-2xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">
                Navigation Routes
              </div>
              {filteredRoutes.length > 0 ? (
                <div className="mt-1 space-y-0.5">
                  {filteredRoutes.map((r) => {
                    const Icon = r.icon;
                    return (
                      <button
                        key={r.href}
                        type="button"
                        onClick={() => {
                          router.push(r.href);
                          setSearchOpenDesktop(false);
                          setSearchQuery("");
                        }}
                        className="flex w-full items-center gap-3 rounded-xl px-3 py-2 text-left text-sm font-medium text-slate-700 transition hover:bg-brand-50 hover:text-brand-600 dark:text-slate-300 dark:hover:bg-brand-500/10 dark:hover:text-brand-400"
                      >
                        <span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-slate-100 dark:bg-slate-800">
                          <Icon className="h-4 w-4 text-slate-500 dark:text-slate-400" />
                        </span>
                        <span className="truncate flex-1">{t(r.labelKey) || r.fallback}</span>
                      </button>
                    );
                  })}
                </div>
              ) : (
                <div className="px-4 py-6 text-center text-sm text-slate-500 dark:text-slate-400">
                  No matching routes found.
                </div>
              )}
            </div>
          )}
        </div>

        {/* Right: action cluster */}
        <div className="flex items-center justify-end gap-2 ms-auto md:ms-0">

          {/* Mobile search trigger */}
          <button
            type="button"
            aria-label={t("common.search") || "Search routes"}
            onClick={() => {
              setSearchOpenMobile(true);
              setSearchQuery("");
            }}
            className="btn-icon border border-slate-200/70 text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-700 dark:border-slate-800/60 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-slate-200 md:hidden"
          >
            <Search className="icon-md" />
          </button>

          {/* Notifications */}
          <div className="relative" ref={notifRef}>
            <button
              type="button"
              onClick={() => {
                setNotifOpen((o) => !o);
                setUserOpen(false);
                setVisibleCount(NOTIF_PAGE_SIZE);
                // Mobile drawer defaults to the Unread tab; the desktop dropdown
                // has no tabs, so it stays "all" to remain fully browsable.
                setNotifFilter(window.matchMedia("(max-width: 1023px)").matches ? "unread" : "all");
              }}
              aria-label={t("agent.header.viewNotifications")}
              aria-expanded={notifOpen}
              className="relative btn-icon border border-slate-200/70 text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-700 dark:border-slate-800/60 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-slate-200"
            >
              <Bell className="icon-md" />
              {unreadCount > 0 && (
                <span className="absolute -end-0.5 -top-0.5 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-brand-500 px-1 text-[10px] font-bold leading-none text-white tabular-nums ring-2 ring-white dark:ring-slate-950">
                  {unreadCount}
                </span>
              )}
            </button>

            {notifOpen && (() => {
              const readCount = notifCount - unreadCount;
              const filteredNotifs =
                notifFilter === "all"
                  ? allNotifs
                  : allNotifs.filter((n) => isRead(notifKey(n.message)) === (notifFilter === "read"));
              const visibleNotifs = filteredNotifs.slice(0, visibleCount);
              const hasMore = visibleCount < filteredNotifs.length;

              function setFilter(next: "all" | "unread" | "read") {
                setNotifFilter(next);
                setVisibleCount(NOTIF_PAGE_SIZE);
              }

              function handleListScroll(e: UIEvent<HTMLDivElement>) {
                if (!hasMore) return;
                const el = e.currentTarget;
                if (el.scrollTop + el.clientHeight >= el.scrollHeight - 80) {
                  setVisibleCount((v) => Math.min(v + NOTIF_PAGE_SIZE, filteredNotifs.length));
                }
              }

              const notifBody = (
                <>
                  <div className="border-b border-slate-100 dark:border-slate-800">
                    <div className="flex items-center justify-between px-4 py-3">
                      <div className="flex items-center gap-2.5">
                        <h3 className="text-[length:var(--text-base-fixed)] font-bold text-slate-900 dark:text-white">{t("agent.header.notifications")}</h3>
                      </div>
                      <button
                        type="button"
                        onClick={() => setNotifOpen(false)}
                        aria-label={t("agent.header.closeNotifications")}
                        className="rounded-lg p-1.5 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600 dark:hover:bg-slate-800 dark:hover:text-slate-300"
                      >
                        <X className="icon-md" />
                      </button>
                    </div>
                    {notifCount > 0 && (
                      <>
                        {/* Desktop: mark-all actions */}
                        <div className="hidden items-center gap-1 px-4 pb-2.5 lg:flex">
                          {unreadCount > 0 && (
                            <button
                              type="button"
                              onClick={() => markAllRead(allNotifs.map((n) => notifKey(n.message)))}
                              className="rounded-lg px-2.5 py-1.5 text-[length:var(--text-xs-fixed)] font-semibold text-brand-600 transition hover:bg-brand-50 dark:text-brand-400 dark:hover:bg-brand-500/10"
                            >
                              {t("agent.header.markAllRead")}
                            </button>
                          )}
                          {readCount > 0 && (
                            <button
                              type="button"
                              onClick={() => markAllUnread(allNotifs.map((n) => notifKey(n.message)))}
                              className="rounded-lg px-2.5 py-1.5 text-[length:var(--text-xs-fixed)] font-semibold text-slate-500 transition hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800"
                            >
                              {t("agent.header.markAllUnread")}
                            </button>
                          )}
                        </div>

                        {/* Mobile: unread/read filter tabs + mark-as-read action */}
                        <div className="flex items-center gap-1.5 px-4 pb-2.5 lg:hidden">
                          <button
                            type="button"
                            onClick={() => setFilter(notifFilter === "unread" ? "all" : "unread")}
                            aria-pressed={notifFilter === "unread"}
                            className={cn(
                              "inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[length:var(--text-xs-fixed)] font-semibold transition",
                              notifFilter === "unread"
                                ? "bg-brand-600 text-white"
                                : "bg-slate-100 text-slate-600 hover:bg-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:hover:bg-slate-700",
                            )}
                          >
                            {t("agent.notifications.tabUnread")}
                            {unreadCount > 0 && (
                              <span
                                className={cn(
                                  "inline-flex h-4 min-w-[16px] items-center justify-center rounded-full px-1 text-[10px] font-bold leading-none tabular-nums",
                                  notifFilter === "unread"
                                    ? "bg-white/25 text-white"
                                    : "bg-brand-100 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300",
                                )}
                              >
                                {unreadCount}
                              </span>
                            )}
                          </button>
                          <button
                            type="button"
                            onClick={() => setFilter(notifFilter === "read" ? "all" : "read")}
                            aria-pressed={notifFilter === "read"}
                            className={cn(
                              "inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[length:var(--text-xs-fixed)] font-semibold transition",
                              notifFilter === "read"
                                ? "bg-brand-600 text-white"
                                : "bg-slate-100 text-slate-600 hover:bg-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:hover:bg-slate-700",
                            )}
                          >
                            {t("agent.notifications.tabRead")}
                            {readCount > 0 && (
                              <span
                                className={cn(
                                  "inline-flex h-4 min-w-[16px] items-center justify-center rounded-full px-1 text-[10px] font-bold leading-none tabular-nums",
                                  notifFilter === "read"
                                    ? "bg-white/25 text-white"
                                    : "bg-brand-100 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300",
                                )}
                              >
                                {readCount}
                              </span>
                            )}
                          </button>
                          {unreadCount > 0 && (
                            <button
                              type="button"
                              onClick={() => markAllRead(allNotifs.map((n) => notifKey(n.message)))}
                              className="ms-auto rounded-lg px-3 py-1.5 text-[length:var(--text-xs-fixed)] font-semibold text-brand-600 transition hover:bg-brand-50 dark:text-brand-400 dark:hover:bg-brand-500/10"
                            >
                              {t("agent.header.markAllRead")}
                            </button>
                          )}
                        </div>
                      </>
                    )}
                  </div>

                  <div
                    onScroll={handleListScroll}
                    className="flex-1 divide-y divide-slate-100 overflow-y-auto dark:divide-slate-800/60 lg:max-h-[340px] lg:flex-none"
                  >
                    {notifLoading ? (
                      <div className="p-8 text-center">
                        <div className="mx-auto h-6 w-6 animate-spin rounded-full border-2 border-slate-300 border-t-brand-600 dark:border-slate-700 dark:border-t-brand-400" />
                      </div>
                    ) : filteredNotifs.length > 0 ? (
                      <>
                        {visibleNotifs.map((notif) => {
                          const read = isRead(notifKey(notif.message));
                          const styles = getNotificationStyles(notif.message);
                          const NotifIcon = styles.icon;
                          return (
                            <button
                              key={notif.id}
                              onClick={() => markRead(notifKey(notif.message))}
                              className="flex w-full gap-3 p-4 text-left transition-colors hover:bg-slate-50/80 dark:hover:bg-slate-800/40"
                            >
                              <div className={cn("relative mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-full", styles.colorClass)}>
                                <NotifIcon className="h-4.5 w-4.5" aria-hidden />
                                {!read && (
                                  <span className={cn("absolute -bottom-0.5 -end-0.5 h-2.5 w-2.5 rounded-full border-2 border-white dark:border-slate-900", styles.dotClass)} />
                                )}
                              </div>
                              <div className="min-w-0 flex-1">
                                <p className={`text-sm leading-snug ${read ? "font-normal text-slate-400 dark:text-slate-500" : "font-medium text-slate-700 dark:text-slate-200"}`}>
                                  {notif.message}
                                </p>
                                <p className="mt-1.5 text-2xs font-semibold uppercase tracking-wider text-slate-400 dark:text-slate-500">
                                  {new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "numeric" }).format(new Date(notif.created_at))}
                                </p>
                              </div>
                              {!read && (
                                <span className="mt-0.5 shrink-0 self-start rounded-full bg-brand-500/10 px-2 py-0.5 text-2xs font-bold uppercase tracking-wide text-brand-600 dark:text-brand-400">
                                  {t("agent.notifications.newBadge")}
                                </span>
                              )}
                            </button>
                          );
                        })}
                        {hasMore && (
                          <div className="flex items-center justify-center p-4">
                            <div className="h-4 w-4 animate-spin rounded-full border-2 border-slate-300 border-t-brand-600 dark:border-slate-700 dark:border-t-brand-400" />
                          </div>
                        )}
                      </>
                    ) : (
                      <div className="p-8 text-center">
                        <Bell className="mx-auto mb-3 h-8 w-8 text-slate-300 dark:text-slate-600" />
                        <p className="text-sm font-medium text-slate-500 dark:text-slate-400">
                          {notifCount === 0
                            ? t("agent.header.allCaughtUp")
                            : notifFilter === "unread"
                              ? t("agent.notifications.noUnread")
                              : t("agent.notifications.noRead")}
                        </p>
                      </div>
                    )}
                  </div>

                  <div className="border-t border-slate-100 bg-slate-50/50 p-2 dark:border-slate-800 dark:bg-slate-900/50">
                    <Link
                      href="/agent/notifications"
                      onClick={() => setNotifOpen(false)}
                      className="block w-full rounded-xl px-4 py-2.5 text-center text-xs font-bold uppercase tracking-wider text-brand-600 transition hover:bg-brand-50 dark:text-brand-400 dark:hover:bg-brand-500/10"
                    >
                      {t("agent.header.viewAllNotifications")}
                    </Link>
                  </div>
                </>
              );

              return (
                <>
                  {/* Desktop dropdown — anchored to the bell */}
                  <div
                    ref={notifDesktopRef}
                    role="menu"
                    className="absolute end-0 z-40 mt-2 hidden w-96 overflow-hidden rounded-2xl border border-slate-200/80 bg-white/95 shadow-elevated backdrop-blur-xl animate-scale-in dark:border-slate-700/80 dark:bg-slate-900/95 lg:block"
                  >
                    {notifBody}
                  </div>

                  {/* Mobile full-screen drawer — portaled to escape header stacking/containing-block */}
                  {createPortal(
                    <div className="lg:hidden">
                      <div className="fixed inset-0 z-40 bg-slate-900/50 backdrop-blur-sm" aria-hidden />
                      <div
                        ref={notifMobileRef}
                        role="menu"
                        className="fixed inset-y-0 end-0 z-50 flex w-full flex-col overflow-hidden bg-white shadow-2xl animate-slide-in-right dark:bg-slate-900 rtl:animate-slide-in-left"
                      >
                        {notifBody}
                      </div>
                    </div>,
                    document.body,
                  )}
                </>
              );
            })()}
          </div>


          {/* User menu */}
          <div className="relative" ref={userRef}>
            <button
              type="button"
              aria-label={t("agent.header.profileMenu") || "Profile menu"}
              aria-expanded={userOpen}
              aria-haspopup="menu"
              onClick={() => {
                setUserOpen((o) => !o);
                setNotifOpen(false);
              }}
              className="group flex items-center gap-2 rounded-full p-1 pe-2.5 transition-all duration-200 hover:bg-slate-100/80 dark:hover:bg-slate-800/70 focus:outline-none"
            >
              {user?.avatar ? (
                <Image
                  src={user.avatar}
                  alt="Avatar"
                  width={32}
                  height={32}
                  unoptimized
                  className="h-8 w-8 shrink-0 rounded-full object-cover ring-2 ring-slate-200/80 transition-all duration-200 group-hover:ring-brand-500/50 dark:ring-slate-700/80"
                />
              ) : (
                <span className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-gradient-to-br from-brand-500 to-accent-500 text-xs font-bold text-white shadow-sm ring-2 ring-slate-200/80 transition-all duration-200 group-hover:ring-brand-500/50 dark:ring-slate-700/80">
                  {initials}
                </span>
              )}
              <span className="hidden text-sm font-semibold text-slate-700 transition-colors group-hover:text-slate-900 dark:text-slate-200 dark:group-hover:text-white sm:block">
                {user?.firstName || user?.email}
              </span>
              <ChevronDown
                className={cn(
                  "hidden h-3.5 w-3.5 shrink-0 text-slate-400 transition-transform duration-200 group-hover:text-slate-600 dark:group-hover:text-slate-300 sm:block",
                  userOpen && "rotate-180 text-brand-600 dark:text-brand-400",
                )}
              />
            </button>

            {userOpen && (
              <div
                role="menu"
                className="absolute end-0 z-40 mt-2 w-72 sm:w-80 overflow-visible rounded-2xl border border-slate-200/80 bg-white/95 shadow-elevated backdrop-blur-xl animate-scale-in dark:border-slate-700/80 dark:bg-slate-900/95"
              >
                <div className="border-b border-slate-100 px-4 py-3 dark:border-slate-800">
                  <div className="flex items-center gap-3">
                    {user?.avatar ? (
                      <Image
                        src={user.avatar}
                        alt="Avatar"
                        width={40}
                        height={40}
                        unoptimized
                        className="h-10 w-10 shrink-0 rounded-full object-cover ring-2 ring-slate-200/80 dark:ring-slate-700/80"
                      />
                    ) : (
                      <span className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-gradient-to-br from-brand-500 to-accent-500 text-sm font-bold text-white ring-2 ring-slate-200/80 dark:ring-slate-700/80">
                        {initials}
                      </span>
                    )}
                    <div className="min-w-0">
                      <p className="truncate text-sm font-semibold text-slate-900 dark:text-white">
                        {user?.firstName} {user?.lastName}
                      </p>
                      <p className="truncate text-xs text-slate-500 dark:text-slate-400">
                        {user?.email}
                      </p>
                    </div>
                  </div>
                  {user?.storeName && (
                    <div className="mt-2.5 flex items-center gap-1.5 rounded-lg bg-slate-50 px-2.5 py-1.5 dark:bg-slate-800/60">
                      <Building2 className="h-3 w-3 shrink-0 text-slate-400 dark:text-slate-500" aria-hidden />
                      <span className="truncate text-xs font-medium text-slate-600 dark:text-slate-300">
                        {user.storeName}
                      </span>
                    </div>
                  )}
                </div>

                <div className="p-1 border-b border-slate-100 dark:border-slate-800">
                  <button
                    type="button"
                    role="menuitem"
                    onClick={() => { setUserOpen(false); router.push("/agent/profile"); }}
                    className="flex w-full items-center gap-2.5 rounded-xl px-3 py-2.5 text-sm font-medium text-slate-700 transition hover:bg-slate-50 dark:text-slate-200 dark:hover:bg-slate-800/70"
                  >
                    <UserCircle className="h-4 w-4 text-slate-400" />
                    {t("agent.header.profile") || "Profile"}
                  </button>
                </div>

                {/* Encapsulated Navbar Items (Language & Theme) under Profile Modal on Tablet/Mobile */}
                <div className="border-b border-slate-100 p-3 dark:border-slate-800 space-y-3 xl:hidden">
                  <div className="space-y-1.5">
                    <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 block whitespace-nowrap">
                      {t("language.switch") !== "language.switch" ? t("language.switch") : "Switch language"}
                    </span>
                    <LanguageDropdown inline />
                  </div>
                  <div className="space-y-1.5">
                    <span className="text-xs font-semibold text-slate-500 dark:text-slate-400 block whitespace-nowrap">
                      {t("common.theme") !== "common.theme" && t("common.theme") ? t("common.theme") : "Appearance / Theme"}
                    </span>
                    <ThemeToggle inline />
                  </div>
                </div>

                <div className="p-1">
                  <button
                    type="button"
                    role="menuitem"
                    onClick={handleSignOutRequest}
                    className="flex w-full items-center gap-2.5 rounded-xl px-3 py-2.5 text-sm font-medium text-rose-600 transition hover:bg-rose-50 dark:text-rose-400 dark:hover:bg-rose-500/10"
                  >
                    <LogOut className="icon-md" />
                    {t("agent.header.signOut") || "Sign Out"}
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </Container>
    </header>

      {/* Mobile search overlay */}
      {searchOpenMobile && (
        <div className="fixed inset-0 z-50 flex flex-col bg-white dark:bg-slate-950 md:hidden animate-fade-in" role="search">
          {/* Top header bar */}
          <div className="flex shrink-0 items-center gap-3 border-b border-slate-200/80 bg-white px-4 py-3.5 dark:border-slate-800 dark:bg-slate-950">
            <div className="flex h-10 flex-1 items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-3 transition focus-within:border-brand-500 focus-within:bg-white focus-within:ring-4 focus-within:ring-brand-500/10 dark:border-slate-700 dark:bg-slate-900 dark:focus-within:border-brand-400 dark:focus-within:bg-slate-900">
              <Search className="h-4 w-4 shrink-0 text-slate-400" />
              <input
                ref={mobileSearchInputRef}
                type="search"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder={searchPlaceholder}
                aria-label={t("common.search") || "Search routes"}
                className="w-full min-w-0 flex-1 border-0 bg-transparent p-0 text-sm text-slate-900 outline-none focus:border-0 focus:outline-none focus-visible:ring-0 focus-visible:ring-offset-0 [-webkit-appearance:none] placeholder:truncate placeholder:text-slate-400 dark:text-white"
              />
            </div>
            <button
              type="button"
              aria-label="Close search"
              onClick={() => setSearchOpenMobile(false)}
              className="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-slate-200 text-slate-500 transition hover:bg-slate-100 dark:border-slate-700 dark:text-slate-400 dark:hover:bg-slate-800"
            >
              <X className="h-4 w-4" />
            </button>
          </div>

          {/* Full height scrollable body */}
          <div className="flex-1 overflow-y-auto p-4">
            <div className="px-3 py-1.5 text-2xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">
              Navigation Routes
            </div>
            {filteredRoutes.length > 0 ? (
              <div className="mt-1 space-y-0.5">
                {filteredRoutes.map((r) => {
                  const Icon = r.icon;
                  return (
                    <button
                      key={r.href}
                      type="button"
                      onClick={() => {
                        router.push(r.href);
                        setSearchOpenMobile(false);
                        setSearchQuery("");
                      }}
                      className="flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left text-sm font-medium text-slate-700 transition hover:bg-brand-50 hover:text-brand-600 dark:text-slate-300 dark:hover:bg-brand-500/10 dark:hover:text-brand-400"
                    >
                      <span className="grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-slate-100 dark:bg-slate-800">
                        <Icon className="h-4.5 w-4.5 text-slate-500 dark:text-slate-400" />
                      </span>
                      <span className="truncate flex-1">{t(r.labelKey) || r.fallback}</span>
                    </button>
                  );
                })}
              </div>
            ) : (
              <div className="px-4 py-8 text-center text-sm text-slate-500 dark:text-slate-400">
                No matching routes found.
              </div>
            )}
          </div>
        </div>
      )}

      <LogoutConfirmModal
        open={logoutOpen}
        onClose={() => setLogoutOpen(false)}
        onConfirm={handleSignOut}
      />
    </>
  );
}
