All files / src/pages/admin/rrm inbox.tsx

100% Statements 120/120
100% Branches 103/103
100% Functions 49/49
100% Lines 114/114

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876                                                                                                                1x 1x   1x           1x                       1x                             1x                               67x                                             155x 155x 17x 17x 1x       327x                 291x 291x 36x 36x 36x 2x           291x 260x 255x         1x           1x                             136x 136x 136x   136x                                                                                     1x                             155x   155x   155x                                                                                                           67x 67x                                                       140x 140x 140x 140x 140x 140x 140x 140x   140x   140x   140x 140x                 140x     140x   9x     156x       140x 140x 65x 65x 65x           140x 65x           140x   140x       140x     37x 37x 37x           2x 2x       8x 8x 8x 6x 6x   2x   8x         3x   3x                         2x 2x       1x         1x       1x 1x       1x               2x 2x 2x 2x         6x     6x 6x       140x     140x 140x       140x                                                                           2x                               1x       408x       480x     5x                               155x       35x                                                           1x                                                     67x                                                                                                     3x                           2x                           3x                                 1x 1x                               2x         198x                 660x     6x                         3x                                                     2x                                                                     544x                                                               198x              
import { useQueryClient } from "@tanstack/react-query";
import {
	AlertTriangle,
	ArrowLeft,
	Ban,
	CheckCircle2,
	Clock,
	MessageSquare,
	Send,
	ShieldAlert,
} from "lucide-react";
import { type ReactNode, useEffect, useRef, useState } from "react";
 
import { Button } from "../../../components/ui/button";
import { Card, CardContent } from "../../../components/ui/card";
import { ConfirmDialog } from "../../../components/ui/confirm-dialog";
import { EmptyState } from "../../../components/ui/empty-state";
import { SkeletonList } from "../../../components/ui/skeleton";
import { StatusBadge } from "../../../components/ui/status-badge";
import { Tooltip } from "../../../components/ui/tooltip";
import {
	useRrmInbox,
	useRrmProspect,
} from "../../../hooks/queries/useRrmQueries";
import {
	adminRrmApi,
	type RrmInboxConversation,
	type RrmLocale,
	type RrmMessage,
	type RrmStage,
} from "../../../lib/api/admin/rrm";
import { notify } from "../../../lib/notify";
import { queryKeys } from "../../../lib/query-keys";
import {
	CANNED_REPLY_ORDER,
	type CannedReplyKey,
	cannedReplyBody,
	cannedReplyLabel,
	firstLine,
} from "../../../lib/rrm/canned-replies";
import { cn } from "../../../lib/utils";
 
/**
 * RRM partner inbox (F-21) — the screen the campaign actually runs on.
 *
 * Requirement P1-0.10 makes an inbox backlog older than 24 hours an
 * AUTO-PAUSE condition. A number that goes stale on this page is therefore not
 * an inconvenience, it is a campaign that stopped sending and nobody noticed.
 *
 * The age of the oldest waiting conversation is surfaced four times over, and
 * no single one of them relies on colour: a sticky strip with an icon and
 * words, the server's oldest-first ordering, a per-row age chip, and the
 * document title, so a backgrounded tab still shows the backlog.
 */
 
/** Minutes. Two hours is the operating SLA; one hour is the warning shoulder. */
const SLA_BREACH_MINUTES = 120;
const SLA_WARN_MINUTES = 60;
 
const LOCALE_LABELS: Record<RrmLocale, string> = {
	en: "English",
	te: "తెలుగు",
	"te-Latn": "Telugu (Latin)",
};
 
const LOCALES: readonly RrmLocale[] = ["en", "te", "te-Latn"];
 
// ─── Stage badge ─────────────────────────────────────────────────────────────
 
/**
 * `StatusBadge.getVariantForStatus` knows marketplace statuses, not RRM
 * stages — "contacted" would come back `warning` and "read" would come back
 * `default`. Every RRM call site therefore passes `variant` explicitly.
 */
const STAGE_VARIANTS: Record<
	RrmStage,
	"default" | "info" | "warning" | "success" | "error"
