"use client";
/**
 * Unified inbox (MSG-005 + Module 11): DMs, comment threads and Google reviews in one place.
 * Filter rail · list with SLA timers · thread with post/ad context and quick actions · contact card.
 * Responsive down to 375px; keyboard: j/k move, r reply, e resolve, a assign to me, s suggest, Esc back.
 */
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
  AlertTriangle, ArrowLeft, Ban, Bot, CheckCheck, Clock, EyeOff, Eye, FileText, Filter, Heart, Inbox as InboxIcon, Keyboard, Lock, Megaphone, MessageCircle,
  MoreHorizontal, RefreshCw, Search, Send, Sparkles, StickyNote, Trash2, UserPlus, X, ExternalLink, Phone, Settings2, ShieldCheck, BookOpen, BarChart3, Wand2,
} from "lucide-react";
import { Avatar, Badge, Button, Checkbox, Empty, Input, Menu, Segmented, Select, Sheet, Spinner, Toggle, api, cx, useAction, useUI } from "@/components/ui";
import { ago, fmtDate, moneyShort, useApi, useDebounced } from "@/components/hooks";
import { CHANNEL_LABEL, ChannelBadge, INTENTS, KindIcon, SentimentDot, SlaChip, Stars, intentLabel } from "@/components/social";

type Conv = {
  id: string; channel: string; kind: string; status: string; priority: string; sentiment: string | null; intent: string | null; tags: string[]; assigneeId: string | null; lastMessageAt: string; unread: number; aiAgentActive: boolean;
  slaDueAt: string | null; slaBreachedAt: string | null; firstResponseAt: string | null; snoozedUntil: string | null;
  contact: { id: string; name: string; phones: string[] }; last: { body: string; direction: string } | null;
  object: { id: string; type: string; thumbnailUrl: string | null; captionExcerpt: string | null; campaignName: string | null } | null; account: { id: string; name: string; platform: string } | null;
};
type Team = { data: { id: string; name: string }[]; perms: Record<string, string>; me: string; timezone: string; currency: string };
type Counts = Record<"open" | "mine" | "unassigned" | "unanswered" | "breached" | "comments" | "reviews" | "dms" | "negative" | "snoozed", number>;

const VIEWS: { key: string; label: string; icon: ReactNode; count?: keyof Counts; f: Record<string, string> }[] = [
  { key: "open", label: "All open", icon: <InboxIcon />, count: "open", f: { status: "active" } },
  { key: "mine", label: "Assigned to me", icon: <UserPlus />, count: "mine", f: { status: "active", assignee: "me" } },
  { key: "unassigned", label: "Unassigned", icon: <MessageCircle />, count: "unassigned", f: { status: "active", assignee: "unassigned" } },
  { key: "unanswered", label: "Unanswered", icon: <Clock />, count: "unanswered", f: { unanswered: "true" } },
  { key: "breached", label: "SLA breached", icon: <AlertTriangle />, count: "breached", f: { status: "active", sla: "breached" } },
  { key: "negative", label: "Negative", icon: <Ban />, count: "negative", f: { status: "active", sentiment: "negative" } },
  { key: "snoozed", label: "Snoozed", icon: <Clock />, count: "snoozed", f: { status: "snoozed" } },
  { key: "resolved", label: "Resolved", icon: <CheckCheck />, f: { status: "resolved" } },
  { key: "all", label: "Everything", icon: <InboxIcon />, f: {} },
];
const KINDS = [{ v: "", l: "All types" }, { v: "dm", l: "Messages" }, { v: "comment_thread", l: "Comments" }, { v: "review", l: "Reviews" }];
const CHANNELS = ["whatsapp", "messenger", "instagram", "sms", "email", "facebook_comment", "instagram_comment", "youtube", "tiktok", "linkedin", "google_review"];

export default function InboxPage() {
  return <Suspense fallback={<div className="grid h-60 place-items-center"><Spinner /></div>}><Inbox /></Suspense>;
}

