import { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
  Search, Settings, DollarSign, Users, Phone, Plus, User, Eye, LogOut, Shield,
  Building2, Home, FileText, AlertTriangle, Loader2, Database, MessageCircle,
  Landmark, ExternalLink, LayoutDashboard, Gavel, Scale, Receipt, BarChart3,
  Calendar, FileBox, FilePlus, FileSignature, FolderKanban, CheckSquare,
  ClipboardList, Megaphone, Mail, MailOpen, AtSign, ServerCog, Bot, CalendarOff,
  FileSearch, UserCog, Car, StickyNote, ListChecks, CreditCard, Vote, UserCheck,
  PieChart, BellRing, FileCode, Send, ImageIcon, Bell, Menu, ChevronDown, FileEdit, Clock, BookOpen, Upload, Inbox, ClipboardCheck, KeyRound, Briefcase, Calculator
} from "lucide-react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { CallLogDialog } from "@/components/CallLogDialog";
import { NotificationBell } from "@/components/NotificationBell";
import { MessagesIconButton } from "@/components/MessagesIconButton";
import { EmailInboxDrawer } from "@/components/dashboard/EmailInboxDrawer";
import { TimerPopover } from "@/components/dashboard/TimerPopover";
import { DateCalculatorPopover } from "@/components/dashboard/DateCalculatorPopover";
import UnitLedgerTransactionForm from "@/components/unit-profile/UnitLedgerTransactionForm";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem,
  DropdownMenuSeparator, DropdownMenuTrigger,
  DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent,
} from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";
import type { Enums } from "@/integrations/supabase/types";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/contexts/AuthContext";
import { useTickerCounts } from "@/contexts/TickerContext";
import { cn } from "@/lib/utils";
import sidebarLogo from "@/assets/favicon-logo.png";

interface DashboardTopNavProps {
  userId?: string;
  userEmail?: string;
  fullName?: string;
  roles?: Enums<"app_role">[];
}

interface SearchResult {
  id: string;
  type: "owner" | "unit" | "association" | "violation" | "invoice" | "shortcut";
  title: string;
  subtitle: string;
  route: string;
}

const typeIcons: Record<SearchResult["type"], React.ReactNode> = {
  owner: <Users className="h-3.5 w-3.5 text-primary" />,
  unit: <Home className="h-3.5 w-3.5 text-primary" />,
  association: <Building2 className="h-3.5 w-3.5 text-primary" />,
  violation: <AlertTriangle className="h-3.5 w-3.5 text-destructive" />,
  invoice: <FileText className="h-3.5 w-3.5 text-primary" />,
  shortcut: <Database className="h-3.5 w-3.5 text-primary" />,
};

/* ── Navigation Data ── */

type NavItemDef = { title: string; url: string; icon: React.ElementType; tickerKey?: string };

interface MegaMenuSection {
  label: string;
  triggerIcon: React.ElementType;
  columns: { heading: string; items: NavItemDef[] }[];
}