> = {
	sourced: "default",
	not_now: "default",
	unreachable: "default",
	queued: "info",
	contacted: "info",
	delivered: "info",
	read: "info",
	replied: "warning",
	interested: "success",
	joined: "success",
	intent_stated: "success",
	do_not_contact: "error",
};
 
const STAGE_LABELS: Record<RrmStage, string> = {
	sourced: "Sourced",
	queued: "Queued",
	contacted: "Contacted",
	delivered: "Delivered",
	read: "Read",
	replied: "Replied",
	interested: "Interested",
	intent_stated: "Intent stated",
	joined: "Joined",
	not_now: "Not now",
	unreachable: "Unreachable",
	do_not_contact: "Do not contact",
};
 
export function StageBadge({ stage }: { stage: RrmStage }) {
	return (
		<span data-testid={`stage-badge-${stage}`}>
			<StatusBadge
				status={STAGE_LABELS[stage]}
				variant={STAGE_VARIANTS[stage]}
				// `intent_stated` is the program's single success criterion — three
				// of them in fourteen days decides whether Phase 2 is built. It has to
				// win the eye in a table of hundreds, so it gets weight and a ring on
				// top of the colour.
				className={
					stage === "intent_stated"
						? "font-semibold ring-1 ring-success"
						: undefined
				}
			/>
		</span>
	);
}
 
// ─── Age formatting ──────────────────────────────────────────────────────────
 
/** Compact, fixed-width form for the row chips: "8m", "3h 12m", "1d 4h". */
export function formatAgeShort(minutes: number): string {
	const safe = Math.max(0, Math.round(minutes));
	if (safe < 60) return `${safe}m`;
	const hours = Math.floor(safe / 60);
	if (hours < 24) return `${hours}h ${safe % 60}m`;
	return `${Math.floor(hours / 24)}d ${hours % 24}h`;
}
 
function plural(value: number, unit: string): string {
	return `${value} ${unit}${value === 1 ? "" : "s"}`;
}
 
/**
 * Spoken form. The compact chip is unreadable aloud ("3h 12m" becomes "three
 * h twelve m"), and this screen's whole point is that the backlog reaches
 * someone who is not looking straight at it.
 */
export function formatAgeLong(minutes: number): string {
	const safe = Math.max(0, Math.round(minutes));
	if (safe < 60) return plural(safe, "minute");
	const hours = Math.floor(safe / 60);
	if (hours < 24)
		return `${plural(hours, "hour")} ${plural(safe % 60, "minute")}`;
	return `${plural(Math.floor(hours / 24), "day")} ${plural(hours % 24, "hour")}`;
}
 
type SlaLevel = "breach" | "warn" | "ok";
 
export function slaLevel(minutes: number): SlaLevel {
	if (minutes >= SLA_BREACH_MINUTES) return "breach";
	if (minutes >= SLA_WARN_MINUTES) return "warn";
	return "ok";
}
 
// ─── Sticky SLA strip ────────────────────────────────────────────────────────
 
const STRIP_TONES: Record<SlaLevel, string> = {
	breach: "bg-error-light text-error border-error",
	warn: "bg-warning-light text-warning border-warning",
	ok: "bg-background-subtle text-foreground-muted border-border-default",
};
 
const STRIP_HEADLINES: Record<SlaLevel, string> = {
	breach: "OVER THE 2h SLA",
	warn: "APPROACHING THE 2h SLA",
	ok: "WITHIN THE 2h SLA",
};
 
function SlaStrip({
	oldest,
	unanswered,
	onJump,
}: {
	oldest: RrmInboxConversation;
	unanswered: number;
	onJump: () => void;
}) {
	const level = slaLevel(oldest.waitingMinutes);
	const Icon = level === "ok" ? Clock : AlertTriangle;
	const who = oldest.name ?? oldest.firmName ?? oldest.phoneNorm;
 
	return (
		// `role="status"` rather than `alert`: the list re-polls every 30s and an
		// assertive live region would interrupt the operator mid-reply on every
		// tick.
		<div
			role="status"
			data-testid="inbox-sla-strip"
			data-sla-level={level}
			className={cn(
				"sticky top-0 z-20 flex flex-col gap-3 rounded-lg border px-4 py-3 sm:flex-row sm:items-center sm:justify-between",
				STRIP_TONES[level],
			)}
		>
			<div className="flex items-start gap-3">
				<Icon className="mt-0.5 h-5 w-5 shrink-0" aria-hidden="true" />
				<div className="min-w-0">
					<p className="text-sm font-bold tracking-wide">
						{STRIP_HEADLINES[level]}
					</p>
					<p className="mt-0.5 text-sm">
						Oldest waiting: <span className="font-semibold">{who}</span> —{" "}
						<span className="tabular-nums font-semibold">
							{formatAgeLong(oldest.waitingMinutes)}
						</span>
						{unanswered > 1 ? `, ${unanswered} unanswered in total` : ""}
					</p>
				</div>
			</div>
			<Button
				variant="outline"
				size="sm"
				onClick={onJump}
				data-testid="inbox-sla-jump"
				className="shrink-0 self-start sm:self-auto"
			>
				Jump to it
			</Button>
		</div>
	);
}
 