function Inbox() {
  const sp = useSearchParams();
  const [view, setView] = useState(sp.get("view") ?? "open");
  const [kind, setKind] = useState(sp.get("kind") ?? "");
  const [channel, setChannel] = useState("");
  const [account, setAccount] = useState("");
  const [intent, setIntent] = useState("");
  const [tag, setTag] = useState("");
  const [object, setObject] = useState(sp.get("object") ?? "");
  const [q, setQ] = useState("");
  const dq = useDebounced(q);
  const [active, setActive] = useState<string | null>(sp.get("c"));
  const [selected, setSelected] = useState<string[]>([]);
  const [filtersOpen, setFiltersOpen] = useState(false);
  const [help, setHelp] = useState(false);
  const { push } = useUI();
  const { busy, run } = useAction();

  const f = { ...(VIEWS.find((v) => v.key === view)?.f ?? {}), ...(kind ? { kind } : {}), ...(channel ? { channel } : {}), ...(account ? { account } : {}), ...(intent ? { intent } : {}), ...(tag ? { tag } : {}), ...(object ? { object } : {}) };
  const qs = new URLSearchParams({ ...Object.fromEntries(Object.entries(f).map(([k, v]) => [`filter[${k}]`, v])), ...(dq ? { q: dq } : {}) }).toString();
  const list = useApi<{ data: Conv[] }>(`/conversations?${qs}`, [qs]);
  const counts = useApi<{ data: Counts }>("/inbox/counts");
  const team = useApi<Team>("/team");
  const accounts = useApi<{ data: { id: string; name: string; platform: string; status: string }[] }>(team.data && team.data.perms.social && team.data.perms.social !== "" ? "/social/accounts" : null, [team.data?.perms.social]);
  const socialOn = !!team.data?.perms.social;
  const canAssign = team.data?.perms.messaging === "C" || team.data?.perms.social === "C";
  const canModerate = team.data?.perms.social_moderate === "C";
  const rows = list.data?.data ?? [];

  // keep the latest reloaders in a ref so the SSE connection is opened once, not on every render
  const reloaders = useRef({ list: list.reload, counts: counts.reload });
  reloaders.current = { list: list.reload, counts: counts.reload };
  const refresh = useCallback(() => { reloaders.current.list(); reloaders.current.counts(); }, []);
  // live updates via SSE, with a polling fallback
  useEffect(() => {
    let es: EventSource | null = null;
    let since = Date.now();
    let stop = false;
    const open = () => {
      if (stop || typeof EventSource === "undefined") return;
      es = new EventSource(`/api/inbox/stream?since=${since}`);
      es.addEventListener("conversations", () => { since = Date.now(); refresh(); window.dispatchEvent(new CustomEvent("inbox:changed")); });
      es.addEventListener("reconnect", (e) => { try { since = JSON.parse((e as MessageEvent).data).since; } catch { /* keep */ } es?.close(); setTimeout(open, 500); });
      es.onerror = () => { es?.close(); if (!stop) setTimeout(open, 10000); };
    };
    open();
    const poll = setInterval(refresh, 60000);
    return () => { stop = true; es?.close(); clearInterval(poll); };
  }, [refresh]);

  // keyboard shortcuts (SOC-UI)
  const activeIdx = rows.findIndex((r) => r.id === active);
  useEffect(() => {
    const h = (e: KeyboardEvent) => {
      const t = e.target as HTMLElement;
      if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.tagName === "SELECT" || t.isContentEditable)) { if (e.key === "Escape") t.blur(); return; }
      if (e.metaKey || e.ctrlKey || e.altKey) return;
      if (e.key === "j" || e.key === "ArrowDown") { const n = rows[Math.min(rows.length - 1, activeIdx + 1)]; if (n) { setActive(n.id); e.preventDefault(); } }
      else if (e.key === "k" || e.key === "ArrowUp") { const n = rows[Math.max(0, activeIdx - 1)]; if (n) { setActive(n.id); e.preventDefault(); } }
      else if (e.key === "Escape") setActive(null);
      else if (e.key === "?") setHelp(true);
      else if (active && ["r", "e", "a", "s", "n"].includes(e.key)) { window.dispatchEvent(new CustomEvent("inbox:key", { detail: e.key })); e.preventDefault(); }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [rows, activeIdx, active]);

  const bulk = (action: string, extra: Record<string, unknown> = {}) => run(async () => {
    const r = await api<{ ok: number; failed: number; data: { ok: boolean; error?: string }[] }>("/conversations/bulk", { body: { ids: selected, action, ...extra } });
    push(r.failed ? "error" : "ok", `${r.ok} updated${r.failed ? ` · ${r.failed} failed (${r.data.find((x) => !x.ok)?.error})` : ""}`);
    setSelected([]); refresh();
  });

  const rail = (
    <nav className="space-y-4 text-[13px]" aria-label="Inbox filters">
      <ul className="space-y-0.5">
        {VIEWS.map((v) => (
          <li key={v.key}><button onClick={() => { setView(v.key); setFiltersOpen(false); }} className={cx("flex w-full items-center gap-2 rounded-[7px] px-2 py-1.5 text-left [&>svg]:h-3.5 [&>svg]:w-3.5", view === v.key ? "bg-brand/10 font-semibold text-brand" : "hover:bg-sunken")}>
            {v.icon}<span className="flex-1">{v.label}</span>{v.count && counts.data?.data?.[v.count] ? <span className={cx("text-[11px] tabular-nums", v.key === "breached" ? "font-bold text-bad" : "text-ink-3")}>{counts.data.data[v.count]}</span> : null}
          </button></li>
        ))}
      </ul>
      {socialOn && <div>
        <div className="mb-1 px-2 text-[11px] font-semibold uppercase tracking-wide text-ink-3">Type</div>
        <ul className="space-y-0.5">{KINDS.map((k) => <li key={k.v}><button onClick={() => setKind(k.v)} className={cx("flex w-full items-center gap-2 rounded-[7px] px-2 py-1.5 text-left", kind === k.v ? "bg-sunken font-semibold" : "hover:bg-sunken")}>{k.v && <KindIcon kind={k.v} className="text-ink-3" />}<span className="flex-1">{k.l}</span>{k.v && counts.data?.data ? <span className="text-[11px] text-ink-3">{counts.data.data[k.v === "dm" ? "dms" : k.v === "review" ? "reviews" : "comments"]}</span> : null}</button></li>)}</ul>
      </div>}
      <div className="space-y-2 px-1">
        <Select value={channel} onChange={(e) => setChannel(e.target.value)} aria-label="Channel"><option value="">All channels</option>{CHANNELS.filter((c) => socialOn || ["whatsapp", "messenger", "instagram", "sms", "email"].includes(c)).map((c) => <option key={c} value={c}>{CHANNEL_LABEL[c]}</option>)}</Select>
        {socialOn && (accounts.data?.data.length ?? 0) > 0 && <Select value={account} onChange={(e) => setAccount(e.target.value)} aria-label="Account"><option value="">All accounts</option>{accounts.data!.data.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}</Select>}
        <Select value={intent} onChange={(e) => setIntent(e.target.value)} aria-label="Intent"><option value="">Any intent</option>{INTENTS.map((i) => <option key={i} value={i}>{intentLabel(i)}</option>)}</Select>
        <Input placeholder="Tag" value={tag} onChange={(e) => setTag(e.target.value.trim())} aria-label="Tag" />
        {object && <button onClick={() => setObject("")} className="flex w-full items-center gap-1 rounded-[7px] bg-violet/10 px-2 py-1 text-[12px] text-violet"><Megaphone className="h-3 w-3" />One post / ad <X className="ml-auto h-3 w-3" /></button>}
      </div>
      {socialOn && <div className="space-y-0.5 border-t border-line/70 pt-3">
        {[{ h: "/inbox/rules", l: "Engagement rules", i: <Wand2 /> }, { h: "/inbox/moderation", l: "Moderation log", i: <ShieldCheck /> }, { h: "/inbox/knowledge", l: "Knowledge base", i: <BookOpen /> }, { h: "/inbox/analytics", l: "Engagement analytics", i: <BarChart3 /> }, { h: "/settings/social", l: "Social settings", i: <Settings2 /> }].map((x) => (
          <Link key={x.h} href={x.h} className="flex items-center gap-2 rounded-[7px] px-2 py-1.5 text-ink-2 hover:bg-sunken [&>svg]:h-3.5 [&>svg]:w-3.5">{x.i}{x.l}</Link>
        ))}
      </div>}
    </nav>
  );

  return (
    <div className="-mx-4 -my-5 flex h-[calc(100dvh-52px)] sm:-mx-6 lg:-mx-8">
      <aside className="hidden w-[210px] shrink-0 overflow-y-auto border-r border-line bg-panel/60 p-3 xl:block">{rail}</aside>
      <Sheet open={filtersOpen} onClose={() => setFiltersOpen(false)} title="Filters" width={320}>{rail}</Sheet>
      <Sheet open={help} onClose={() => setHelp(false)} title="Keyboard shortcuts" width={360}>
        <ul className="space-y-2 text-[13px]">{[["j / k", "Next / previous conversation"], ["r", "Focus the reply box"], ["e", "Resolve"], ["a", "Assign to me"], ["s", "AI reply suggestions"], ["n", "Internal note"], ["/", "Saved replies (in the reply box)"], ["⌘ / Ctrl + Enter", "Send"], ["Esc", "Back to the list"]].map(([k, d]) => <li key={k} className="flex justify-between gap-3"><kbd className="rounded border border-line bg-sunken px-1.5 font-mono text-[12px]">{k}</kbd><span className="text-ink-2">{d}</span></li>)}</ul>
      </Sheet>

      {/* list */}
      <div className={cx("flex w-full min-w-0 flex-col border-r border-line bg-panel md:w-[360px] md:shrink-0", active && "hidden md:flex")}>
        <div className="space-y-2 border-b border-line/70 p-3">
          <div className="flex items-center gap-2">
            <h1 className="text-[18px] font-bold">Inbox</h1>
            <span className="text-[12px] text-ink-3">{VIEWS.find((v) => v.key === view)?.label}</span>
            <div className="ml-auto flex items-center gap-1">
              <button className="rounded-[7px] p-1.5 hover:bg-sunken xl:hidden" onClick={() => setFiltersOpen(true)} aria-label="Filters"><Filter className="h-4 w-4" /></button>
              <button className="rounded-[7px] p-1.5 hover:bg-sunken" onClick={refresh} aria-label="Refresh"><RefreshCw className={cx("h-4 w-4", list.loading && "animate-spin")} /></button>
              <button className="hidden rounded-[7px] p-1.5 hover:bg-sunken sm:block" onClick={() => setHelp(true)} aria-label="Keyboard shortcuts"><Keyboard className="h-4 w-4" /></button>
            </div>
          </div>
          <div className="relative"><Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-ink-3" /><Input className="pl-8" placeholder="Search name or phone" value={q} onChange={(e) => setQ(e.target.value)} /></div>
          {socialOn && <div className="xl:hidden"><Segmented size="sm" value={kind} onChange={setKind} options={KINDS.map((k) => ({ value: k.v, label: k.l.replace("All types", "All") }))} /></div>}
          {selected.length > 0 && (
            <div className="flex flex-wrap items-center gap-1.5 rounded-[8px] bg-brand/8 px-2 py-1.5 text-[12px]">
              <b>{selected.length} selected</b>
              <Button size="sm" loading={busy} onClick={() => bulk("resolve")}>Resolve</Button>
              {canAssign && <Button size="sm" onClick={() => bulk("assign", { user_id: team.data?.me })}>Assign me</Button>}
              <Button size="sm" onClick={() => bulk("snooze", { until: new Date(Date.now() + 4 * 3600000).toISOString() })}>Snooze 4h</Button>
              {canModerate && <Menu trigger={<Button size="sm" icon={<MoreHorizontal className="h-3.5 w-3.5" />} aria-label="More" />} items={[{ label: "Hide comments", onClick: () => bulk("hide") }, { label: "Mark spam", onClick: () => bulk("mark_spam"), danger: true }, { label: "Reopen", onClick: () => bulk("open") }]} />}
              <button className="ml-auto" onClick={() => setSelected([])} aria-label="Clear selection"><X className="h-3.5 w-3.5" /></button>
            </div>
          )}
        </div>
        <ul className="flex-1 overflow-y-auto">
          {list.loading && !list.data && <li className="flex justify-center py-8"><Spinner /></li>}
          {list.error && <li className="p-4 text-[13px] text-bad">{list.error}</li>}
          {rows.map((c) => {
            const on = active === c.id;
            return (
              <li key={c.id} className={cx("group flex border-b border-line/50", on ? "bg-brand text-white" : "hover:bg-sunken")}>
                <label className={cx("flex items-start pl-2.5 pt-3.5", selected.length ? "" : "opacity-0 group-hover:opacity-100 max-md:opacity-100")} onClick={(e) => e.stopPropagation()}>
                  <input type="checkbox" className="h-3.5 w-3.5 accent-brand" checked={selected.includes(c.id)} onChange={(e) => setSelected((s) => e.target.checked ? [...s, c.id] : s.filter((x) => x !== c.id))} aria-label={`Select ${c.contact.name}`} />
                </label>
                <button onClick={() => setActive(c.id)} className="flex min-w-0 flex-1 gap-2.5 px-2.5 py-2.5 text-left">
                  <div className="relative shrink-0">
                    {c.object?.thumbnailUrl ? <img src={c.object.thumbnailUrl} alt="" className="h-9 w-9 rounded-[8px] object-cover" /> : <Avatar name={c.contact.name} size={36} />}
                    <span className={cx("absolute -bottom-1 -right-1 grid h-4 w-4 place-items-center rounded-full ring-2", on ? "bg-white text-brand ring-brand" : "bg-panel text-ink-2 ring-panel")}><KindIcon kind={c.kind} className="h-2.5 w-2.5" /></span>
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-1.5">
                      {c.priority !== "normal" && c.priority !== "low" && <span className={cx("h-1.5 w-1.5 shrink-0 rounded-full", c.priority === "urgent" ? "bg-bad" : "bg-warn")} title={`${c.priority} priority`} />}
                      <span className="truncate text-[13px] font-semibold">{c.contact.name}</span>
                      {c.aiAgentActive && <Bot className="h-3.5 w-3.5 shrink-0" />}
                      <span className={cx("ml-auto shrink-0 text-[11px]", on ? "text-white/80" : "text-ink-3")}>{ago(c.lastMessageAt)}</span>
                    </div>
                    <div className={cx("truncate text-[12px]", on ? "text-white/85" : "text-ink-3")}>{c.last ? `${c.last.direction === "out" ? "You: " : ""}${c.last.body}` : "No messages"}</div>
                    <div className="mt-1 flex flex-wrap items-center gap-1">
                      <ChannelBadge channel={c.channel} className={on ? "bg-white/20 text-white" : ""} />
                      {c.object?.type === "ad" && <Badge tone="violet" className={on ? "bg-white/20 text-white" : ""}>Ad</Badge>}
                      {c.intent && c.intent !== "other" && <span className={cx("text-[10.5px]", on ? "text-white/80" : "text-ink-3")}>{intentLabel(c.intent)}</span>}
                      <SentimentDot s={c.sentiment} />
                      <span className="ml-auto flex items-center gap-1">
                        {c.status === "snoozed" && <Clock className="h-3 w-3" />}
                        <SlaChip due={c.slaDueAt} breached={c.slaBreachedAt} responded={c.firstResponseAt} compact />
                        {c.unread > 0 && <span className={cx("grid h-4 min-w-4 place-items-center rounded-full px-1 text-[10px] font-bold", on ? "bg-white text-brand" : "bg-brand text-white")}>{c.unread}</span>}
                      </span>
                    </div>
                  </div>
                </button>
              </li>
            );
          })}
          {list.data && !rows.length && <Empty title="Inbox zero" icon={<InboxIcon className="h-5 w-5" />}>Nothing matches these filters.</Empty>}
        </ul>
      </div>

      {/* thread */}
      <div className={cx("min-w-0 flex-1", !active && "hidden md:block")}>
        {active ? <Thread key={active} id={active} team={team.data} canAssign={canAssign} canModerate={canModerate} onBack={() => setActive(null)} onChange={refresh} />
          : <div className="grid h-full place-items-center p-6"><Empty title="Select a conversation" icon={<InboxIcon className="h-5 w-5" />}>WhatsApp, Messenger, Instagram, SMS, email, Facebook &amp; Instagram comments, YouTube, TikTok, LinkedIn and Google reviews — one inbox for the whole team. Press <kbd className="rounded border border-line px-1">?</kbd> for shortcuts.</Empty></div>}
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */

function Thread({ id, team, canAssign, canModerate, onBack, onChange }: { id: string; team: Team | null; canAssign: boolean; canModerate: boolean; onBack: () => void; onChange: () => void }) {
  const t = useApi<{ data: any }>(`/conversations/${id}`, [id]);
  const conv = t.data?.data;
  const isDm = conv?.kind === "dm";
  const isComment = conv?.kind === "comment_thread";
  const isReview = conv?.kind === "review";
  const tpls = useApi<{ data: any[] }>(conv && isDm ? `/templates?channel=${conv.channel}` : null, [conv?.channel, isDm]);
  const saved = useApi<{ data: { id: string; shortcut: string; title: string | null; body: string }[] }>(conv ? `/saved-replies?filter[channel]=${conv.channel}` : null, [conv?.channel]);
  const [text, setText] = useState("");
  const [mode, setMode] = useState<"reply" | "private" | "note">("reply");
  const [target, setTarget] = useState<string | null>(null); // comment being replied to
  const [templateId, setTemplateId] = useState("");
  const [subject, setSubject] = useState("");
  const [ai, setAi] = useState<{ suggestions: { text: string; confidence: number; reason?: string; publicSafe: boolean }[]; source: string } | null>(null);
  const [aiBusy, setAiBusy] = useState(false);
  const [snoozeOpen, setSnoozeOpen] = useState(false);
  const [contactOpen, setContactOpen] = useState(false);
  const { busy, run } = useAction();
  const { push } = useUI();
  const end = useRef<HTMLDivElement>(null);
  const box = useRef<HTMLTextAreaElement>(null);
  const lastLock = useRef(0);
  const tz = team?.timezone;

  useEffect(() => { end.current?.scrollIntoView({ block: "end" }); }, [t.data]);
  const reloadThread = t.reload;
  useEffect(() => { const h = () => reloadThread(); window.addEventListener("inbox:changed", h); return () => window.removeEventListener("inbox:changed", h); }, [reloadThread]);
  useEffect(() => () => { api(`/conversations/${id}/lock`, { body: { release: true } }).catch(() => {}); }, [id]);
  // default reply target = latest inbound comment
  useEffect(() => { if (isComment && !target) { const last = [...(conv?.comments ?? [])].reverse().find((c: any) => c.direction === "inbound" && !c.isDeleted); if (last) setTarget(last.id); } }, [isComment, conv, target]);
  useEffect(() => { if (isReview && conv?.review?.replyBody && conv.review.replyStatus !== "published" && !text) setText(conv.review.replyBody); }, [isReview, conv]); // eslint-disable-line react-hooks/exhaustive-deps

  const lock = (force = false) => {
    if (!force && Date.now() - lastLock.current < 60000) return;
    lastLock.current = Date.now();
    api<{ data: { locked: boolean; heldBy?: { name: string } } }>(`/conversations/${id}/lock`, { body: { force } }).then((r) => { if (!r.data.locked && r.data.heldBy) push("error", `${r.data.heldBy.name} is replying to this right now`); else if (force) t.reload(); }).catch(() => {});
  };
  const update = async (body: Record<string, unknown>, ok: string) => { try { await api(`/conversations/${id}`, { method: "PATCH", body }); push("ok", ok); t.reload(); onChange(); } catch (e) { push("error", (e as Error).message); } };
  const post = async (path: string, body: Record<string, unknown> = {}, ok?: string) => { try { const r = await api(path, { body }); if (ok) push("ok", ok); t.reload(); onChange(); return r; } catch (e) { push("error", (e as Error).message); return null; } };
  const suggest = async () => {
    setAiBusy(true);
    try { const r = await api<{ data: any }>("/ai/suggest-reply", { body: { conversation_id: id, mode: isDm || mode === "private" ? "private" : "public" } }); setAi(r.data); } catch (e) { push("error", (e as Error).message); } finally { setAiBusy(false); }
  };

  // keyboard actions from the list
  useEffect(() => {
    const h = (e: Event) => {
      const k = (e as CustomEvent).detail;
      if (k === "r") { setMode("reply"); box.current?.focus(); }
      else if (k === "n") { setMode("note"); box.current?.focus(); }
      else if (k === "e") post(`/conversations/${id}/status`, { status: "resolved" }, "Resolved");
      else if (k === "a" && team?.me) post(`/conversations/${id}/assign`, { user_id: team.me }, "Assigned to you");
      else if (k === "s") suggest();
    };
    window.addEventListener("inbox:key", h);
    return () => window.removeEventListener("inbox:key", h);
  }); // eslint-disable-line react-hooks/exhaustive-deps

  const savedMatches = useMemo(() => (text.startsWith("/") ? (saved.data?.data ?? []).filter((c) => c.shortcut.startsWith(text.split(" ")[0]!)).slice(0, 8) : []), [text, saved.data]);
  if (!conv) return <div className="grid h-full place-items-center">{t.error ? <span className="text-[13px] text-bad">{t.error}</span> : <Spinner />}</div>;
  const windowClosed = conv.channel === "whatsapp" && !conv.whatsappWindowOpen;
  const privateUntil = conv.window?.privateReplyUntil ? new Date(conv.window.privateReplyUntil) : null;
  const privateOk = isComment && ["facebook", "instagram"].includes(conv.account?.platform) && (!privateUntil || privateUntil > new Date());
  const targetComment = conv.comments?.find((c: any) => c.id === target);

  const send = () => run(async () => {
    if (!text.trim() && !templateId) return;
    if (mode === "note") await api(`/conversations/${id}/notes`, { body: { body: text } });
    else if (isReview) await api(`/reviews/${conv.review.id}/reply`, { body: { body: text } });
    else if (isComment) {
      if (!target) throw new Error("Choose the comment you're replying to");
      if (mode === "private") await api(`/comments/${target}/private-reply`, { body: { body: text } });
      else await api(`/comments/${target}/reply`, { body: { body: text } });
    } else {
      if (windowClosed && !templateId) throw new Error("The 24-hour WhatsApp window is closed — pick an approved template");
      await api("/messages", { body: { contact_id: conv.contactId, channel: conv.channel, conversation_id: id, body: templateId ? undefined : text, template_id: templateId || undefined, subject: subject || undefined } });
    }
    setText(""); setTemplateId(""); setAi(null); t.reload(); onChange();
    api(`/conversations/${id}/lock`, { body: { release: true } }).catch(() => {});
    push("ok", mode === "note" ? "Note added" : mode === "private" ? "Private reply sent" : "Reply sent");
  });

  const timeline = isComment ? conv.comments : isReview ? [] : conv.messages;
  const notes = isDm ? [] : conv.messages.filter((m: any) => m.direction === "note");
  const statusMenu = [
    ...(conv.status !== "resolved" ? [{ label: "Resolve", icon: <CheckCheck className="h-3.5 w-3.5" />, onClick: () => post(`/conversations/${id}/status`, { status: "resolved" }, "Resolved") }] : [{ label: "Reopen", onClick: () => post(`/conversations/${id}/status`, { status: "open" }, "Reopened") }]),
    { label: "Snooze…", icon: <Clock className="h-3.5 w-3.5" />, onClick: () => setSnoozeOpen(true) },
    { label: "Mark pending", onClick: () => post(`/conversations/${id}/status`, { status: "pending" }, "Marked pending") },
    "sep" as const,
    { label: "Priority: urgent", onClick: () => update({ priority: "urgent" }, "Priority set to urgent") },
    { label: "Priority: high", onClick: () => update({ priority: "high" }, "Priority set to high") },
    { label: "Priority: normal", onClick: () => update({ priority: "normal" }, "Priority set to normal") },
    "sep" as const,
    { label: "Create lead", icon: <UserPlus className="h-3.5 w-3.5" />, onClick: () => post(`/conversations/${id}/create-lead`, {}, "Lead created and attributed") },
    ...(!isDm || conv.channel !== "whatsapp" ? [{ label: "Move to WhatsApp", icon: <Phone className="h-3.5 w-3.5" />, onClick: async () => { const r: any = await post(`/conversations/${id}/move-to-whatsapp`); if (r) push("ok", r.data.method === "whatsapp_template" ? "WhatsApp template sent" : "WhatsApp link sent"); } }] : []),
    { label: "Summarize with AI", icon: <Sparkles className="h-3.5 w-3.5" />, onClick: () => post("/ai/summarize", { conversation_id: id }, "Summary logged to the contact timeline") },
    { label: "Close", onClick: () => post(`/conversations/${id}/status`, { status: "closed" }, "Closed") },
  ];

  return (
    <div className="flex h-full">
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="flex flex-wrap items-center gap-2 border-b border-line bg-panel/80 px-3 py-2.5 backdrop-blur sm:px-4">
          <button className="rounded p-1 md:hidden" onClick={onBack} aria-label="Back"><ArrowLeft className="h-4 w-4" /></button>
          <Avatar name={conv.contact?.name ?? "?"} size={32} />
          <div className="min-w-0 flex-1">
            <button onClick={() => setContactOpen(true)} className="block max-w-full truncate text-left text-[14px] font-semibold hover:text-brand 2xl:pointer-events-none">{conv.contact?.name}</button>
            <div className="flex items-center gap-1.5 truncate text-[11.5px] text-ink-3"><ChannelBadge channel={conv.channel} />{conv.account && <span className="truncate">via {conv.account.name}</span>}{conv.intent && <span>· {intentLabel(conv.intent)}</span>}<SentimentDot s={conv.sentiment} /></div>
          </div>
          <div className="flex flex-wrap items-center gap-1.5">
            <SlaChip due={conv.slaDueAt} breached={conv.slaBreachedAt} responded={conv.firstResponseAt} />
            {conv.status === "snoozed" && <Badge tone="amber">Snoozed · {ago(conv.snoozedUntil)}</Badge>}
            {isDm && <Toggle checked={conv.aiAgentActive} onChange={(v) => v ? update({ ai_agent_active: true }, "AI agent will reply and qualify") : post(`/conversations/${id}/handoff`, {}, "You took over from the AI agent")} label={<span className="inline-flex items-center gap-1 text-[12px]"><Bot className="h-3.5 w-3.5" /><span className="hidden sm:inline">AI agent</span></span>} />}
            {canAssign && <select aria-label="Assignee" className="field w-[130px] py-1 text-[12.5px]" value={conv.assigneeId ?? ""} onChange={(e) => post(`/conversations/${id}/assign`, { user_id: e.target.value || null }, "Reassigned")}><option value="">Unassigned</option>{team?.data.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}</select>}
            <Button size="sm" className="hidden sm:inline-flex" icon={<CheckCheck className="h-3.5 w-3.5" />} onClick={() => post(`/conversations/${id}/status`, { status: conv.status === "resolved" ? "open" : "resolved" }, conv.status === "resolved" ? "Reopened" : "Resolved")}>{conv.status === "resolved" ? "Reopen" : "Resolve"}</Button>
            <Menu trigger={<Button size="sm" icon={<MoreHorizontal className="h-3.5 w-3.5" />} aria-label="More actions" />} items={statusMenu} />
          </div>
        </header>

        {conv.lockedBy && (
          <div className="flex items-center gap-2 border-b border-warn/30 bg-warn/10 px-4 py-1.5 text-[12px] text-warn">
            <Lock className="h-3.5 w-3.5" /><span><b>{conv.lockedBy.name}</b> is replying to this conversation.</span>
            <button className="ml-auto underline" onClick={() => lock(true)}>Take over</button>
          </div>
        )}

        <div className="flex-1 space-y-2 overflow-y-auto bg-sunken/60 px-3 py-4 sm:px-4">
          {/* post / ad context (SOC-014/015) */}
          {conv.object && (
            <div className="mx-auto mb-3 flex max-w-xl gap-3 rounded-[12px] border border-line bg-panel p-2.5">
              {conv.object.thumbnailUrl && <img src={conv.object.thumbnailUrl} alt="" className="h-14 w-14 shrink-0 rounded-[8px] object-cover" />}
              <div className="min-w-0 flex-1 text-[12.5px]">
                <div className="flex items-center gap-1.5"><Badge tone={conv.object.type === "ad" ? "violet" : "gray"}>{conv.object.type}</Badge>{conv.object.campaignName && <span className="truncate font-semibold">{conv.object.campaignName}</span>}{conv.object.permalink && <a href={conv.object.permalink} target="_blank" rel="noreferrer" className="ml-auto text-ink-3 hover:text-brand" aria-label="Open post"><ExternalLink className="h-3.5 w-3.5" /></a>}</div>
                <p className="mt-0.5 line-clamp-2 text-ink-2">{conv.object.captionExcerpt ?? "(no caption)"}</p>
                {conv.object.externalAdId && <p className="mt-0.5 text-[11px] text-ink-3">Ad ID {conv.object.externalAdId}</p>}
              </div>
            </div>
          )}
          {/* review (SOC-060) */}
          {isReview && conv.review && (
            <div className="mx-auto max-w-xl space-y-2">
              <div className="rounded-[12px] border border-line bg-panel p-3">
                <div className="flex items-center gap-2"><Stars rating={conv.review.rating} /><span className="text-[12px] text-ink-3">{conv.review.reviewerName} · {fmtDate(conv.review.externalCreatedAt, tz)}</span></div>
                <p className="mt-1.5 whitespace-pre-wrap text-[13px]">{conv.review.body ?? <i className="text-ink-3">Rating only, no text</i>}</p>
              </div>
              {conv.review.replyBody && (
                <div className={cx("ml-6 rounded-[12px] p-3 text-[13px]", conv.review.replyStatus === "published" ? "bg-brand text-white" : "border border-dashed border-line bg-panel")}>
                  <div className="mb-0.5 text-[10.5px] font-semibold uppercase opacity-80">{conv.review.replyStatus === "published" ? `Owner reply${conv.review.repliedByAi ? " · AI" : ""}` : conv.review.replyStatus === "pending_approval" ? "AI draft awaiting approval" : conv.review.replyStatus}</div>
                  <div className="whitespace-pre-wrap">{conv.review.replyBody}</div>
                </div>
              )}
            </div>
          )}
          {timeline.map((m: any) => isComment ? (
            <CommentRow key={m.id} c={m} tz={tz} selected={target === m.id} canModerate={canModerate} platform={conv.account?.platform}
              onReplyTo={() => { setTarget(m.id); setMode("reply"); box.current?.focus(); }}
              onPrivate={() => { setTarget(m.id); setMode("private"); box.current?.focus(); }}
              onAction={(a, body) => post(`/comments/${m.id}/${a}`, body ?? {}, a === "retry" ? "Retried" : a === "create-lead" ? "Lead created" : a === "block-author" ? "Author blocked" : "Done")} />
          ) : (
            <MessageRow key={m.id} m={m} tz={tz} />
          ))}
          {notes.map((m: any) => <MessageRow key={m.id} m={m} tz={tz} />)}
          <div ref={end} />
        </div>

        {/* composer */}
        <div className="border-t border-line bg-panel p-2.5 sm:p-3">
          {windowClosed && mode !== "note" && <div className="mb-2 flex items-center gap-2 rounded-[8px] bg-warn/10 px-3 py-1.5 text-[12px] text-warn"><Lock className="h-3.5 w-3.5 shrink-0" />24-hour window closed — WhatsApp only allows approved templates until the customer replies.</div>}
          {isComment && mode === "private" && <div className="mb-2 flex items-center gap-2 rounded-[8px] bg-violet/10 px-3 py-1.5 text-[12px] text-violet"><Lock className="h-3.5 w-3.5 shrink-0" />Private reply opens a DM with the commenter{privateUntil ? ` · allowed until ${fmtDate(privateUntil, tz)}` : ""} · one per comment</div>}
          {isDm && conv.window && ["messenger", "instagram"].includes(conv.channel) && <div className={cx("mb-2 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px]", conv.window.open ? "bg-ok/12 text-ok" : "bg-warn/15 text-warn")}><Clock className="h-3 w-3" />{conv.window.open ? `Messaging window open until ${fmtDate(conv.window.expiresAt, tz)}` : "Messaging window closed — only tagged messages allowed"}</div>}
          {ai && (
            <div className="mb-2 space-y-1.5">
              <div className="flex items-center gap-1.5 text-[11px] font-semibold uppercase text-violet"><Sparkles className="h-3 w-3" />AI suggestions {ai.source === "knowledge" && <span className="font-normal normal-case text-ink-3">(knowledge base — AI not configured)</span>}<button className="ml-auto" onClick={() => setAi(null)} aria-label="Dismiss suggestions"><X className="h-3 w-3" /></button></div>
              <div className="flex gap-1.5 overflow-x-auto pb-1">
                {ai.suggestions.map((s, i) => (
                  <button key={i} onClick={() => { setText(s.text); box.current?.focus(); }} className="w-[260px] shrink-0 rounded-[10px] border border-line bg-sunken/60 p-2 text-left text-[12px] hover:border-violet">
                    <div className="line-clamp-3">{s.text}</div>
                    <div className="mt-1 flex items-center gap-1 text-[10.5px] text-ink-3"><span className={cx("font-semibold", s.confidence >= 0.8 ? "text-ok" : s.confidence >= 0.5 ? "text-warn" : "text-bad")}>{Math.round(s.confidence * 100)}%</span>{!s.publicSafe && <span className="text-bad">· keep private</span>}{s.reason && <span className="truncate">· {s.reason}</span>}</div>
                  </button>
                ))}
              </div>
            </div>
          )}
          {savedMatches.length > 0 && <div className="mb-2 flex flex-wrap gap-1.5">{savedMatches.map((s) => <button key={s.id} onClick={() => { setText(s.body); box.current?.focus(); }} className="rounded-full border border-line px-2.5 py-1 text-[12px] hover:border-brand hover:text-brand" title={s.body}>{s.shortcut}{s.title ? ` · ${s.title}` : ""}</button>)}</div>}
          <div className="mb-2 flex flex-wrap items-center gap-2">
            <Segmented size="sm" value={mode} onChange={(v) => setMode(v)} options={[
              { value: "reply", label: isComment ? "Public reply" : isReview ? "Reply to review" : "Reply" },
              ...(privateOk ? [{ value: "private" as const, label: "Private reply" }] : []),
              { value: "note", label: "Note" },
            ]} />
            {isDm && mode !== "note" && <select aria-label="Template" className="field w-auto max-w-[180px] py-1 text-[12px]" value={templateId} onChange={(e) => setTemplateId(e.target.value)}><option value="">{windowClosed ? "Choose an approved template…" : "Free text"}</option>{tpls.data?.data.map((tp) => <option key={tp.id} value={tp.id} disabled={conv.channel === "whatsapp" && tp.providerStatus !== "approved"}>{tp.name}{tp.providerStatus !== "approved" ? ` (${tp.providerStatus})` : ""}</option>)}</select>}
            {isDm && mode !== "note" && conv.channel === "email" && <input className="field w-[200px] py-1 text-[12px]" placeholder="Subject" value={subject} onChange={(e) => setSubject(e.target.value)} />}
            {mode !== "note" && <Button size="sm" variant="ghost" loading={aiBusy} icon={<Sparkles className="h-3.5 w-3.5" />} onClick={suggest}>Suggest</Button>}
            <span className="ml-auto truncate text-[11px] text-ink-3">{mode === "note" ? "Only your team sees notes · @name to mention" : isDm ? `Sending as ${team?.data.find((u) => u.id === team.me)?.name ?? "you"}` : `Replying publicly as ${conv.account?.name ?? "the page"}`}{targetComment && isComment && mode !== "note" ? ` → ${targetComment.authorName ?? "comment"}` : ""}</span>
          </div>
          <div className="flex items-end gap-2">
            {templateId ? <div className="flex flex-1 items-start gap-2 rounded-[8px] bg-sunken px-3 py-2 text-[12.5px]"><FileText className="mt-0.5 h-3.5 w-3.5 shrink-0 text-ink-3" /><span className="whitespace-pre-wrap">{tpls.data?.data.find((x) => x.id === templateId)?.body}</span></div>
              : <textarea ref={box} className={cx("field min-h-[44px] flex-1 resize-none", mode === "note" && "border-warn/40 bg-warn/5", mode === "private" && "border-violet/40")} rows={2} placeholder={mode === "note" ? "Only your team sees this" : "Write a reply… ( / for saved replies )"} value={text}
                onChange={(e) => { setText(e.target.value); if (mode !== "note") lock(); }} onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) send(); }} />}
            <Button variant="primary" loading={busy} onClick={send} icon={mode === "note" ? <StickyNote className="h-3.5 w-3.5" /> : <Send className="h-3.5 w-3.5" />}><span className="hidden sm:inline">{mode === "note" ? "Add note" : "Send"}</span></Button>
          </div>
        </div>
      </div>

      {/* contact card (desktop) / sheet (mobile) */}
      <aside className="hidden w-[280px] shrink-0 overflow-y-auto border-l border-line bg-panel p-4 2xl:block"><ContactCard conv={conv} currency={team?.currency} onTags={(tags) => api(`/conversations/${id}/tags`, { method: "PUT", body: { tags } }).then(() => t.reload())} /></aside>
      <Sheet open={contactOpen} onClose={() => setContactOpen(false)} title={conv.contact?.name ?? "Contact"} width={360}><ContactCard conv={conv} currency={team?.currency} onTags={(tags) => api(`/conversations/${id}/tags`, { method: "PUT", body: { tags } }).then(() => t.reload())} /></Sheet>
      <SnoozeSheet open={snoozeOpen} onClose={() => setSnoozeOpen(false)} onPick={(until) => { setSnoozeOpen(false); post(`/conversations/${id}/snooze`, { until }, "Snoozed"); }} />
    </div>
  );
}

