"use client";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
  LayoutDashboard, Users, KanbanSquare, CheckSquare, Inbox, Workflow, Megaphone, FileText, BarChart3, LineChart, FileStack, Plug, Sparkles,
  ShieldCheck, Settings, Search, Bell, Moon, Sun, Menu as MenuIcon, ChevronsUpDown, LogOut, Languages, Target, Layers, Upload, Calendar, Check, X, Plus, PanelLeftClose, PanelLeftOpen,
} from "lucide-react";
import { Avatar, Badge, cx, api, Menu } from "./ui";
import { Assistant } from "./assistant";
import type { TKey } from "@/lib/i18n";

type NavItem = { href: string; key: TKey; icon: ReactNode; cap?: string; badge?: number };
type Props = {
  children: ReactNode;
  user: { name: string; email: string; isAgencyAdmin: boolean };
  workspace: { id: string; name: string; plan: string };
  workspaces: { id: string; name: string }[];
  roleName: string;
  caps: Record<string, string>;
  strings: Record<TKey, string>;
  locale: string;
  unread: number;
  inboxOpen: number;
  approvals: number;
  branding: { productName: string; color?: string; logoUrl?: string };
  /** nav hrefs (and "voice") not included in the workspace plan */
  locked?: string[];
};

const GROUPS: { key: TKey; items: NavItem[] }[] = [
  { key: "crm", items: [
    { href: "/dashboard", key: "dashboard", icon: <LayoutDashboard /> },
    { href: "/contacts", key: "contacts", icon: <Users />, cap: "contacts" },
    { href: "/pipeline", key: "pipeline", icon: <KanbanSquare />, cap: "contacts" },
    { href: "/tasks", key: "tasks", icon: <CheckSquare />, cap: "contacts" },
    { href: "/segments", key: "segments", icon: <Layers />, cap: "contacts" },
  ] },
  { key: "engage", items: [
    { href: "/inbox", key: "inbox", icon: <Inbox />, cap: "messaging" },
    { href: "/journeys", key: "journeys", icon: <Workflow />, cap: "journeys" },
    { href: "/broadcasts", key: "broadcasts", icon: <Megaphone />, cap: "messaging" },
    { href: "/templates", key: "templates", icon: <FileText />, cap: "messaging" },
  ] },
  { key: "grow", items: [
    { href: "/ads", key: "ads", icon: <Target />, cap: "ads" },
    { href: "/content", key: "content", icon: <Calendar />, cap: "content" },
    { href: "/forms", key: "forms", icon: <FileStack />, cap: "contacts" },
  ] },
  { key: "measure", items: [
    { href: "/analytics", key: "analytics", icon: <BarChart3 />, cap: "reports" },
    { href: "/reports", key: "reports", icon: <LineChart />, cap: "reports" },
    { href: "/ai", key: "ai", icon: <Sparkles />, cap: "reports" },
    { href: "/ai/approvals", key: "approvals", icon: <ShieldCheck />, cap: "ai_spend" },
  ] },
  { key: "platform", items: [
    { href: "/integrations", key: "integrations", icon: <Plug />, cap: "admin" },
    { href: "/settings", key: "settings", icon: <Settings /> },
  ] },
];