const megaMenuSections: MegaMenuSection[] = [
  {
    label: "Community",
    triggerIcon: Building2,
    columns: [
      {
        heading: "Management",
        items: [
          { title: "Associations", url: "/dashboard/associations", icon: Building2 },
          { title: "Directory", url: "/dashboard/directory", icon: Home },
        ],
      },
      {
        heading: "Board & Governance",
        items: [
          { title: "Board Members", url: "/dashboard/board-members", icon: UserCheck },
          { title: "Board Resources", url: "/dashboard/board-resources", icon: BookOpen },
          { title: "Board Votes", url: "/dashboard/board-votes", icon: Vote, tickerKey: "board_votes" },
          { title: "Elections", url: "/dashboard/elections", icon: Vote },
        ],
      },
      {
        heading: "Compliance",
        items: [
          { title: "Violations", url: "/dashboard/violations", icon: AlertTriangle },
          { title: "ARC Applications", url: "/dashboard/arc-applications", icon: Gavel, tickerKey: "arc_applications" },
          { title: "Parking", url: "/dashboard/parking", icon: Car },
          { title: "RV / Boat Lots", url: "/dashboard/rv-boat-lots", icon: Car },
        ],
      },
      {
        heading: "Requests & Cases",
        items: [
          { title: "Homeowner Requests", url: "/dashboard/homeowner-requests", icon: MessageCircle, tickerKey: "homeowner_requests" },
          { title: "Client Requests", url: "/dashboard/client-requests", icon: ClipboardList },
          { title: "Legal Matters", url: "/dashboard/legal-matters", icon: Scale },
        ],
      },
    ],
  },
  {
    label: "Operations",
    triggerIcon: FolderKanban,
    columns: [
      {
        heading: "Projects & Tasks",
        items: [
          { title: "Projects", url: "/dashboard/projects", icon: FolderKanban, tickerKey: "projects" },
          { title: "Tasks", url: "/dashboard/tasks", icon: CheckSquare, tickerKey: "tasks" },
          { title: "Checklists", url: "/dashboard/checklists", icon: ListChecks },
        ],
      },
      {
        heading: "Scheduling",
        items: [
          { title: "Calendar", url: "/dashboard/calendar", icon: Calendar },
          { title: "Reminders", url: "/dashboard/reminders", icon: Bell, tickerKey: "reminders" },
          { title: "Blocked Dates", url: "/dashboard/blocked-dates", icon: CalendarOff },
        ],
      },
      {
        heading: "Field & Updates",
        items: [
          { title: "Inspections", url: "/dashboard/inspections", icon: ClipboardList },
          { title: "Communication Log", url: "/dashboard/call-log", icon: Phone },
          { title: "Owner Updates", url: "/dashboard/owner-updates", icon: StickyNote },
          { title: "Status Updates", url: "/dashboard/status-updates", icon: BarChart3 },
          { title: "Association Reports", url: "/dashboard/reports", icon: BarChart3 },
        ],
      },
      {
        heading: "Vendors",
        items: [
          { title: "Vendors", url: "/dashboard/vendors", icon: Users },
          { title: "Bids & Quotes", url: "/dashboard/bids-quotes", icon: Scale },
          { title: "Bill Approvals", url: "/dashboard/bill-approvals", icon: Shield, tickerKey: "bill_approvals" },
        ],
      },
    ],
  },
  {
    label: "Finance",
    triggerIcon: DollarSign,
    columns: [
      {
        heading: "Overview",
        items: [
          { title: "Financial Overview", url: "/dashboard/financial-overview", icon: PieChart },
          { title: "Financial Reports", url: "/dashboard/financial-reports", icon: BarChart3 },
          { title: "Recent Ledger Updates", url: "/dashboard/recent-ledger-updates", icon: Clock },
          { title: "Budget Management", url: "/dashboard/budget-management", icon: BarChart3 },
        ],
      },
      {
        heading: "Receivables",
        items: [
          { title: "Outstanding Balances", url: "/dashboard/outstanding-balances", icon: DollarSign },
          { title: "Bulk Charges", url: "/dashboard/bulk-charges", icon: DollarSign },
          { title: "Collections", url: "/dashboard/collections", icon: DollarSign },
          { title: "Payments", url: "/dashboard/payments", icon: CreditCard },
          { title: "Estoppels", url: "/dashboard/estoppels", icon: FileText },
          { title: "Payment Plans", url: "/dashboard/payment-plans", icon: DollarSign },
        ],
      },
      {
        heading: "Payables",
        items: [
          { title: "Payables", url: "/dashboard/payables", icon: Receipt },
        ],
      },
    ],
  },
  {
    label: "Communication",
    triggerIcon: MessageCircle,
    columns: [
      {
        heading: "Messaging",
        items: [
          { title: "Messages", url: "/dashboard/messages", icon: MessageCircle },
          { title: "Compose Email", url: "/dashboard/compose-email", icon: Send },
        ],
      },
      {
        heading: "Notifications",
        items: [
          { title: "Notify Board", url: "/dashboard/notify-board", icon: Megaphone },
          { title: "Notify Owners", url: "/dashboard/notify-owners", icon: BellRing },
        ],
      },
      {
        heading: "Email Management",
        items: [
          { title: "Email History", url: "/dashboard/email-history", icon: Mail },
          { title: "Email Templates", url: "/dashboard/email-templates", icon: FileCode },
          { title: "Email Senders", url: "/dashboard/email-senders", icon: AtSign },
          { title: "Email Routing", url: "/dashboard/email-routing", icon: MailOpen },
        ],
      },
    ],
  },
  {
    label: "Documents",
    triggerIcon: FileBox,
    columns: [
      {
        heading: "Content",
        items: [
          { title: "Documents", url: "/dashboard/documents", icon: FileBox },
          { title: "Forms & Letters", url: "/dashboard/forms-letters", icon: FilePlus },
          { title: "Avria Sign", url: "/dashboard/avria-sign", icon: FileSignature },
          { title: "Announcements", url: "/dashboard/announcements", icon: Megaphone },
          { title: "Media Library", url: "/dashboard/media", icon: ImageIcon },
          { title: "Collab Docs", url: "/dashboard/collaborative-docs", icon: FileEdit },
        ],
      },
    ],
  },
];