function MessageRow({ m, tz }: { m: any; tz?: string }) {
  return (
    <div className={cx("flex", m.direction === "in" ? "justify-start" : "justify-end")}>
      <div className={cx("max-w-[85%] rounded-[16px] px-3.5 py-2 text-[13px] shadow-[0_1px_1px_rgb(0_0_0/.06)] sm:max-w-[75%]",
        m.direction === "in" ? "rounded-bl-[5px] bg-panel" : m.direction === "note" ? "rounded-br-[5px] border border-warn/40 bg-warn/10" : "rounded-br-[5px] bg-brand text-white")}>
        {m.direction === "note" && <div className="mb-0.5 flex items-center gap-1 text-[10.5px] font-semibold uppercase text-warn"><StickyNote className="h-3 w-3" />Internal note{m.senderName ? ` · ${m.senderName}` : ""}</div>}
        {m.subject && <div className="mb-1 font-semibold">{m.subject}</div>}
        <div className="whitespace-pre-wrap break-words">{m.body}</div>
        <div className={cx("mt-1 flex items-center justify-end gap-1 text-[10.5px]", m.direction === "out" ? "text-white/75" : "text-ink-3")}>
          {m.direction === "out" && !m.senderId && <Bot className="h-3 w-3" />}{m.senderName && m.direction === "out" ? `${m.senderName} · ` : ""}{fmtDate(m.createdAt, tz)}{m.direction === "out" && ` · ${m.status}`}
        </div>
        {m.error && <div className={cx("mt-1 rounded-[6px] px-1.5 py-0.5 text-[11px]", m.direction === "out" ? "bg-white/20 text-white" : "text-bad")}>⚠ {m.error}</div>}
      </div>
    </div>
  );
}