export function Shell(p: Props) {
  const path = usePathname();
  const router = useRouter();
  const [mobileNav, setMobileNav] = useState(false);
  const [palette, setPalette] = useState(false);
  const [railOpen, setRailOpenState] = useState(false);
  const setRailOpen = (v: boolean) => { setRailOpenState(v); try { localStorage.setItem("tp-rail", v ? "1" : "0"); } catch { /* storage unavailable */ } };
  useEffect(() => { try { setRailOpenState(localStorage.getItem("tp-rail") === "1"); } catch { /* storage unavailable */ } }, []);
  const [theme, setTheme] = useState<"light" | "dark" | "auto">("auto");
  const s = p.strings;

  useEffect(() => {
    try { const t = localStorage.getItem("tp-theme"); if (t === "light" || t === "dark") setTheme(t); } catch { /* storage unavailable */ }
    const k = (e: KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setPalette((o) => !o); } };
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, []);
  useEffect(() => setMobileNav(false), [path]);

  const signOut = async () => { try { await api("/api/auth/logout", { method: "POST" }); } finally { window.location.href = "/login"; } };
  const accountItems = [
    { label: s.profile, icon: <ShieldCheck className="h-3.5 w-3.5" />, onClick: () => router.push("/settings/security") },
    { label: p.locale === "bn" ? "English" : "বাংলা", icon: <Languages className="h-3.5 w-3.5" />, onClick: () => setLocale(p.locale === "bn" ? "en" : "bn") },
    "sep" as const,
    { label: s.logout, icon: <LogOut className="h-3.5 w-3.5" />, danger: true, onClick: signOut },
  ];

  const cycleTheme = () => {
    const next = theme === "auto" ? "dark" : theme === "dark" ? "light" : "auto";
    setTheme(next);
    try { if (next === "auto") { localStorage.removeItem("tp-theme"); delete document.documentElement.dataset.theme; } else { localStorage.setItem("tp-theme", next); document.documentElement.dataset.theme = next; } } catch { /* ignore */ }
  };

  const groups = GROUPS.map((g) => ({ ...g, items: g.items.filter((i) => !i.cap || !!p.caps[i.cap]).map((i) => ({ ...i, badge: i.href === "/inbox" ? p.inboxOpen : i.href === "/ai/approvals" ? p.approvals : undefined })) })).filter((g) => g.items.length);
  const current = groups.flatMap((g) => g.items).filter((i) => path === i.href || path.startsWith(i.href + "/")).sort((a, b) => b.href.length - a.href.length)[0];

  const switchWs = async (id: string) => {
    await api("/api/auth/workspace", { body: { workspaceId: id } });
    window.location.href = "/dashboard";
  };
  const setLocale = async (l: string) => {
    await api("/me", { method: "PATCH", body: { locale: l } });
    router.refresh();
  };

  const navLink = (i: NavItem & { badge?: number }, expanded: boolean) => {
    const active = current?.href === i.href;
    const locked = p.locked?.includes(i.href);
    return (
      <Link key={i.href} href={locked ? `/settings/billing?upgrade=${encodeURIComponent(i.href)}` : i.href} title={expanded ? undefined : s[i.key]}
        className={cx("group relative flex items-center gap-3 rounded-[14px] transition-all duration-200", expanded ? "px-3 py-2" : "mx-auto h-10 w-10 justify-center",
          active ? "bg-brand text-white shadow-[0_8px_20px_-6px_rgb(var(--brand)/.55)]" : "text-ink-2 hover:bg-white/70 hover:text-brand dark:hover:bg-white/10")}>
        <span className="[&>svg]:h-[18px] [&>svg]:w-[18px]">{i.icon}</span>
        {expanded && <span className="flex-1 truncate text-[13px] font-medium">{s[i.key]}</span>}
        {expanded && locked && <span className="rounded-full bg-violet/15 px-1.5 text-[10px] font-semibold text-violet">PRO</span>}
        {!!i.badge && (expanded
          ? <span className={cx("rounded-full px-1.5 text-[10.5px] font-semibold", active ? "bg-white/25" : "bg-brand/10 text-brand")}>{i.badge}</span>
          : <span className="absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full bg-brand ring-2 ring-white dark:ring-panel" />)}
        {!expanded && <span className="pointer-events-none absolute left-[calc(100%+12px)] z-50 hidden whitespace-nowrap rounded-[8px] bg-ink px-2 py-1 text-[11.5px] font-medium text-white shadow-pop group-hover:block">{s[i.key]}{locked ? " · upgrade" : ""}</span>}
      </Link>
    );
  };

  const workspaceSwitcher = (
    <Menu align="left" trigger={
      <button className="flex items-center gap-2.5 rounded-[14px] px-1.5 py-1 text-left hover:bg-white/60 dark:hover:bg-white/10">
        {p.branding.logoUrl ? <img src={p.branding.logoUrl} alt="" className="h-8 w-8 rounded-[10px] object-contain" /> : <span className="grid h-8 w-8 place-items-center rounded-[10px] bg-gradient-to-br from-brand to-[#4F8BFF] text-white shadow-[0_6px_16px_-4px_rgb(var(--brand)/.6)]"><img src="/icon.svg" alt="" className="h-5 w-5 brightness-0 invert" /></span>}
        <span className="hidden min-w-0 sm:block">
          <span className="block max-w-[160px] truncate text-[14px] font-bold leading-tight">{p.branding.productName}</span>
          <span className="block max-w-[160px] truncate text-[11px] text-ink-3">{p.workspace.name}</span>
        </span>
        <ChevronsUpDown className="hidden h-3.5 w-3.5 text-ink-3 sm:block" />
      </button>
    } items={[
      ...p.workspaces.map((w) => ({ label: <span className="flex w-full items-center justify-between gap-3"><span className="truncate">{w.name}</span>{w.id === p.workspace.id && <Check className="h-3.5 w-3.5" />}</span>, onClick: () => w.id !== p.workspace.id && switchWs(w.id) })),
      ...(p.user.isAgencyAdmin ? ["sep" as const, { label: "Agency & sub-accounts", icon: <Plus className="h-3.5 w-3.5" />, onClick: () => router.push("/settings/agency") }] : []),
    ]} />
  );

  const rail = (expanded: boolean) => (
    <aside className={cx("glass-panel flex h-full flex-col rounded-[26px] py-3 transition-[width] duration-300", expanded ? "w-[236px] px-3" : "w-[68px] px-2")}>
      <div className={cx("mb-2 flex items-center", expanded ? "justify-between px-1" : "justify-center")}>
        {expanded ? <span className="text-[11px] font-semibold uppercase tracking-[.12em] text-ink-3">Menu</span> : null}
        <button onClick={() => setRailOpen(!expanded)} className="hidden h-8 w-8 place-items-center rounded-[10px] text-ink-3 hover:bg-white/70 hover:text-brand lg:grid dark:hover:bg-white/10" aria-label={expanded ? "Collapse menu" : "Expand menu"}>
          {expanded ? <PanelLeftClose className="h-4 w-4" /> : <PanelLeftOpen className="h-4 w-4" />}
        </button>
        {mobileNav && <button className="grid h-8 w-8 place-items-center rounded-[10px] lg:hidden" onClick={() => setMobileNav(false)} aria-label="Close menu"><X className="h-4 w-4" /></button>}
      </div>
      <nav className="flex-1 space-y-3 overflow-y-auto overflow-x-visible pb-2">
        {groups.map((g, gi) => (
          <div key={g.key} className="space-y-1">
            {expanded ? <div className="px-3 pb-0.5 pt-1 text-[10.5px] font-semibold uppercase tracking-[.1em] text-ink-3">{s[g.key]}</div> : gi > 0 ? <div className="mx-auto my-1.5 h-px w-6 bg-line" /> : null}
            {g.items.map((i) => navLink(i, expanded))}
          </div>
        ))}
      </nav>
      <div className={cx("mt-2 space-y-1 border-t border-white/60 pt-2 dark:border-white/10", !expanded && "flex flex-col items-center")}>
        <button onClick={() => window.dispatchEvent(new CustomEvent("assistant:open"))} title="Ask AI" className={cx("flex items-center gap-3 rounded-[14px] text-violet hover:bg-violet/10", expanded ? "w-full px-3 py-2" : "h-10 w-10 justify-center")}>
          <Sparkles className="h-[18px] w-[18px]" />{expanded && <span className="text-[13px] font-medium">Ask AI</span>}
        </button>
        <button onClick={signOut} title={s.logout} aria-label={s.logout} className={cx("flex items-center gap-3 rounded-[14px] text-ink-2 hover:bg-bad/10 hover:text-bad", expanded ? "w-full px-3 py-2" : "h-10 w-10 justify-center")}>
          <LogOut className="h-[18px] w-[18px]" />{expanded && <span className="text-[13px] font-medium">{s.logout}</span>}
        </button>
      </div>
    </aside>
  );

  const PRIMARY: { href: string; label: string; cap?: string }[] = [
    { href: "/dashboard", label: "Overview" }, { href: "/pipeline", label: "Deals", cap: "contacts" }, { href: "/contacts", label: "Accounts", cap: "contacts" },
    { href: "/inbox", label: "Inbox", cap: "messaging" }, { href: "/ads", label: "Campaigns", cap: "ads" }, { href: "/reports", label: "Reports", cap: "reports" },
  ].filter((x) => !x.cap || !!p.caps[x.cap]);
  const primaryActive = PRIMARY.filter((x) => path === x.href || path.startsWith(x.href + "/")).sort((a, b) => b.href.length - a.href.length)[0]?.href;

  return (
    <div className="app-bg relative flex h-dvh overflow-hidden" lang={p.locale}>
      <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden>
        <div className="absolute -left-40 -top-40 h-[520px] w-[520px] rounded-full bg-[#3B82F6]/20 blur-[110px]" />
        <div className="absolute -right-32 top-1/3 h-[460px] w-[460px] rounded-full bg-[#818CF8]/20 blur-[110px]" />
        <div className="absolute bottom-[-180px] left-1/3 h-[420px] w-[420px] rounded-full bg-[#38BDF8]/15 blur-[110px]" />
      </div>
      <div className="relative z-10 hidden p-3 pr-0 lg:block">{rail(railOpen)}</div>
      {mobileNav && <div className="fixed inset-0 z-[60] flex lg:hidden"><div className="animate-sheet p-3">{rail(true)}</div><div className="flex-1 bg-black/25 backdrop-blur-sm" onClick={() => setMobileNav(false)} /></div>}
      <div className="relative z-10 flex min-w-0 flex-1 flex-col">
        <header className="glass-panel sticky top-0 z-40 mx-3 mt-3 flex h-[60px] shrink-0 items-center gap-2 rounded-[22px] px-2.5 sm:px-3">
          <button className="grid h-9 w-9 place-items-center rounded-[12px] hover:bg-white/70 lg:hidden dark:hover:bg-white/10" onClick={() => setMobileNav(true)} aria-label="Open menu"><MenuIcon className="h-4 w-4" /></button>
          {workspaceSwitcher}
          <nav className="mx-auto hidden items-center gap-1 rounded-full bg-white/55 p-1 shadow-[inset_0_0_0_1px_rgb(255_255_255/.7)] md:flex dark:bg-white/5 dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/.08)]" aria-label="Primary">
            {PRIMARY.map((x) => (
              <Link key={x.href} href={x.href} className={cx("rounded-full px-4 py-1.5 text-[13px] font-medium transition-all duration-200", primaryActive === x.href ? "bg-ink text-white shadow-[0_6px_16px_-6px_rgb(0_0_0/.45)] dark:bg-white dark:text-ink" : "text-ink-2 hover:bg-white hover:text-ink dark:hover:bg-white/10")}>{x.label}</Link>
            ))}
          </nav>
          <div className="ml-auto flex items-center gap-1 md:ml-0">
            <button onClick={() => setPalette(true)} className="grid h-9 w-9 place-items-center rounded-full border border-white/70 bg-white/60 text-ink-2 hover:text-brand dark:border-white/10 dark:bg-white/5" aria-label={s.search} title={`${s.search} (⌘K)`}><Search className="h-4 w-4" /></button>
            <button onClick={cycleTheme} className="hidden h-9 w-9 place-items-center rounded-full border border-white/70 bg-white/60 text-ink-2 hover:text-brand sm:grid dark:border-white/10 dark:bg-white/5" title={`Theme: ${theme}`} aria-label="Toggle theme">{theme === "dark" ? <Moon className="h-4 w-4" /> : theme === "light" ? <Sun className="h-4 w-4" /> : <span className="text-[9px] font-bold">AUTO</span>}</button>
            <Notifications initialUnread={p.unread} title={s.notifications} markAll={s.markAllRead} />
            <Menu trigger={
              <button className="flex items-center gap-2 rounded-full py-0.5 pl-0.5 pr-0.5 hover:bg-white/60 sm:pr-3 dark:hover:bg-white/10" aria-label="Account menu">
                <Avatar name={p.user.name} size={34} />
                <span className="hidden text-left lg:block"><span className="block max-w-[140px] truncate text-[12.5px] font-semibold leading-tight">{p.user.name}</span><span className="block max-w-[140px] truncate text-[11px] text-ink-3">{p.user.email}</span></span>
              </button>
            } items={[{ label: <span className="block"><span className="block font-medium">{p.user.name}</span><span className="block text-[11px] text-ink-3">{p.roleName} · {p.workspace.plan}</span></span>, onClick: () => router.push("/settings/security") }, "sep", ...accountItems]} />
          </div>
        </header>
        <nav className="no-scrollbar mx-3 mt-2 flex gap-1 overflow-x-auto md:hidden" aria-label="Primary">
          {PRIMARY.map((x) => <Link key={x.href} href={x.href} className={cx("shrink-0 rounded-full px-3.5 py-1.5 text-[12.5px] font-medium", primaryActive === x.href ? "bg-ink text-white" : "glass-panel text-ink-2")}>{x.label}</Link>)}
        </nav>
        <main className="min-h-0 flex-1 overflow-y-auto">
          <div className="mx-auto w-full max-w-[1520px] px-3 py-5 sm:px-5 lg:px-7">{p.children}</div>
        </main>
      </div>
      {palette && <Palette onClose={() => setPalette(false)} groups={groups} strings={s} />}
      <Assistant voice={!p.locked?.includes("voice")} />
    </div>
  );
}