const adminSection: MegaMenuSection = {
  label: "Admin",
  triggerIcon: UserCog,
  columns: [
    {
      heading: "System",
      items: [
        { title: "User Management", url: "/dashboard/user-management", icon: UserCog },
        { title: "Sign-up Codes", url: "/dashboard/signup-codes", icon: KeyRound },
        { title: "Time Tracking", url: "/dashboard/time-tracking", icon: Clock },
        { title: "Bulk Updates", url: "/dashboard/bulk-updates", icon: Upload },
        { title: "Compliance Checklists", url: "/dashboard/compliance-checklists", icon: ClipboardCheck },
        { title: "Data Migration", url: "/dashboard/data-migration", icon: Database },
        { title: "Migration Fields", url: "/dashboard/migration-fields", icon: Database },
      ],
    },
    {
      heading: "Accounting Setup",
      items: [
        { title: "Bank Accounts", url: "/dashboard/bank-accounts", icon: Landmark },
        { title: "Chart of Accounts", url: "/dashboard/chart-of-accounts", icon: BookOpen },
      ],
    },
    {
      heading: "Billing & Invoicing",
      items: [
        { title: "Billable Expenses", url: "/dashboard/billable-expenses", icon: Receipt },
        { title: "Invoice Clients", url: "/dashboard/invoice-clients", icon: FileText },
        { title: "Client Invoices", url: "/dashboard/client-invoices", icon: FileText },
        { title: "Invoice Tracking", url: "/dashboard/invoice-tracking", icon: FileSearch },
      ],
    },
  ],
};

/* ── Mega Menu Panel ── */

function MegaMenuPanel({ section, onNavigate }: { section: MegaMenuSection; onNavigate: (url: string) => void }) {
  const location = useLocation();
  const counts = useTickerCounts();

  return (
    <div className={cn(
      "grid gap-6 p-5",
      section.columns.length === 1 ? "grid-cols-1 min-w-[220px]" :
      section.columns.length === 2 ? "grid-cols-2 min-w-[400px]" :
      section.columns.length === 3 ? "grid-cols-3 min-w-[560px]" :
      "grid-cols-4 min-w-[720px]"
    )}>
      {section.columns.map((col) => (
        <div key={col.heading} className="space-y-1.5">
          <div className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/50 px-2 pb-1">
            {col.heading}
          </div>
          {col.items.map((item) => {
            const isActive = location.pathname === item.url;
            const count = item.tickerKey ? counts[item.tickerKey as keyof typeof counts] : 0;
            return (
              <button
                key={item.url}
                onClick={() => onNavigate(item.url)}
                className={cn(
                  "flex items-center gap-2.5 w-full rounded-md px-2 py-1.5 text-[13px] transition-colors text-left",
                  "hover:bg-accent/60",
                  isActive ? "bg-primary/10 text-primary font-medium" : "text-foreground/80"
                )}
              >
                <item.icon className={cn("h-3.5 w-3.5 shrink-0", isActive ? "text-primary" : "text-muted-foreground/60")} />
                <span className="truncate flex-1">{item.title}</span>
                {count > 0 && (
                  <Badge variant="secondary" className="h-4 min-w-4 px-1 text-[9px] font-semibold bg-primary/15 text-primary border-0">
                    {count > 99 ? "99+" : count}
                  </Badge>
                )}
              </button>
            );
          })}
        </div>
      ))}
    </div>
  );
}

/* ── Mobile Nav Drawer ── */