function CommentRow({ c, tz, selected, canModerate, platform, onReplyTo, onPrivate, onAction }: { c: any; tz?: string; selected: boolean; canModerate: boolean; platform?: string; onReplyTo: () => void; onPrivate: () => void; onAction: (a: string, body?: Record<string, unknown>) => void }) {
  const out = c.direction === "outbound";
  const nested = !!c.parentExternalCommentId;
  const items = [
    { label: "Reply publicly", onClick: onReplyTo },
    ...(["facebook", "instagram"].includes(platform ?? "") && !out ? [{ label: "Private reply", onClick: onPrivate }] : []),
    ...(platform === "facebook" ? [{ label: c.likedByPage ? "Unlike" : "Like", icon: <Heart className="h-3.5 w-3.5" />, onClick: () => onAction(c.likedByPage ? "unlike" : "like") }] : []),
    ...(!out ? [{ label: "Create lead", icon: <UserPlus className="h-3.5 w-3.5" />, onClick: () => onAction("create-lead") }] : []),
    ...(canModerate ? ["sep" as const,
      c.isHidden ? { label: "Unhide", icon: <Eye className="h-3.5 w-3.5" />, onClick: () => onAction("unhide") } : { label: "Hide", icon: <EyeOff className="h-3.5 w-3.5" />, onClick: () => onAction("hide", { reason: "Hidden by agent" }) },
      ...(!out ? [{ label: "Mark spam", onClick: () => onAction("mark-spam") }, { label: "Block author", icon: <Ban className="h-3.5 w-3.5" />, onClick: () => { if (confirm("Block this author? Their future comments will be hidden automatically.")) onAction("block-author"); } }] : []),
      { label: "Delete", icon: <Trash2 className="h-3.5 w-3.5" />, danger: true, onClick: () => { if (confirm("Delete this comment on the platform? This can't be undone.")) onAction("delete"); } }] : []),
  ];
  return (
    <div className={cx("flex", out ? "justify-end" : "justify-start", nested && !out && "pl-6")}>
      <div className={cx("group relative max-w-[88%] rounded-[16px] px-3.5 py-2 text-[13px] shadow-[0_1px_1px_rgb(0_0_0/.06)] sm:max-w-[75%]",
        out ? "rounded-br-[5px] bg-brand text-white" : "rounded-bl-[5px] bg-panel", selected && !out && "ring-2 ring-brand/40", (c.isHidden || c.isDeleted) && "opacity-60")}>
        <div className={cx("mb-0.5 flex items-center gap-1.5 text-[11px] font-semibold", out ? "text-white/85" : "text-ink-2")}>
          <span className="truncate">{out ? c.senderName ?? (c.sentByAi ? "AI" : c.sentByRuleId ? "Rule" : c.authorName) : c.authorName ?? c.authorHandle ?? "Someone"}</span>
          {c.sentByAi && <Bot className="h-3 w-3" />}{c.sentByRuleId && <Wand2 className="h-3 w-3" />}
          {c.isHidden && <Badge tone="amber">hidden</Badge>}{c.isDeleted && <Badge tone="red">deleted</Badge>}{c.likedByPage && <Heart className="h-3 w-3 fill-current text-brand" />}
          {!out && <SentimentDot s={c.sentiment} />}{!out && c.language && c.language !== "en" && <span className="font-normal opacity-70">{c.language}</span>}
        </div>
        <div className="whitespace-pre-wrap break-words">{c.body}</div>
        {c.editHistory?.length > 0 && <div className="mt-0.5 text-[10.5px] opacity-70">edited</div>}
        <div className={cx("mt-1 flex items-center justify-end gap-1 text-[10.5px]", out ? "text-white/75" : "text-ink-3")}>{fmtDate(c.externalCreatedAt, tz)}{out && c.providerStatus && ` · ${c.providerStatus}`}</div>
        {c.providerStatus === "failed" && <div className="mt-1 flex items-center gap-2 rounded-[6px] bg-white/20 px-1.5 py-0.5 text-[11px]">⚠ {c.providerError}<button className="ml-auto underline" onClick={() => onAction("retry")}>Retry</button></div>}
        {!c.isDeleted && (
          <div className={cx("absolute top-1 opacity-0 transition group-hover:opacity-100 max-md:opacity-100", out ? "-left-8" : "-right-8")}>
            <Menu align={out ? "left" : "right"} trigger={<button className="rounded-full bg-panel p-1 text-ink-2 shadow" aria-label="Comment actions"><MoreHorizontal className="h-3.5 w-3.5" /></button>} items={items} />
          </div>
        )}
      </div>
    </div>
  );
}