function Notifications({ initialUnread, title, markAll }: { initialUnread: number; title: string; markAll: string }) {
  const [open, setOpen] = useState(false);
  const [items, setItems] = useState<any[]>([]);
  const [unread, setUnread] = useState(initialUnread);
  const ref = useRef<HTMLDivElement>(null);
  const load = async () => { const r = await api("/notifications"); setItems(r.data); setUnread(r.unread); };
  useEffect(() => {
    const id = setInterval(() => api("/notifications?limit=1").then((r) => setUnread(r.unread)).catch(() => {}), 30000);
    const h = (e: MouseEvent) => ref.current && !ref.current.contains(e.target as Node) && setOpen(false);
    document.addEventListener("mousedown", h);
    return () => { clearInterval(id); document.removeEventListener("mousedown", h); };
  }, []);
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => { setOpen(!open); if (!open) load(); }} className="relative grid h-9 w-9 place-items-center rounded-full border border-white/70 bg-white/60 text-ink-2 hover:text-brand dark:border-white/10 dark:bg-white/5" aria-label={title}>
        <Bell className="h-4 w-4" />
        {unread > 0 && <span className="absolute right-1 top-1 grid h-4 min-w-4 place-items-center rounded-full bg-brand px-1 text-[9.5px] font-bold text-white">{unread > 99 ? "99+" : unread}</span>}
      </button>
      {open && (
        <div className="glass-panel absolute right-0 z-50 mt-2 w-[360px] max-w-[calc(100vw-24px)] animate-pop overflow-hidden rounded-[12px] shadow-pop">
          <div className="flex items-center justify-between border-b border-line/70 px-3.5 py-2.5"><span className="text-[13px] font-semibold">{title}</span>
            <button className="text-[12px] text-brand hover:underline" onClick={async () => { await api("/notifications", { method: "POST", body: { all: true } }); load(); }}>{markAll}</button></div>
          <div className="max-h-[420px] overflow-y-auto">
            {!items.length && <p className="px-4 py-8 text-center text-[12.5px] text-ink-3">You’re all caught up.</p>}
            {items.map((n) => (
              <Link key={n.id} href={n.link ?? "#"} onClick={() => { setOpen(false); api("/notifications", { method: "POST", body: { ids: [n.id] } }); }} className={cx("block border-b border-line/50 px-3.5 py-2.5 hover:bg-brand/5", !n.readAt && "bg-brand/[.04]")}>
                <div className="flex items-start gap-2">{!n.readAt && <span className="mt-1.5 h-2 w-2 shrink-0 rounded-full bg-brand" />}
                  <div className="min-w-0"><p className="truncate text-[12.5px] font-medium">{n.title}</p>{n.body && <p className="line-clamp-2 text-[12px] text-ink-3">{n.body}</p>}<p className="mt-0.5 text-[10.5px] text-ink-3">{new Date(n.createdAt).toLocaleString()}</p></div></div>
              </Link>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

/** Spotlight-style command palette */
function Palette({ onClose, groups, strings }: { onClose: () => void; groups: { items: NavItem[] }[]; strings: Record<TKey, string> }) {
  const router = useRouter();
  const [q, setQ] = useState("");
  const [results, setResults] = useState<{ id: string; title: string; sub?: string; href: string; kind: string }[]>([]);
  const [idx, setIdx] = useState(0);
  const pages = useMemo(() => groups.flatMap((g) => g.items).map((i) => ({ id: i.href, title: strings[i.key], href: i.href, kind: "Page" })), [groups, strings]);
  const actions = [
    { id: "a-lead", title: "Add a new lead", href: "/contacts?new=1", kind: "Action" },
    { id: "a-import", title: "Import contacts (CSV / XLSX)", href: "/contacts/import", kind: "Action" },
    { id: "a-journey", title: "Create a journey", href: "/journeys?new=1", kind: "Action" },
    { id: "a-ask", title: "Ask your data", href: "/ai?tab=ask", kind: "Action" },
    { id: "a-gen", title: "Generate ad copy with AI", href: "/ai?tab=generate", kind: "Action" },
  ];
  useEffect(() => {
    const t = setTimeout(async () => {
      const ql = q.toLowerCase();
      const local = [...pages, ...actions].filter((x) => !q || x.title.toLowerCase().includes(ql));
      let remote: typeof results = [];
      if (q.length >= 2) {
        try { remote = (await api(`/search?q=${encodeURIComponent(q)}`)).data; } catch { /* ignore */ }
      }
      setResults([...remote, ...local].slice(0, 12));
      setIdx(0);
    }, 140);
    return () => clearTimeout(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [q]);
  const go = (href: string) => { onClose(); router.push(href); };
  return (
    <div className="fixed inset-0 z-[85] flex items-start justify-center bg-black/20 px-4 pt-[14vh] animate-fade" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="glass w-full max-w-[620px] animate-sheet overflow-hidden rounded-[14px] shadow-window">
        <div className="flex items-center gap-3 border-b border-line/70 px-4">
          <Search className="h-5 w-5 text-ink-3" />
          <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder={strings.searchHint}
            onKeyDown={(e) => {
              if (e.key === "Escape") onClose();
              if (e.key === "ArrowDown") { e.preventDefault(); setIdx((i) => Math.min(i + 1, results.length - 1)); }
              if (e.key === "ArrowUp") { e.preventDefault(); setIdx((i) => Math.max(i - 1, 0)); }
              if (e.key === "Enter" && results[idx]) go(results[idx]!.href);
            }}
            className="h-14 flex-1 bg-transparent text-[17px] outline-none placeholder:text-ink-3" />
        </div>
        <div className="max-h-[400px] overflow-y-auto p-1.5">
          {results.map((r, i) => (
            <button key={r.id + i} onMouseEnter={() => setIdx(i)} onClick={() => go(r.href)} className={cx("flex w-full items-center gap-3 rounded-[8px] px-3 py-2 text-left", i === idx ? "bg-brand text-white" : "")}>
              <span className="min-w-0 flex-1"><span className="block truncate text-[13.5px]">{r.title}</span>{r.sub && <span className={cx("block truncate text-[11.5px]", i === idx ? "text-white/80" : "text-ink-3")}>{r.sub}</span>}</span>
              <Badge tone={i === idx ? "gray" : "gray"} className={i === idx ? "bg-white/20 text-white" : ""}>{r.kind}</Badge>
            </button>
          ))}
          {!results.length && <p className="px-3 py-6 text-center text-[13px] text-ink-3">No results</p>}
        </div>
      </div>
    </div>
  );
}