// ─── Conversation row ────────────────────────────────────────────────────────
 
const AGE_CHIP_TONES: Record<SlaLevel, string> = {
	breach: "bg-error-light text-error",
	warn: "bg-warning-light text-warning",
	ok: "bg-background-muted text-foreground-muted",
};
 
function ConversationRow({
	conversation,
	selected,
	onSelect,
}: {
	conversation: RrmInboxConversation;
	selected: boolean;
	onSelect: () => void;
}) {
	const level = slaLevel(conversation.waitingMinutes);
	const name =
		conversation.name ?? conversation.firmName ?? conversation.phoneNorm;
 
	return (
		<button
			type="button"
			onClick={onSelect}
			aria-current={selected ? "true" : undefined}
			data-testid={`conversation-row-${conversation.prospectId}`}
			className={cn(
				"w-full border-b border-border-default px-4 py-3 text-left transition-colors hover:bg-background-muted",
				selected && "bg-background-muted",
			)}
		>
			<div className="flex items-center gap-2">
				{/* Age leads the row, before the name: the operator scans this column
				    top-to-bottom looking for the number that is too big. */}
				<span
					data-testid={`conversation-age-${conversation.prospectId}`}
					className={cn(
						"inline-flex shrink-0 items-center gap-1 rounded-md px-2 py-0.5 text-xs font-semibold tabular-nums",
						AGE_CHIP_TONES[level],
					)}
				>
					{level === "breach" && (
						<AlertTriangle className="h-3 w-3" aria-hidden="true" />
					)}
					<span aria-hidden="true">
						{formatAgeShort(conversation.waitingMinutes)}
					</span>
					<span className="sr-only">
						Waiting {formatAgeLong(conversation.waitingMinutes)}
					</span>
				</span>
				<span className="truncate text-sm font-medium text-foreground-default">
					{name}
				</span>
				{conversation.needsOptOutReview && (
					<ShieldAlert
						className="ml-auto h-4 w-4 shrink-0 text-warning"
						aria-label="Needs opt-out review"
					/>
				)}
			</div>
			<p className="mt-1 truncate text-xs text-foreground-muted">
				{conversation.lastMessagePreview}
			</p>
			<p className="mt-1 text-xs text-foreground-subtle">
				{LOCALE_LABELS[conversation.locale]} · {conversation.phoneNorm}
			</p>
		</button>
	);
}
 
// ─── Message thread ──────────────────────────────────────────────────────────
 
function MessageBubble({ message }: { message: RrmMessage }) {
	const inbound = message.direction === "inbound";
	return (
		<div className={cn("flex", inbound ? "justify-start" : "justify-end")}>
			<div
				className={cn(
					"max-w-[85%] rounded-lg px-3 py-2 text-sm sm:max-w-[70%]",
					inbound
						? "bg-background-muted text-foreground-default"
						: "bg-primary-500 text-foreground-inverse",
				)}
			>
				<p className="whitespace-pre-wrap break-words">{message.body}</p>
				<p
					className={cn(
						"mt-1 text-xs",
						inbound ? "text-foreground-subtle" : "text-foreground-inverse/80",
					)}
				>
					{new Date(message.dateCreated).toLocaleString()}
					{message.templateName ? ` · ${message.templateName}` : ""}
				</p>
			</div>
		</div>
	);
}
 
// ─── Page ────────────────────────────────────────────────────────────────────
 