function ContactCard({ conv, currency, onTags }: { conv: any; currency?: string; onTags: (tags: string[]) => void }) {
  const [tag, setTag] = useState("");
  const c = conv.contact;
  if (!c) return null;
  return (
    <div className="space-y-4 text-[13px]">
      <div className="text-center">
        <Avatar name={c.name} size={56} className="mx-auto" />
        <Link href={`/contacts/${c.id}`} className="mt-2 block font-semibold hover:text-brand">{c.name}</Link>
        <div className="text-[12px] text-ink-3">{c.lifecycleStage?.replace(/_/g, " ")}{c.project ? ` · ${c.project}` : ""}</div>
      </div>
      <dl className="space-y-1.5">
        {c.phones?.map((p: string) => <div key={p} className="flex gap-2"><dt className="w-14 text-ink-3">Phone</dt><dd className="truncate">{p}</dd></div>)}
        {c.emails?.map((e: string) => <div key={e} className="flex gap-2"><dt className="w-14 text-ink-3">Email</dt><dd className="truncate">{e}</dd></div>)}
        {c.city && <div className="flex gap-2"><dt className="w-14 text-ink-3">City</dt><dd>{c.city}</dd></div>}
      </dl>
      <div>
        <div className="mb-1 text-[11px] font-semibold uppercase text-ink-3">Conversation tags</div>
        <div className="flex flex-wrap gap-1">{(conv.tags ?? []).map((t: string) => <button key={t} onClick={() => onTags(conv.tags.filter((x: string) => x !== t))} className="rounded-full bg-sunken px-2 py-0.5 text-[11.5px] hover:line-through">{t}</button>)}</div>
        <form className="mt-1.5" onSubmit={(e) => { e.preventDefault(); if (tag.trim()) { onTags([...(conv.tags ?? []), tag.trim()]); setTag(""); } }}><input className="field py-1 text-[12px]" placeholder="Add tag + Enter" value={tag} onChange={(e) => setTag(e.target.value)} /></form>
      </div>
      {conv.deals?.length > 0 && <div>
        <div className="mb-1 text-[11px] font-semibold uppercase text-ink-3">Deals</div>
        <ul className="space-y-1">{conv.deals.map((d: any) => <li key={d.id}><Link href={`/pipeline?deal=${d.id}`} className="flex justify-between gap-2 rounded-[7px] px-2 py-1 hover:bg-sunken"><span className="truncate">{d.title}</span><span className="shrink-0 text-ink-3">{d.wonAt ? "won" : d.lostAt ? "lost" : moneyShort(d.value, currency)}</span></Link></li>)}</ul>
      </div>}
      <div>
        <div className="mb-1 text-[11px] font-semibold uppercase text-ink-3">Other conversations</div>
        {conv.otherConversations?.length ? <ul className="space-y-1">{conv.otherConversations.map((o: any) => <li key={o.id}><Link href={`/inbox?c=${o.id}`} className="flex items-center gap-2 rounded-[7px] px-2 py-1 hover:bg-sunken"><KindIcon kind={o.kind} className="text-ink-3" /><span className="flex-1 truncate">{CHANNEL_LABEL[o.channel] ?? o.channel}</span><span className="text-[11px] text-ink-3">{o.status} · {ago(o.lastMessageAt)}</span></Link></li>)}</ul> : <p className="text-[12px] text-ink-3">None — first touch on this channel.</p>}
      </div>
    </div>
  );
}

