"use client";

import { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { Bell, Search, ChevronDown, Check, Globe, LogIn, Settings, Shield, Users, RefreshCw, AlertCircle, CheckCircle2, X, Plug, ListChecks, CreditCard, Building2, Zap, Plus, Loader2, ShieldCheck, ArrowRight, Menu, Command, Pencil } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useBrand } from "@/context/brand-context";
import { UserButton } from "@clerk/nextjs";
import { TaskHistoryDropdown } from "@/components/task-history-dropdown";

export function TopNav({ onMenuClick }: { onMenuClick?: () => void }) {
  const { brand: selectedBrand, brands, setBrand: setSelectedBrand, loading: brandsLoading, refresh: refreshBrands, orgId } = useBrand();
  const router = useRouter();
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [brandSearch, setBrandSearch] = useState("");
  const brandSearchRef = useRef<HTMLInputElement>(null);
  const [notifOpen, setNotifOpen] = useState(false);
  const [addMode, setAddMode] = useState(false);
  const [newName, setNewName] = useState("");
  const [newDomain, setNewDomain] = useState("");
  const [creating, setCreating] = useState(false);
  const [createError, setCreateError] = useState<string | null>(null);
  // ── Add brand handler ──
  async function handleAddBrand() {
    if (!newName.trim() || !newDomain.trim() || creating) return;
    setCreating(true);
    setCreateError(null);
    try {
      if (!orgId) { setCreateError("No organization found"); setCreating(false); return; }

      const res = await fetch("/api/brands", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ orgId, name: newName.trim(), domain: newDomain.trim() }),
      });
      if (!res.ok) {
        const data = await res.json();
        setCreateError(data.error || "Failed to create brand");
        setCreating(false);
        return;
      }

      // Refresh brands list and auto-select the new one
      await refreshBrands();
      setNewName("");
      setNewDomain("");
      setAddMode(false);
      setDropdownOpen(false);
    } catch {
      setCreateError("Network error");
    }
    setCreating(false);
  }

  const [notifFilter, setNotifFilter] = useState<string>("all");
  const [notifications, setNotifications] = useState<Array<{
    id: string; type: string; title: string; detail: string; time: string; read: boolean; action: { label: string; href: string } | null;
  }>>([])
  const [unreadCount, setUnreadCount] = useState(0);
  const [nba, setNba] = useState<{ title: string; description: string; errorCount: number; warningCount: number; crawlHealth: number } | null>(null);

  // Action label mapping by category + title keywords
  function getAction(category: string, title: string, actionUrl?: string | null): { label: string; href: string } | null {
    if (!actionUrl) return null;
    const lower = title.toLowerCase();
    if (lower.includes("failed"))    return { label: "Retry", href: actionUrl };
    if (lower.includes("overdue"))   return { label: "Review", href: actionUrl };
    if (lower.includes("assigned"))  return { label: "Open Task", href: actionUrl };
    if (lower.includes("completed")) return { label: "View", href: actionUrl };
    if (lower.includes("launched"))  return { label: "View Launch", href: actionUrl };
    if (lower.includes("invoice"))   return { label: "View Invoice", href: actionUrl };
    if (lower.includes("upgraded") || lower.includes("plan")) return { label: "View Plan", href: actionUrl };
    if (lower.includes("usage") || lower.includes("limit"))   return { label: "Upgrade", href: actionUrl };
    if (lower.includes("brand added"))  return { label: "View Brand", href: actionUrl };
    if (lower.includes("team"))      return { label: "Manage Team", href: actionUrl };
    if (lower.includes("crawl"))     return { label: "View Audit", href: actionUrl };
    if (lower.includes("report"))    return { label: "Download", href: actionUrl };
    if (lower.includes("login"))     return { label: "Review", href: actionUrl };
    if (lower.includes("settings"))  return { label: "Open Settings", href: actionUrl };
    if (lower.includes("synced"))    return { label: "View Data", href: actionUrl };
    if (lower.includes("connected")) return { label: "View", href: actionUrl };
    return { label: "View", href: actionUrl };
  }

  function timeAgo(date: Date): string {
    const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
    if (seconds < 60)    return "Just now";
    if (seconds < 3600)  return `${Math.floor(seconds / 60)} min ago`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)} hours ago`;
    if (seconds < 172800) return "Yesterday";
    return `${Math.floor(seconds / 86400)} days ago`;
  }

  const loadNotifications = useCallback(async () => {
    if (!selectedBrand.id) return;
    try {
      const res = await fetch(`/api/notifications?brandId=${encodeURIComponent(selectedBrand.id)}`, { cache: "no-store" });
      if (!res.ok) return;
      const data = await res.json();

      if (data.notifications?.length > 0) {
        setNotifications(data.notifications.map((n: Record<string, unknown>) => ({
          id: n.id as string,
          type: n.category as string,
          title: n.title as string,
          detail: n.message as string,
          time: timeAgo(new Date(n.createdAt as string)),
          read: n.status !== "unread",
          action: getAction(n.category as string, n.title as string, n.actionUrl as string | null),
        })));
      }
      setUnreadCount(data.unreadCount ?? 0);
    } catch { /* use empty state */ }
  }, [selectedBrand.id]);

  useEffect(() => { loadNotifications(); }, [loadNotifications]);

  // Load recommended action from technical audit — skip when brandId
  // hasn't resolved yet (brand context initializes with { id: "" }
  // and resolves asynchronously; fetching with empty string produces
  // a 400 that floods the console).
  useEffect(() => {
    if (!selectedBrand.id) return;
    fetch(`/api/technical-audit?brandId=${selectedBrand.id}`)
      .then(res => res.ok ? res.json() : null)
      .then(data => {
        if (!data?.audit) { setNba(null); return; }
        const a = data.audit;
        const totalIssues = (a.errorCount ?? 0) + (a.warningCount ?? 0);
        if (totalIssues === 0 || (a.pagesScanned ?? 0) === 0) { setNba(null); return; }
        setNba({
          title: `Fix ${a.errorCount} error${a.errorCount !== 1 ? "s" : ""} and ${a.warningCount} warning${a.warningCount !== 1 ? "s" : ""} on ${selectedBrand.domain}`,
          description: `Latest audit scanned ${a.pagesScanned} page${a.pagesScanned !== 1 ? "s" : ""} — Health: ${a.crawlHealth}/100`,
          errorCount: a.errorCount,
          warningCount: a.warningCount,
          crawlHealth: a.crawlHealth,
        });
      })
      .catch(() => setNba(null));
  }, [selectedBrand.id, selectedBrand.domain]);

  const filteredBrands = useMemo(() => {
    const q = brandSearch.trim().toLowerCase();
    if (!q) return brands;
    return brands.filter((b) => b.name.toLowerCase().includes(q) || b.domain.toLowerCase().includes(q));
  }, [brands, brandSearch]);

  useEffect(() => {
    if (dropdownOpen) {
      setTimeout(() => brandSearchRef.current?.focus(), 50);
    } else {
      setBrandSearch("");
    }
  }, [dropdownOpen]);

  const filteredNotifs = notifFilter === "all" ? notifications
    : notifFilter === "unread" ? notifications.filter((n) => !n.read)
    : notifications.filter((n) => n.type === notifFilter);

  async function markAllRead() {
    setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
    setUnreadCount(0);
    try { await fetch("/api/notifications", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "mark_all_read" }) }); } catch {}
  }

  async function dismissNotif(id: string) {
    setNotifications((prev) => prev.filter((n) => n.id !== id));
    try { await fetch("/api/notifications", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "dismiss", notificationId: id }) }); } catch {}
    setUnreadCount((prev) => Math.max(0, prev - (notifications.find((n) => n.id === id && !n.read) ? 1 : 0)));
  }

  const NOTIF_ICONS: Record<string, { icon: typeof Bell; color: string; bg: string }> = {
    system:      { icon: RefreshCw,    color: "text-brand-600",   bg: "bg-brand-50" },
    security:    { icon: Shield,       color: "text-emerald-600", bg: "bg-emerald-50" },
    integration: { icon: Plug,         color: "text-blue-600",    bg: "bg-blue-50" },
    task:        { icon: ListChecks,   color: "text-amber-600",   bg: "bg-amber-50" },
    billing:     { icon: CreditCard,   color: "text-violet-600",  bg: "bg-violet-50" },
    workspace:   { icon: Building2,    color: "text-sky-600",     bg: "bg-sky-50" },
  };

  const NOTIF_FILTERS: { key: string; label: string }[] = [
    { key: "all",         label: "All" },
    { key: "unread",      label: "Unread" },
    { key: "task",        label: "Tasks" },
    { key: "integration", label: "Integrations" },
    { key: "workspace",   label: "Workspace" },
    { key: "billing",     label: "Billing" },
    { key: "security",    label: "Security" },
    { key: "system",      label: "System" },
  ];

  return (
    <header className="h-14 md:h-16 border-b border-slate-200 bg-white flex items-center px-3 md:px-6 gap-2 md:gap-4">

      {/* Mobile hamburger */}
      {onMenuClick && (
        <button onClick={onMenuClick} className="md:hidden p-2 -ml-1 rounded-lg hover:bg-slate-100 text-slate-600">
          <Menu className="w-5 h-5" />
        </button>
      )}

      {/* Brand switcher. When the caller only has access to a single
          brand (Growth-tier solo users, members with one explicit
          BrandMembership) we collapse this to a static badge — the
          dropdown + chevron would be dead UI since there's nothing
          to switch to. */}
      <div className="relative">
        {brands.length <= 1 ? (
          <div
            className="flex items-center gap-2.5 px-3 py-2 rounded-lg border border-slate-200 bg-slate-50/50 select-none"
            aria-label="Active brand"
          >
            {selectedBrand.logoUrl && selectedBrand.logoUrl.trim() ? (
              <div className="w-7 h-7 rounded-lg overflow-hidden bg-white border border-slate-100 shrink-0">
                <img src={selectedBrand.logoUrl} alt={selectedBrand.name} className="w-full h-full object-contain p-0.5" />
              </div>
            ) : (
              <div className={`w-7 h-7 rounded-lg ${selectedBrand.color} flex items-center justify-center shrink-0`}>
                <span className="text-[10px] font-bold text-white">{selectedBrand.initials}</span>
              </div>
            )}
            <span className="text-sm font-semibold text-slate-800 truncate max-w-[100px] md:max-w-none">
              {selectedBrand.name}
            </span>
            {selectedBrand.isDemo && (
              <span className="text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0">Demo</span>
            )}
          </div>
        ) : (
          <button
            onClick={() => setDropdownOpen(!dropdownOpen)}
            className="flex items-center gap-2.5 px-3 py-2 rounded-lg border border-slate-200 hover:bg-slate-50 transition-colors"
          >
            {selectedBrand.logoUrl && selectedBrand.logoUrl.trim() ? (
              <div className="w-7 h-7 rounded-lg overflow-hidden bg-white border border-slate-100 shrink-0">
                <img src={selectedBrand.logoUrl} alt={selectedBrand.name} className="w-full h-full object-contain p-0.5" />
              </div>
            ) : (
              <div className={`w-7 h-7 rounded-lg ${selectedBrand.color} flex items-center justify-center shrink-0`}>
                <span className="text-[10px] font-bold text-white">{selectedBrand.initials}</span>
              </div>
            )}
            <span className="text-sm font-semibold text-slate-800 truncate max-w-[100px] md:max-w-none">{selectedBrand.name}</span>
            {selectedBrand.isDemo && (
              <span className="text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0">Demo</span>
            )}
            <ChevronDown className={`w-3.5 h-3.5 text-slate-400 ml-1 transition-transform ${dropdownOpen ? "rotate-180" : ""}`} />
          </button>
        )}

        {dropdownOpen && brands.length > 1 && (
          <>
            <div className="fixed inset-0 z-40" onClick={() => setDropdownOpen(false)} />
            <div className="absolute top-full left-0 mt-1.5 bg-white border border-slate-200 rounded-xl shadow-lg py-1.5 z-50 min-w-[260px] max-h-[400px] overflow-y-auto">
              <div className="px-3 py-2">
                <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Switch Workspace</p>
              </div>

              {brands.length > 5 && (
                <div className="px-3 pb-2">
                  <div className="relative">
                    <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400 pointer-events-none" />
                    <input
                      ref={brandSearchRef}
                      type="text"
                      value={brandSearch}
                      onChange={(e) => setBrandSearch(e.target.value)}
                      placeholder="Search brands…"
                      className="w-full pl-8 pr-3 py-1.5 text-sm bg-slate-50 border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-400 placeholder:text-slate-400"
                    />
                  </div>
                </div>
              )}

              {brandsLoading ? (
                <div className="px-3 py-4 text-center">
                  <Loader2 className="w-4 h-4 text-brand-500 animate-spin mx-auto" />
                </div>
              ) : brands.length === 0 ? (
                <div className="px-3 py-4 text-center">
                  <p className="text-xs text-slate-400">No brands yet</p>
                </div>
              ) : filteredBrands.length === 0 ? (
                <div className="px-3 py-4 text-center">
                  <p className="text-xs text-slate-400">No brands match &ldquo;{brandSearch}&rdquo;</p>
                </div>
              ) : (
                filteredBrands.map((brand) => {
                  const isActive = brand.id === selectedBrand.id;
                  return (
                    <div
                      key={brand.id}
                      className={`flex items-center transition-colors ${isActive ? "bg-brand-50" : "hover:bg-slate-50"}`}
                    >
                      <button
                        onClick={() => { setSelectedBrand(brand); setDropdownOpen(false); }}
                        className="flex-1 flex items-center gap-2.5 px-3 py-2.5"
                      >
                        {brand.logoUrl && brand.logoUrl.trim() ? (
                          <div className="w-8 h-8 rounded-lg overflow-hidden bg-white border border-slate-100 shrink-0">
                            <img src={brand.logoUrl} alt={brand.name} className="w-full h-full object-contain p-0.5" />
                          </div>
                        ) : (
                          <div className={`w-8 h-8 rounded-lg ${brand.color} flex items-center justify-center shrink-0`}>
                            <span className="text-[11px] font-bold text-white">{brand.initials}</span>
                          </div>
                        )}
                        <div className="flex-1 text-left">
                          <div className="flex items-center gap-1.5">
                            <p className={`text-sm font-semibold ${isActive ? "text-brand-700" : "text-slate-800"}`}>{brand.name}</p>
                            {brand.isDemo && (
                              <span className="text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0">Demo</span>
                            )}
                          </div>
                          <p className="text-[11px] text-slate-400">{brand.domain}</p>
                        </div>
                        {isActive && <Check className="w-4 h-4 text-brand-600 shrink-0" />}
                      </button>
                      <Link
                        href={`/brands/${brand.id}/edit`}
                        onClick={() => setDropdownOpen(false)}
                        className="pr-3 pl-1 text-slate-400 hover:text-slate-600 transition-colors"
                        aria-label={`Edit ${brand.name}`}
                      >
                        <Pencil className="w-3.5 h-3.5" />
                      </Link>
                    </div>
                  );
                })
              )}

              <div className="border-t border-slate-100 mt-1.5 pt-1.5">
                <button
                  onClick={() => { setDropdownOpen(false); router.push("/website-upload"); }}
                  className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm text-slate-500 hover:bg-slate-50 transition-colors"
                >
                  <Plus className="w-4 h-4" />
                  Add New Website
                </button>
              </div>
            </div>
          </>
        )}
      </div>

      {/* Search / command palette */}
      <CommandSearch brands={brands} onSwitchBrand={(b) => { setSelectedBrand(b); }} />

      {/* Right side: notification center + Clerk user button */}
      <div className="flex items-center gap-3 ml-auto">
        <TaskHistoryDropdown />
        <div className="relative">
          <button
            onClick={() => setNotifOpen(!notifOpen)}
            className="relative p-2 rounded-lg hover:bg-slate-100 transition-colors"
          >
            <Bell className="w-5 h-5 text-slate-500" />
            {unreadCount > 0 && (
              <span className="absolute top-1 right-1 w-4 h-4 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center">{unreadCount}</span>
            )}
          </button>

          {notifOpen && (
            <>
              <div className="fixed inset-0 z-40" onClick={() => setNotifOpen(false)} />
              <div className="absolute top-full right-0 mt-2 w-[400px] bg-white border border-slate-200 rounded-xl shadow-xl z-50 overflow-hidden">
                {/* Header */}
                <div className="px-4 py-3 border-b border-slate-100 flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Bell className="w-4 h-4 text-slate-600" />
                    <p className="text-sm font-bold text-slate-800">Notifications</p>
                    {unreadCount > 0 && (
                      <span className="text-[10px] font-semibold text-brand-600 bg-brand-50 border border-brand-200 rounded-full px-2 py-0.5">{unreadCount} new</span>
                    )}
                  </div>
                  {unreadCount > 0 && (
                    <button onClick={markAllRead} className="text-[11px] font-semibold text-brand-600 hover:text-brand-700 transition-colors">
                      Mark all read
                    </button>
                  )}
                </div>

                {/* Filter tabs */}
                <div className="px-3 py-2 border-b border-slate-100 flex items-center gap-1 overflow-x-auto">
                  {NOTIF_FILTERS.map((f) => {
                    const count = f.key === "all" ? notifications.length
                      : f.key === "unread" ? unreadCount
                      : notifications.filter((n) => n.type === f.key).length;
                    return (
                      <button
                        key={f.key}
                        onClick={() => setNotifFilter(f.key)}
                        className={`px-2.5 py-1 rounded-md text-[10px] font-semibold transition-colors whitespace-nowrap ${
                          notifFilter === f.key
                            ? "bg-brand-600 text-white"
                            : "text-slate-500 hover:bg-slate-100"
                        }`}
                      >
                        {f.label}
                        {count > 0 && <span className={`ml-1 ${notifFilter === f.key ? "text-brand-200" : "text-slate-400"}`}>({count})</span>}
                      </button>
                    );
                  })}
                </div>

                {/* Pinned recommended action */}
                {nba && (
                  <div className="px-4 py-3 bg-amber-50/60 border-b border-amber-100">
                    <p className="text-[9px] font-bold uppercase tracking-widest text-amber-600 mb-1.5">Recommended Action</p>
                    <div className="flex items-start gap-2.5">
                      <div className="w-7 h-7 rounded-lg bg-white border border-amber-200 flex items-center justify-center shrink-0 mt-0.5">
                        <ShieldCheck className="w-3.5 h-3.5 text-amber-600" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-xs font-semibold text-slate-900">{nba.title}</p>
                        <div className="flex items-center gap-1.5 mt-1">
                          <span className="text-[9px] font-semibold text-red-700 bg-white border border-red-200 rounded-full px-1.5 py-0.5">{nba.errorCount} err</span>
                          <span className="text-[9px] font-semibold text-amber-700 bg-white border border-amber-200 rounded-full px-1.5 py-0.5">{nba.warningCount} warn</span>
                          <span className="text-[9px] font-semibold text-slate-500 bg-white border border-slate-200 rounded-full px-1.5 py-0.5">Health: {nba.crawlHealth}/100</span>
                        </div>
                        <Link
                          href="/technical-audit"
                          onClick={() => setNotifOpen(false)}
                          className="inline-flex items-center gap-1 mt-1.5 text-[10px] font-semibold text-amber-700 hover:text-amber-900 transition-colors"
                        >
                          View Audit <ArrowRight className="w-3 h-3" />
                        </Link>
                      </div>
                    </div>
                  </div>
                )}

                {/* Notification list */}
                <div className="max-h-[360px] overflow-y-auto divide-y divide-slate-100">
                  {filteredNotifs.map((n) => {
                    const cfg = NOTIF_ICONS[n.type] ?? NOTIF_ICONS.system;
                    const Icon = cfg.icon;
                    return (
                      <div key={n.id} className={`px-4 py-3 flex items-start gap-3 group transition-colors ${n.read ? "bg-white" : "bg-brand-50/30"}`}>
                        <div className={`w-8 h-8 rounded-lg ${cfg.bg} flex items-center justify-center shrink-0 mt-0.5`}>
                          <Icon className={`w-4 h-4 ${cfg.color}`} />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-1.5">
                            {!n.read && <span className="w-1.5 h-1.5 rounded-full bg-brand-500 shrink-0" />}
                            <p className={`text-xs font-semibold truncate ${n.read ? "text-slate-600" : "text-slate-900"}`}>{n.title}</p>
                          </div>
                          <p className="text-[11px] text-slate-400 mt-0.5 truncate">{n.detail}</p>
                          <div className="flex items-center gap-2 mt-1">
                            <span className="text-[10px] text-slate-300">{n.time}</span>
                            {n.action && (
                              <a
                                href={n.action.href}
                                onClick={(e) => { e.stopPropagation(); setNotifOpen(false); }}
                                className={`text-[10px] font-semibold transition-colors ${
                                  n.action.label === "Retry" ? "text-red-500 hover:text-red-700" :
                                  n.action.label === "Upgrade" ? "text-violet-600 hover:text-violet-800" :
                                  "text-brand-600 hover:text-brand-800"
                                }`}
                              >
                                {n.action.label} →
                              </a>
                            )}
                          </div>
                        </div>
                        <button
                          onClick={() => dismissNotif(n.id)}
                          className="p-1 rounded text-slate-300 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-all shrink-0"
                        >
                          <X className="w-3 h-3" />
                        </button>
                      </div>
                    );
                  })}

                  {filteredNotifs.length === 0 && (
                    <div className="px-4 py-8 text-center">
                      <CheckCircle2 className="w-6 h-6 text-slate-300 mx-auto mb-2" />
                      <p className="text-xs text-slate-400">{notifFilter === "unread" ? "No unread notifications" : notifFilter === "all" ? "All caught up!" : `No ${notifFilter} notifications`}</p>
                    </div>
                  )}
                </div>

                {/* Footer */}
                <div className="px-4 py-2.5 border-t border-slate-100 bg-slate-50/50 flex items-center justify-between">
                  <Link
                    href="/settings"
                    onClick={() => setNotifOpen(false)}
                    className="text-[11px] font-semibold text-brand-600 hover:text-brand-700 transition-colors"
                  >
                    View all notifications
                  </Link>
                  <Link
                    href="/signals"
                    onClick={() => setNotifOpen(false)}
                    className="flex items-center gap-1 text-[11px] font-semibold text-violet-600 hover:text-violet-700 transition-colors"
                  >
                    <Zap className="w-3 h-3" />
                    Signals Center
                  </Link>
                </div>
              </div>
            </>
          )}
        </div>
        <div className="pl-3 border-l border-slate-200">
          <UserButton
            
            appearance={{
              elements: {
                avatarBox: "w-8 h-8",
              },
            }}
          />
        </div>
      </div>
    </header>
  );
}

// ─── Command Search ─────────────────────────────────────────────────────────────────

const NAV_ITEMS = [
  { label: "Dashboard",             href: "/dashboard",              kw: "dashboard home overview" },
  { label: "Site Tag Analytics",    href: "/site-tag-analytics",     kw: "analytics site tag events tracking" },
  { label: "Paid Media",           href: "/paid-media",             kw: "paid media attribution ads" },
  { label: "AI Strategist",        href: "/ai-strategist",          kw: "ai strategy strategist chat" },
  { label: "Keyword Research",     href: "/keyword-research",       kw: "keyword research search" },
  { label: "Rank Tracker",         href: "/rank-tracker",           kw: "rank tracker position serp" },
  { label: "Competitor Intel",     href: "/competitors",            kw: "competitor competition intel" },
  { label: "AI Visibility",        href: "/ai-visibility",          kw: "ai visibility llmo chatgpt" },
  { label: "Backlinks",            href: "/backlinks",              kw: "backlink links referring" },
  { label: "Technical Audit",      href: "/site-performance-audit", kw: "technical audit seo performance" },
  { label: "Core Web Intelligence", href: "/core-web-intelligence", kw: "core web vitals cwv performance" },
  { label: "Broken Links",         href: "/broken-links",           kw: "broken links 404 dead" },
  { label: "Schema Generator",     href: "/schema-generator",       kw: "schema structured data json-ld" },
  { label: "Report Studio",        href: "/report-studio",          kw: "report studio generate" },
  { label: "Brands Hub",           href: "/brands-hub",             kw: "brands hub manage" },
  { label: "Industry Intel",       href: "/industry-intel",         kw: "industry intelligence" },
  { label: "Content Brief",        href: "/content-brief",          kw: "content brief seo" },
  { label: "Email Reports",        href: "/email-reports",          kw: "email reports schedule" },
  { label: "Settings",             href: "/settings",               kw: "settings account billing plan" },
  { label: "Execution Hub",        href: "/execution-hub",          kw: "execution hub tasks pipeline" },
  { label: "Signals Center",       href: "/signals",                kw: "signals center alerts" },
  { label: "Page Launch Tracker",  href: "/page-launch-tracker",    kw: "page launch tracker" },
  { label: "Writing Assistant",    href: "/writing-assistant",      kw: "writing assistant content" },
  { label: "Topic Map",            href: "/topic-map",              kw: "topic map cluster" },
];

type CmdBrand = { id: string; name: string; domain: string; initials: string; color: string; logoUrl: string | null; isDemo: boolean };

function CommandSearch({ brands, onSwitchBrand }: { brands: CmdBrand[]; onSwitchBrand: (b: CmdBrand) => void }) {
  const router = useRouter();
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  const q = query.toLowerCase().trim();
  const navResults = useMemo(() =>
    q.length < 2 ? [] : NAV_ITEMS.filter((i) => i.label.toLowerCase().includes(q) || i.kw.includes(q)).slice(0, 6),
    [q],
  );
  const brandResults = useMemo(() =>
    q.length < 2 ? [] : brands.filter((b) => b.name.toLowerCase().includes(q) || b.domain.toLowerCase().includes(q)).slice(0, 5),
    [q, brands],
  );
  const allResults = useMemo(() => [
    ...brandResults.map((b) => ({ type: "brand" as const, id: b.id, label: b.name, sub: b.domain, data: b })),
    ...navResults.map((n) => ({ type: "nav" as const, id: n.href, label: n.label, sub: n.href, data: n })),
  ], [brandResults, navResults]);

  useEffect(() => { setActive(0); }, [q]);

  useEffect(() => {
    if (!open) return;
    function onClick(e: MouseEvent) {
      if (!containerRef.current?.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, [open]);

  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        inputRef.current?.focus();
        setOpen(true);
      }
      if (e.key === "Escape") { setOpen(false); inputRef.current?.blur(); }
    }
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

  function select(item: (typeof allResults)[number]) {
    setOpen(false);
    setQuery("");
    if (item.type === "brand") onSwitchBrand(item.data as CmdBrand);
    else router.push((item.data as { href: string }).href);
  }

  function onKeyDown(e: React.KeyboardEvent) {
    if (e.key === "ArrowDown") { e.preventDefault(); setActive((a) => Math.min(a + 1, allResults.length - 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setActive((a) => Math.max(a - 1, 0)); }
    else if (e.key === "Enter" && allResults[active]) { e.preventDefault(); select(allResults[active]); }
  }

  return (
    <div ref={containerRef} className="hidden md:block flex-1 max-w-md relative">
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
        <input
          ref={inputRef}
          type="text"
          value={query}
          onChange={(e) => { setQuery(e.target.value); if (e.target.value.length >= 2) setOpen(true); }}
          onFocus={() => { if (q.length >= 2) setOpen(true); }}
          onKeyDown={onKeyDown}
          placeholder="Search brands, pages... (⌘K)"
          className="w-full pl-9 pr-16 py-2 text-sm bg-slate-100 border border-transparent rounded-lg focus:outline-none focus:border-brand-500 focus:bg-white transition-colors"
        />
        <kbd className="absolute right-3 top-1/2 -translate-y-1/2 hidden lg:inline-flex items-center gap-0.5 text-[10px] font-semibold text-slate-400 bg-white border border-slate-200 rounded px-1.5 py-0.5">
          <Command className="w-2.5 h-2.5" />K
        </kbd>
      </div>

      {open && allResults.length > 0 && (
        <div className="absolute top-full left-0 right-0 mt-1.5 bg-white border border-slate-200 rounded-xl shadow-xl z-50 max-h-80 overflow-auto py-1">
          {brandResults.length > 0 && (
            <>
              <div className="px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest text-slate-400">Brands</div>
              {brandResults.map((b, i) => {
                const idx = i;
                return (
                  <button key={b.id} onClick={() => select(allResults[idx])} onMouseEnter={() => setActive(idx)}
                    className={`w-full px-3 py-2 text-left flex items-center gap-2.5 transition-colors ${active === idx ? "bg-brand-50" : "hover:bg-slate-50"}`}>
                    {b.logoUrl && b.logoUrl.trim() ? (
                      <div className="w-6 h-6 rounded overflow-hidden bg-white border border-slate-100 shrink-0"><img src={b.logoUrl} alt="" className="w-full h-full object-contain p-0.5" /></div>
                    ) : (
                      <div className={`w-6 h-6 rounded ${b.color} flex items-center justify-center shrink-0`}><span className="text-[9px] font-bold text-white">{b.initials}</span></div>
                    )}
                    <span className="text-sm font-medium text-slate-800 truncate">{b.name}</span>
                    <span className="text-xs text-slate-400 truncate ml-auto">{b.domain}</span>
                  </button>
                );
              })}
            </>
          )}
          {navResults.length > 0 && (
            <>
              <div className="px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest text-slate-400">Pages</div>
              {navResults.map((n, i) => {
                const idx = brandResults.length + i;
                return (
                  <button key={n.href} onClick={() => select(allResults[idx])} onMouseEnter={() => setActive(idx)}
                    className={`w-full px-3 py-2 text-left flex items-center gap-2.5 transition-colors ${active === idx ? "bg-brand-50" : "hover:bg-slate-50"}`}>
                    <ArrowRight className="w-3.5 h-3.5 text-slate-400 shrink-0" />
                    <span className="text-sm font-medium text-slate-800">{n.label}</span>
                  </button>
                );
              })}
            </>
          )}
        </div>
      )}
    </div>
  );
}