function MobileNavDrawer({ sections, onNavigate, open, onClose }: {
  sections: MegaMenuSection[];
  onNavigate: (url: string) => void;
  open: boolean;
  onClose: () => void;
}) {
  const location = useLocation();
  const counts = useTickerCounts();

  if (!open) return null;

  return (
    <>
      <div className="fixed inset-0 bg-black/30 z-40" onClick={onClose} />
      <div className="fixed inset-y-0 left-0 w-72 bg-card border-r border-border z-50 overflow-y-auto">
        <div className="p-4 border-b border-border flex items-center justify-between">
          <span className="text-sm font-semibold">Navigation</span>
          <Button variant="ghost" size="sm" onClick={onClose} className="h-7 w-7 p-0">✕</Button>
        </div>
        <div className="py-2">
          <button
            onClick={() => { onNavigate("/dashboard"); onClose(); }}
            className={cn(
              "flex items-center gap-2.5 w-full px-4 py-2 text-[13px] hover:bg-accent/60",
              location.pathname === "/dashboard" && "bg-primary/10 text-primary font-medium"
            )}
          >
            <LayoutDashboard className="h-4 w-4" /> Dashboard
          </button>
          {sections.map((section) => (
            <div key={section.label} className="mt-2">
              <div className="px-4 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/50">
                {section.label}
              </div>
              {section.columns.flatMap((col) => col.items).map((item) => {
                const isActive = location.pathname === item.url;
                const count = item.tickerKey ? counts[item.tickerKey as keyof typeof counts] : 0;
                return (
                  <button
                    key={item.url}
                    onClick={() => { onNavigate(item.url); onClose(); }}
                    className={cn(
                      "flex items-center gap-2.5 w-full px-4 py-1.5 text-[13px] hover:bg-accent/60",
                      isActive ? "bg-primary/10 text-primary font-medium" : "text-foreground/80"
                    )}
                  >
                    <item.icon className={cn("h-3.5 w-3.5 shrink-0", isActive ? "text-primary" : "text-muted-foreground/60")} />
                    <span className="truncate flex-1">{item.title}</span>
                    {count > 0 && (
                      <Badge variant="secondary" className="h-4 min-w-4 px-1 text-[9px] font-semibold bg-primary/15 text-primary border-0">
                        {count > 99 ? "99+" : count}
                      </Badge>
                    )}
                  </button>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

/* ── Main Component ── */

export function DashboardTopNav({ userEmail, fullName, roles = [], userId }: DashboardTopNavProps) {
  const navigate = useNavigate();
  const location = useLocation();
  const { isAdmin, isStaff, realIsAdmin, setViewAsRole } = useAuth();
  const { toast } = useToast();

  const displayName = fullName || userEmail || "User";
  const initials = fullName
    ? fullName.split(" ").map((n) => n[0]).join("").toUpperCase().slice(0, 2)
    : userEmail ? userEmail.slice(0, 2).toUpperCase() : "U";
  const primaryRole = roles[0];
  const roleLabel = primaryRole ? primaryRole.charAt(0).toUpperCase() + primaryRole.slice(1) : undefined;

  const [callLogOpen, setCallLogOpen] = useState(false);
  const [chargePaymentOpen, setChargePaymentOpen] = useState(false);
  const [profileOpen, setProfileOpen] = useState(false);
  const [profileForm, setProfileForm] = useState({ full_name: fullName || "", email: userEmail || "" });
  const [associations, setAssociations] = useState<{ id: string; name: string }[]>([]);
  const [mobileNavOpen, setMobileNavOpen] = useState(false);

  // Search state
  const [searchQuery, setSearchQuery] = useState("");
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
  const [searchLoading, setSearchLoading] = useState(false);
  const [showResults, setShowResults] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(-1);
  const searchRef = useRef<HTMLDivElement>(null);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>();

  // Mega menu hover state
  const [activeMenu, setActiveMenu] = useState<string | null>(null);
  const menuTimeoutRef = useRef<ReturnType<typeof setTimeout>>();

  const visibleSections = isAdmin
    ? [...megaMenuSections, adminSection]
    : megaMenuSections;

  useEffect(() => {
    supabase.from("associations").select("id, name, zoho_organization_id").eq("status", "active").order("name").then(({ data }) => {
      setAssociations(data || []);
    });
  }, []);

  useEffect(() => {
    setProfileForm({ full_name: fullName || "", email: userEmail || "" });
  }, [fullName, userEmail]);

  // Close search on outside click
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (searchRef.current && !searchRef.current.contains(e.target as Node)) {
        setShowResults(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Close mega menu on route change
  useEffect(() => {
    setActiveMenu(null);
  }, [location.pathname]);

  const handleMenuEnter = (label: string) => {
    if (menuTimeoutRef.current) clearTimeout(menuTimeoutRef.current);
    setActiveMenu(label);
  };

  const handleMenuLeave = () => {
    menuTimeoutRef.current = setTimeout(() => setActiveMenu(null), 150);
  };

  const handleNavigate = (url: string) => {
    setActiveMenu(null);
    navigate(url);
  };

  // Search logic (same as DashboardHeader)
  const performSearch = useCallback(async (query: string) => {
    if (query.length < 2) {
      setSearchResults([]);
      setShowResults(false);
      return;
    }
    setSearchLoading(true);
    setShowResults(true);
    const term = `%${query}%`;
    const results: SearchResult[] = [];
    try {
      const [ownersRes, unitsRes, assocsRes, violationsRes, invoicesRes] = await Promise.all([
        supabase.from("owners").select("id, first_name, last_name, associations(name), units(account_number)").neq("status", "archived").or(`first_name.ilike.${term},last_name.ilike.${term}`).limit(5),
        supabase.from("units").select("id, unit_number, address, associations(name)").or(`unit_number.ilike.${term},address.ilike.${term}`).limit(5),
        supabase.from("associations").select("id, name, address").ilike("name", term).limit(5),
        supabase.from("violations").select("id, violation_type, status, associations(name)").or(`violation_type.ilike.${term},status.ilike.${term}`).limit(5),
        supabase.from("invoices").select("id, invoice_number, owner_name, associations(name)").or(`invoice_number.ilike.${term},owner_name.ilike.${term}`).limit(5),
      ]);
      (ownersRes.data || []).forEach((o: any) => results.push({ id: o.id, type: "owner", title: `${o.first_name || ""} ${o.last_name || ""}`.trim() || "Unknown", subtitle: `${o.associations?.name || "No association"} • ${o.units?.account_number || "No acct"}`, route: `/dashboard/owner-roster/${o.id}` }));
      (unitsRes.data || []).forEach((u: any) => results.push({ id: u.id, type: "unit", title: `Unit ${u.unit_number}`, subtitle: `${u.associations?.name || ""} • ${u.address || ""}`.trim(), route: `/dashboard/units/${u.id}` }));
      (assocsRes.data || []).forEach((a: any) => results.push({ id: a.id, type: "association", title: a.name, subtitle: a.address || "No address", route: `/dashboard/associations/${a.id}` }));
      (violationsRes.data || []).forEach((v: any) => results.push({ id: v.id, type: "violation", title: v.violation_type || "Violation", subtitle: `${v.associations?.name || ""} • ${v.status || ""}`, route: `/dashboard/violations` }));
      (invoicesRes.data || []).forEach((inv: any) => results.push({ id: inv.id, type: "invoice", title: `Invoice ${inv.invoice_number}`, subtitle: `${inv.owner_name || ""} • ${inv.associations?.name || ""}`, route: `/dashboard/invoices` }));

      const normalizedQuery = query.trim().toLowerCase();
      if (roles.includes("admin") && (normalizedQuery.includes("migration") || normalizedQuery.includes("migrate") || normalizedQuery.includes("data import"))) {
        results.unshift({ id: "data-migration-shortcut", type: "shortcut", title: "Data Migration", subtitle: "Open the admin migration tool", route: "/dashboard/data-migration" });
      }
    } catch (err) { console.error("Search error:", err); }
    setSearchResults(results);
    setSelectedIndex(-1);
    setSearchLoading(false);
  }, [roles]);

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value;
    setSearchQuery(val);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => performSearch(val), 300);
  };

  const handleSelectResult = (result: SearchResult) => {
    setShowResults(false);
    setSearchQuery("");
    setSearchResults([]);
    navigate(result.route);
  };

  const handleSearchKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      e.preventDefault();
      if (!showResults || searchResults.length === 0) return;
      handleSelectResult(searchResults[selectedIndex >= 0 ? selectedIndex : 0]);
      return;
    }
    if (!showResults || searchResults.length === 0) return;
    if (e.key === "ArrowDown") { e.preventDefault(); setSelectedIndex((p) => Math.min(p + 1, searchResults.length - 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setSelectedIndex((p) => Math.max(p - 1, 0)); }
    else if (e.key === "Escape") { setShowResults(false); }
  };

  const handleSaveProfile = async () => {
    if (!userId) return;
    const { error } = await supabase.from("profiles").update({ full_name: profileForm.full_name }).eq("user_id", userId);
    if (error) { toast({ title: "Error", description: "Failed to update profile", variant: "destructive" }); }
    else { toast({ title: "Profile updated" }); setProfileOpen(false); }
  };

  const handleSignOut = async () => {
    await supabase.auth.signOut();
    navigate("/");
  };

  return (
    <>
      <header className="sticky top-0 z-30 bg-card border-b border-border">
        {/* Top bar: logo, search, actions */}
        <div className="flex h-12 items-center gap-3 px-4">
          {/* Mobile hamburger */}
          <Button variant="ghost" size="sm" className="h-8 w-8 p-0 lg:hidden" onClick={() => setMobileNavOpen(true)}>
            <Menu className="h-4 w-4" />
          </Button>

          {/* Logo */}
          <button onClick={() => navigate("/dashboard")} className="flex items-center gap-2 shrink-0 hover:opacity-80 transition-opacity">
            <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary overflow-hidden">
              <img src={sidebarLogo} alt="Logo" className="h-4 w-4 object-contain" />
            </div>
            <span className="text-[13px] font-semibold text-foreground tracking-tight hidden sm:inline">Community Cloud</span>
          </button>

          {/* Search */}
          <div className="relative flex-1 ml-2" ref={searchRef}>
            <Search className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground/40 z-10" />
            <Input
              placeholder="Search owners, units, associations…"
              className="h-8 pl-9 text-[13px] bg-muted/50 border-transparent focus:border-border focus:bg-card transition-colors rounded-lg"
              value={searchQuery}
              onChange={handleSearchChange}
              onKeyDown={handleSearchKeyDown}
              onFocus={() => { if (searchResults.length > 0) setShowResults(true); }}
            />
            {showResults && (
              <div className="absolute top-full left-0 right-0 mt-1 bg-popover border border-border rounded-lg shadow-lg overflow-hidden z-50 max-h-[360px] overflow-y-auto">
                {searchLoading ? (
                  <div className="flex items-center justify-center py-6 gap-2 text-muted-foreground text-[13px]">
                    <Loader2 className="h-4 w-4 animate-spin" /> Searching…
                  </div>
                ) : searchResults.length === 0 ? (
                  <div className="py-6 text-center text-muted-foreground text-[13px]">No results for "{searchQuery}"</div>
                ) : (
                  <div className="py-1">
                    {searchResults.map((result, idx) => (
                      <button
                        key={`${result.type}-${result.id}`}
                        className={`w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-accent/50 transition-colors ${idx === selectedIndex ? "bg-accent/50" : ""}`}
                        onClick={() => handleSelectResult(result)}
                        onMouseEnter={() => setSelectedIndex(idx)}
                      >
                        <div className="shrink-0">{typeIcons[result.type]}</div>
                        <div className="min-w-0 flex-1">
                          <p className="text-[13px] font-medium text-foreground truncate">{result.title}</p>
                          <p className="text-[11px] text-muted-foreground truncate">{result.subtitle}</p>
                        </div>
                        <span className="shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground/60 font-medium">{result.type}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Quick actions */}
          <div className="flex items-center gap-1">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button size="sm" className="h-7 gap-1.5 text-[12px] rounded-lg">
                  <Plus className="h-3.5 w-3.5" /> <span className="hidden sm:inline">Quick Action</span>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-48">
                <DropdownMenuItem onClick={() => setChargePaymentOpen(true)}>
                  <DollarSign className="h-3.5 w-3.5 mr-2" /> New Charge / Payment
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setCallLogOpen(true)}>
                  <Phone className="h-3.5 w-3.5 mr-2" /> New Call Log
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => navigate("/dashboard/notify-owners")}>
                  <Users className="h-3.5 w-3.5 mr-2" /> Notify Owners
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>

          {/* Utilities */}
          <div className="flex items-center gap-1 border-l border-border pl-2">
            {isAdmin && <TimerPopover userId={userId} associations={associations} />}
            {isAdmin && <DateCalculatorPopover />}
            {isAdmin && <EmailInboxDrawer />}
            <MessagesIconButton to="/dashboard/messages" />
            <NotificationBell userId={userId} />
            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-muted-foreground hover:text-foreground" onClick={() => navigate("/dashboard/settings/branding")}>
                  <Settings className="h-3.5 w-3.5" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Settings</TooltipContent>
            </Tooltip>

          </div>

          {/* User */}
          <div className="flex items-center gap-2 border-l border-border pl-3">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <button className="flex items-center gap-2 hover:opacity-80 transition-opacity cursor-pointer outline-none">
                  <Avatar className="h-7 w-7">
                    <AvatarFallback className="bg-primary/10 text-primary text-[11px] font-semibold">{initials}</AvatarFallback>
                  </Avatar>
                  <div className="hidden md:flex flex-col leading-tight text-left">
                    <span className="text-[13px] font-medium truncate max-w-[120px]">{displayName}</span>
                    {roleLabel && <span className="text-[11px] text-muted-foreground">{roleLabel}</span>}
                  </div>
                </button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-52">
                <div className="px-3 py-2 border-b border-border mb-1">
                  <p className="text-[13px] font-medium truncate">{displayName}</p>
                  <p className="text-[11px] text-muted-foreground truncate">{userEmail}</p>
                </div>
                <DropdownMenuItem onClick={() => setProfileOpen(true)} className="text-[13px] gap-2">
                  <User className="h-3.5 w-3.5" /> Update Profile
                </DropdownMenuItem>
                {realIsAdmin && (
                  <>
                    <DropdownMenuSeparator />
                    <div className="px-3 py-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60 flex items-center gap-1.5">
                      <Eye className="h-3 w-3" /> View As
                    </div>
                    <DropdownMenuItem
                      className="text-[13px] gap-2"
                      onClick={() => { setViewAsRole("homeowner"); navigate("/homeowner"); }}
                    >
                      <Home className="h-3.5 w-3.5" /> Homeowner
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      className="text-[13px] gap-2"
                      onClick={() => { setViewAsRole("board_member"); navigate("/homeowner"); }}
                    >
                      <Shield className="h-3.5 w-3.5" /> Board Member
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      className="text-[13px] gap-2"
                      onClick={() => { setViewAsRole("master_board_member" as any); navigate("/master-board"); }}
                    >
                      <Building2 className="h-3.5 w-3.5" /> Master Board Member
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      className="text-[13px] gap-2"
                      onClick={() => { setViewAsRole("legal"); navigate("/legal"); }}
                    >
                      <Scale className="h-3.5 w-3.5" /> Legal
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      className="text-[13px] gap-2"
                      onClick={() => { setViewAsRole("rv_boat_lot" as any); navigate("/rv-portal"); }}
                    >
                      <Car className="h-3.5 w-3.5" /> RV / Boat Lot Renter
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      className="text-[13px] gap-2"
                      onClick={() => { setViewAsRole("association_management"); navigate("/homeowner"); }}
                    >
                      <Briefcase className="h-3.5 w-3.5" /> Association Management
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      className="text-[13px] gap-2"
                      onClick={() => { setViewAsRole("arc_member" as any); navigate("/arc"); }}
                    >
                      <Gavel className="h-3.5 w-3.5" /> ARC Member
                    </DropdownMenuItem>
                  </>
                )}
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => navigate("/dashboard/settings")} className="text-[13px] gap-2">
                  <Settings className="h-3.5 w-3.5" /> Settings
                </DropdownMenuItem>
                {isAdmin && (
                  <DropdownMenuItem
                    onClick={() => window.open("https://avriacam.com/dashboard", "_blank", "noopener,noreferrer")}
                    className="text-[13px] gap-2"
                  >
                    <ExternalLink className="h-3.5 w-3.5" /> Avriacam Dashboard
                  </DropdownMenuItem>
                )}
                <DropdownMenuItem onClick={handleSignOut} className="text-[13px] gap-2 text-destructive focus:text-destructive">
                  <LogOut className="h-3.5 w-3.5" /> Sign Out
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>

        {isStaff && (
          <div className="flex lg:hidden h-9 items-center px-4 border-t border-border/50 bg-card">
            <Button
              variant={location.pathname === "/dashboard/calendar" ? "secondary" : "ghost"}
              size="sm"
              className="h-7 gap-1.5 px-3 text-[12px] font-medium"
              onClick={() => navigate("/dashboard/calendar")}
            >
              <Calendar className="h-3.5 w-3.5" /> Staff Calendar
            </Button>
          </div>
        )}

        {/* Mega menu nav bar - desktop only */}
        <nav className="hidden lg:flex items-center h-9 px-4 gap-0.5 border-t border-border/50 bg-card">
          <button
            onClick={() => navigate("/dashboard")}
            className={cn(
              "flex items-center gap-1.5 px-3 py-1 rounded-md text-[12px] font-medium transition-colors",
              location.pathname === "/dashboard" ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground hover:bg-accent/50"
            )}
          >
            <LayoutDashboard className="h-3.5 w-3.5" /> Dashboard
          </button>

          {isStaff && (
            <button
              onClick={() => navigate("/dashboard/calendar")}
              className={cn(
                "flex items-center gap-1.5 px-3 py-1 rounded-md text-[12px] font-medium transition-colors",
                location.pathname === "/dashboard/calendar" ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground hover:bg-accent/50"
              )}
            >
              <Calendar className="h-3.5 w-3.5" /> Staff Calendar
            </button>
          )}

          <button
            onClick={() => navigate("/dashboard/accounting")}
            className={cn(
              "flex items-center gap-1.5 px-3 py-1 rounded-md text-[12px] font-medium transition-colors",
              location.pathname.startsWith("/dashboard/accounting") ? "bg-primary/10 text-primary" : "text-muted-foreground hover:text-foreground hover:bg-accent/50"
            )}
          >
            <Calculator className="h-3.5 w-3.5" /> Accounting
          </button>

          {visibleSections.map((section) => (
            <div
              key={section.label}
              className="relative"
              onMouseEnter={() => handleMenuEnter(section.label)}
              onMouseLeave={handleMenuLeave}
            >
              <button
                className={cn(
                  "flex items-center gap-1.5 px-3 py-1 rounded-md text-[12px] font-medium transition-colors",
                  activeMenu === section.label
                    ? "bg-accent text-foreground"
                    : "text-muted-foreground hover:text-foreground hover:bg-accent/50"
                )}
              >
                <section.triggerIcon className="h-3.5 w-3.5" />
                {section.label}
                <ChevronDown className={cn("h-3 w-3 transition-transform", activeMenu === section.label && "rotate-180")} />
              </button>

              {activeMenu === section.label && (
                <div
                  className="absolute left-0 top-full pt-1 z-50"
                  onMouseEnter={() => handleMenuEnter(section.label)}
                  onMouseLeave={handleMenuLeave}
                >
                  <div className="bg-popover border border-border rounded-lg shadow-xl">
                    <MegaMenuPanel section={section} onNavigate={handleNavigate} />
                  </div>
                </div>
              )}
            </div>
          ))}
        </nav>
      </header>

      {/* Mobile drawer */}
      <MobileNavDrawer
        sections={visibleSections}
        onNavigate={(url) => navigate(url)}
        open={mobileNavOpen}
        onClose={() => setMobileNavOpen(false)}
      />

      <CallLogDialog open={callLogOpen} onOpenChange={setCallLogOpen} associations={associations} />
      <UnitLedgerTransactionForm open={chargePaymentOpen} onOpenChange={setChargePaymentOpen} />

      {/* Profile Dialog */}
      <Dialog open={profileOpen} onOpenChange={setProfileOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-[15px] font-semibold">Update Profile</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 pt-2">
            <div className="space-y-1.5">
              <Label className="text-[12px]">Full Name</Label>
              <Input value={profileForm.full_name} onChange={(e) => setProfileForm(prev => ({ ...prev, full_name: e.target.value }))} className="h-8 text-[13px]" />
            </div>
            <div className="space-y-1.5">
              <Label className="text-[12px]">Email</Label>
              <Input value={profileForm.email} disabled className="h-8 text-[13px] bg-muted/50" />
              <p className="text-[11px] text-muted-foreground">Email cannot be changed here.</p>
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <Button variant="outline" size="sm" className="h-8 text-[12px]" onClick={() => setProfileOpen(false)}>Cancel</Button>
              <Button size="sm" className="h-8 text-[12px]" onClick={handleSaveProfile}>Save Changes</Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