export function AdminRrmInboxPage() {
	const queryClient = useQueryClient();
	const { data, isLoading, error } = useRrmInbox();
	const [selectedId, setSelectedId] = useState<string | null>(null);
	const [localeFilter, setLocaleFilter] = useState<RrmLocale | "all">("all");
	const [draft, setDraft] = useState("");
	const [localeOverride, setLocaleOverride] = useState<RrmLocale | null>(null);
	const [dncOpen, setDncOpen] = useState(false);
	const [busy, setBusy] = useState(false);
 
	const detailQuery = useRrmProspect(selectedId ?? undefined);
	// The API client wraps every payload in an `ApiResponse` envelope.
	const detail = detailQuery.data?.data;
 
	const conversations = data?.data ?? [];
	const unanswered = conversations.length;
 
	/**
	 * Computed from the UNFILTERED list, deliberately. If the operator has
	 * filtered to Telugu and the oldest waiting conversation is English, a strip
	 * built from the filtered rows would report a healthy backlog while the
	 * auto-pause clock runs. The chips narrow what is listed, never what is
	 * watched.
	 */
	const oldest = conversations[0] ?? null;
 
	const visible =
		localeFilter === "all"
			? conversations
			: conversations.filter((c) => c.locale === localeFilter);
 
	const selected =
		conversations.find((c) => c.prospectId === selectedId) ?? null;
 
	// Capture the title once, on mount, so the per-count effect below cannot
	// capture its own output as the value to restore.
	const originalTitle = useRef<string>("");
	useEffect(() => {
		originalTitle.current = document.title;
		return () => {
			document.title = originalTitle.current;
		};
	}, []);
 
	// The operator keeps this tab open all day. A backgrounded tab that reads
	// "(7) RRM Inbox" is the cheapest backlog alarm available.
	useEffect(() => {
		document.title = unanswered > 0 ? `(${unanswered}) RRM Inbox` : "RRM Inbox";
	}, [unanswered]);
 
	// The prospect record is the authority on locale; the reply UI only renders
	// once it has loaded, so there is no row-level fallback to reach for.
	const replyLocale: RrmLocale =
		localeOverride ?? detail?.prospect.locale ?? "en";
 
	const windowOpen = Boolean(
		detail?.windowExpiresAt &&
			new Date(detail.windowExpiresAt).getTime() > Date.now(),
	);
	const dnc = detail?.prospect.doNotContact ?? false;
 
	function handleSelect(prospectId: string) {
		setSelectedId(prospectId);
		setDraft("");
		setLocaleOverride(null);
	}
 
	function handleJump(prospectId: string) {
		// Also clears the filter: selecting a row that the current filter hides
		// leaves a thread on screen with no matching row, which reads as a bug.
		setLocaleFilter("all");
		handleSelect(prospectId);
	}
 
	async function run(fn: () => Promise<unknown>, success: string) {
		setBusy(true);
		try {
			await fn();
			queryClient.invalidateQueries({ queryKey: queryKeys.admin.rrm.all });
			notify.success(success);
		} catch {
			notify.error("That did not go through. Nothing was sent — try again.");
		} finally {
			setBusy(false);
		}
	}
 
	function handleInterested(prospectId: string) {
		void run(
			() =>
				adminRrmApi.sendMessage(
					prospectId,
					cannedReplyBody("your_page", replyLocale),
				),
			"Join link sent.",
		);
	}
 
	function handleSnooze(prospectId: string) {
		// Message first, snooze second, and only on success. P1-7.11 requires a
		// snoozed prospect to be TOLD — snoozing after a failed send would go
		// silent for sixty days and nothing on screen would say so. The reverse
		// failure (line sent, snooze refused) is visible and retryable.
		void run(async () => {
			await adminRrmApi.sendMessage(
				prospectId,
				cannedReplyBody("no_problem", replyLocale),
			);
			await adminRrmApi.snooze(prospectId, 60);
		}, "Told them we'll leave it, and snoozed for 60 days.");
	}
 
	function handleDnc(prospectId: string) {
		setDncOpen(false);
		// Same ordering, for a harder reason: once the prospect is marked DNC the
		// send engine refuses outbound messages, so the confirmation they were
		// promised has to leave first or it never leaves at all.
		void run(async () => {
			await adminRrmApi.sendMessage(
				prospectId,
				cannedReplyBody("understood_stopping", replyLocale),
			);
			await adminRrmApi.markDnc(
				prospectId,
				"Operator marked do-not-contact from inbox",
			);
		}, "Confirmation sent. This number will not be contacted again.");
	}
 
	function handleSend(prospectId: string) {
		const body = draft.trim();
		void run(async () => {
			await adminRrmApi.sendMessage(prospectId, body);
			setDraft("");
		}, "Reply sent.");
	}
 
	function insertCanned(key: CannedReplyKey) {
		const body = cannedReplyBody(key, replyLocale);
		// Inserts, never sends. Every canned line is an answer that usually needs
		// a sentence of its own attached before it goes out.
		setDraft((current) =>
			current.trim() ? `${current.trimEnd()}\n\n${body}` : body,
		);
	}
 
	const interestedFirstLine = firstLine(
		cannedReplyBody("your_page", replyLocale),
	);
	const snoozeFirstLine = firstLine(cannedReplyBody("no_problem", replyLocale));
	const dncFirstLine = firstLine(
		cannedReplyBody("understood_stopping", replyLocale),
	);
 
	return (
		<div className="space-y-4" data-testid="rrm-inbox-page">
			<div>
				<h1 className="font-heading text-2xl font-bold text-foreground-default">
					Partner inbox
				</h1>
				<p className="mt-1 text-sm text-foreground-muted">
					Oldest first, always. Backlog older than 24 hours pauses the campaign.
				</p>
			</div>
 
			{error ? (
				<div
					data-testid="inbox-error"
					className="rounded-lg border border-notification-error-border bg-notification-error-bg p-6 text-sm text-notification-error-text"
				>
					Could not load the inbox. The backlog clock is still running — refresh
					the page.
				</div>
			) : isLoading ? (
				<div data-testid="inbox-loading" className="space-y-4">
					<SkeletonList count={6} />
				</div>
			) : !oldest ? (
				<Card>
					<CardContent className="pt-6" data-testid="inbox-empty">
						<EmptyState
							icon={CheckCircle2}
							title="Inbox zero"
							description="Every partner has been answered. New replies land here within 30 seconds."
						/>
					</CardContent>
				</Card>
			) : (
				<>
					<SlaStrip
						oldest={oldest}
						unanswered={unanswered}
						onJump={() => handleJump(oldest.prospectId)}
					/>
 
					<div className="flex flex-col gap-4 lg:flex-row lg:items-start">
						{/* Left pane — conversation list */}
						<Card
							className={cn(
								"w-full lg:w-80 lg:shrink-0",
								selectedId && "hidden lg:block",
							)}
						>
							<div className="flex flex-wrap gap-2 border-b border-border-default p-3">
								<FilterChip
									label="All"
									count={conversations.length}
									active={localeFilter === "all"}
									onClick={() => setLocaleFilter("all")}
									testId="inbox-locale-filter-all"
								/>
								{LOCALES.map((locale) => (
									<FilterChip
										key={locale}
										label={locale}
										count={
											conversations.filter((c) => c.locale === locale).length
										}
										active={localeFilter === locale}
										onClick={() => setLocaleFilter(locale)}
										testId={`inbox-locale-filter-${locale}`}
									/>
								))}
							</div>
							<div className="max-h-[70vh] overflow-y-auto">
								{visible.length === 0 ? (
									<p
										data-testid="inbox-filter-empty"
										className="p-6 text-center text-sm text-foreground-muted"
									>
										Nothing waiting in this language. The strip above still
										shows the real oldest.
									</p>
								) : (
									visible.map((conversation) => (
										<ConversationRow
											key={conversation.prospectId}
											conversation={conversation}
											selected={conversation.prospectId === selectedId}
											onSelect={() => handleSelect(conversation.prospectId)}
										/>
									))
								)}
							</div>
						</Card>
 
						{/* Right pane — thread and triage */}
						<Card
							className={cn("min-w-0 flex-1", !selectedId && "hidden lg:block")}
						>
							{!selectedId || !detail ? (
								<CardContent className="pt-6">
									<EmptyState
										icon={MessageSquare}
										title="Pick a conversation"
										description={
											detailQuery.isLoading
												? "Loading the thread…"
												: "Start at the top — the list is ordered oldest-first."
										}
									/>
								</CardContent>
							) : (
								<div data-testid="inbox-thread">
									<div className="flex items-center gap-3 border-b border-border-default p-4">
										<Button
											variant="ghost"
											size="icon"
											className="lg:hidden"
											onClick={() => setSelectedId(null)}
											aria-label="Back to conversation list"
											data-testid="inbox-back"
										>
											<ArrowLeft className="h-5 w-5" />
										</Button>
										<div className="min-w-0 flex-1">
											<p className="truncate text-sm font-semibold text-foreground-default">
												{detail.prospect.name ??
													detail.prospect.firmName ??
													detail.prospect.phoneNorm}
											</p>
											<p className="truncate text-xs text-foreground-muted">
												{detail.prospect.phoneNorm} ·{" "}
												{LOCALE_LABELS[detail.prospect.locale]}
											</p>
										</div>
										<StageBadge stage={detail.prospect.stage} />
									</div>
 
									<div className="max-h-[45vh] space-y-3 overflow-y-auto p-4">
										{detail.messages.length === 0 ? (
											<p className="text-sm text-foreground-muted">
												No messages on this thread yet.
											</p>
										) : (
											detail.messages.map((message) => (
												<MessageBubble key={message.id} message={message} />
											))
										)}
									</div>
 
									{dnc ? (
										<div
											data-testid="dnc-notice"
											className="m-4 flex items-start gap-2 rounded-lg border border-error bg-error-light p-3 text-sm text-error"
										>
											<Ban
												className="mt-0.5 h-4 w-4 shrink-0"
												aria-hidden="true"
											/>
											<p>
												This number is marked do-not-contact. Nothing further
												can be sent from here.
											</p>
										</div>
									) : (
										<div className="border-t border-border-default p-4">
											{selected?.needsOptOutReview && (
												<div
													data-testid="optout-review-warning"
													className="mb-4 flex items-start gap-2 rounded-lg border border-warning bg-warning-light p-3 text-sm text-warning"
												>
													<ShieldAlert
														className="mt-0.5 h-4 w-4 shrink-0"
														aria-hidden="true"
													/>
													<p>
														This reply reads as a possible opt-out. Read it
														before you answer — the engine has already erred
														toward stopping, and sending a join link here would
														be the worst available reply.
													</p>
												</div>
											)}
 
											{/* Triage — three one-click actions. Each carries a
											    Tooltip showing the first line of what it will send. */}
											<div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap">
												<TriageAction
													tooltip={
														selected?.needsOptOutReview
															? "Disabled: this reply reads as a possible opt-out. Confirm what they meant before sending a join link."
															: `Sends: "${interestedFirstLine}"`
													}
												>
													<Button
														size="sm"
														onClick={() => handleInterested(selectedId)}
														disabled={busy || selected?.needsOptOutReview}
														data-testid="triage-interested"
													>
														Interested — send link
													</Button>
												</TriageAction>
 
												<TriageAction
													tooltip={`One click, two effects. Sends: "${snoozeFirstLine}" — then snoozes them for 60 days.`}
												>
													<Button
														variant="outline"
														size="sm"
														onClick={() => handleSnooze(selectedId)}
														disabled={busy}
														data-testid="triage-snooze"
													>
														Not now — snooze 60d
													</Button>
												</TriageAction>
 
												<TriageAction
													tooltip={`Permanent. Sends one confirmation: "${dncFirstLine}" — then never contacts this number again.`}
												>
													<Button
														variant="destructive"
														size="sm"
														onClick={() => setDncOpen(true)}
														disabled={busy}
														data-testid="triage-dnc"
													>
														Never — mark DNC
													</Button>
												</TriageAction>
											</div>
 
											{/* Lives inside the thread pane so it cannot outlive the
											    conversation it would act on. */}
											<ConfirmDialog
												open={dncOpen}
												variant="destructive"
												title="Never contact this number again?"
												description="This is permanent. They will receive one confirmation message saying we have stopped, and will never be contacted again — no second number, no future campaign, nothing."
												confirmLabel="Mark do-not-contact"
												onConfirm={() => handleDnc(selectedId)}
												onCancel={() => setDncOpen(false)}
											/>
 
											{/* Canned replies — insert, never send. */}
											<div className="mt-4">
												<div className="flex items-center justify-between gap-2">
													<p className="text-xs font-medium text-foreground-muted">
														Canned replies
													</p>
													<label className="flex items-center gap-2 text-xs text-foreground-muted">
														Language
														<select
															aria-label="Canned reply language"
															data-testid="reply-locale-select"
															value={replyLocale}
															onChange={(e) =>
																setLocaleOverride(e.target.value as RrmLocale)
															}
															className="h-8 rounded-md border border-border-default bg-background-base px-2 text-xs text-foreground-default focus:outline-none focus:ring-2 focus:ring-primary-500"
														>
															{LOCALES.map((locale) => (
																<option key={locale} value={locale}>
																	{LOCALE_LABELS[locale]}
																</option>
															))}
														</select>
													</label>
												</div>
												<div className="mt-2 flex gap-2 overflow-x-auto pb-2">
													{CANNED_REPLY_ORDER.map((key) => (
														<button
															key={key}
															type="button"
															onClick={() => insertCanned(key)}
															data-testid={`canned-chip-${key}`}
															className="shrink-0 rounded-full border border-border-default bg-background-subtle px-3 py-1 text-xs font-medium text-foreground-default transition-colors hover:bg-background-muted"
														>
															{cannedReplyLabel(key, replyLocale)}
														</button>
													))}
												</div>
											</div>
 
											{/* Reply box */}
											<textarea
												value={draft}
												onChange={(e) => setDraft(e.target.value)}
												rows={3}
												aria-label="Reply message"
												data-testid="reply-textarea"
												disabled={!windowOpen}
												placeholder={
													windowOpen
														? "Write a reply, or tap a chip above to insert one."
														: "The 24-hour window is closed."
												}
												className="mt-2 w-full rounded-md border border-border-default bg-background-base p-3 text-sm text-foreground-default focus:outline-none focus:ring-2 focus:ring-primary-500 disabled:bg-background-muted disabled:text-foreground-subtle"
											/>
 
											{!windowOpen && (
												<p
													data-testid="window-closed-notice"
													className="mt-2 text-xs text-warning"
												>
													The 24-hour free-form window has closed. Only an
													approved template can reach this person now — the API
													will refuse a plain reply.
												</p>
											)}
 
											<div className="mt-2 flex justify-end">
												<Button
													size="sm"
													onClick={() => handleSend(selectedId)}
													disabled={busy || !windowOpen || !draft.trim()}
													data-testid="reply-send"
												>
													<Send className="h-4 w-4" />
													Send reply
												</Button>
											</div>
										</div>
									)}
								</div>
							)}
						</Card>
					</div>
				</>
			)}
		</div>
	);
}
 