function SnoozeSheet({ open, onClose, onPick }: { open: boolean; onClose: () => void; onPick: (iso: string) => void }) {
  const [custom, setCustom] = useState("");
  const at = (h: number) => new Date(Date.now() + h * 3600000).toISOString();
  const tomorrow9 = () => { const d = new Date(); d.setDate(d.getDate() + 1); d.setHours(9, 0, 0, 0); return d.toISOString(); };
  return (
    <Sheet open={open} onClose={onClose} title="Snooze until" width={340}>
      <div className="space-y-2">
        {[["1 hour", at(1)], ["4 hours", at(4)], ["Tomorrow 9:00", tomorrow9()], ["Next week", at(24 * 7)]].map(([l, v]) => <Button key={l} className="w-full justify-start" onClick={() => onPick(v!)}>{l}</Button>)}
        <div className="flex gap-2 pt-2"><input type="datetime-local" className="field flex-1" value={custom} onChange={(e) => setCustom(e.target.value)} aria-label="Custom time" /><Button variant="primary" disabled={!custom} onClick={() => onPick(new Date(custom).toISOString())}>Snooze</Button></div>
        <p className="text-[12px] text-ink-3">It comes back automatically — or sooner if the customer writes again.</p>
      </div>
    </Sheet>
  );
}