// ─── Small parts ─────────────────────────────────────────────────────────────
 
function FilterChip({
	label,
	count,
	active,
	onClick,
	testId,
}: {
	label: string;
	count: number;
	active: boolean;
	onClick: () => void;
	testId: string;
}) {
	return (
		<button
			type="button"
			onClick={onClick}
			aria-pressed={active}
			data-testid={testId}
			className={cn(
				"rounded-full border px-3 py-1 text-xs font-medium transition-colors",
				active
					? "border-primary-500 bg-primary-500 text-foreground-inverse"
					: "border-border-default bg-background-subtle text-foreground-muted hover:bg-background-muted",
			)}
		>
			{label} <span className="tabular-nums">({count})</span>
		</button>
	);
}
 
/**
 * The Tooltip primitive renders its children INSIDE its own `<button>`, so
 * wrapping an action button in it would nest buttons — and `Button` carries
 * `disabled:pointer-events-none`, which means a wrapping tooltip could never
 * fire on the disabled "Interested" button, the one case where the operator
 * most needs to be told why. The trigger therefore sits beside the action.
 */
function TriageAction({
	tooltip,
	children,
}: {
	tooltip: string;
	children: ReactNode;
}) {
	return (
		<span className="inline-flex items-center gap-1.5">
			{children}
			<Tooltip content={tooltip} />
		</span>
	);
}