All files / src/pages/admin/rrm prospect-detail.tsx

98.16% Statements 107/109
95.96% Branches 119/124
100% Functions 36/36
100% Lines 102/102

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 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954                                                                                                                                      1x     1x   1x   1x                             1x                                                                                                                                                                                                                                                                         1x                       1x                                         6x 2x 2x 7x 5x 3x   2x       1x 1x       7x 7x                                     6x       6x                                                 56x 56x     7x     56x 5x         8x 8x                                                                                           88x 86x             1x                             85x                                                             6x 6x                                                                                           1x                       88x 88x 88x 88x 88x 88x   88x 88x 88x 88x 88x 88x   88x 88x 51x       88x   87x 2x                                                   85x 85x 85x   85x             5x       9x 9x 9x 9x   2x   9x         3x     3x 3x 3x 2x 2x 2x             4x 4x 4x             3x 2x             1x 1x               1x 1x 1x 1x               1x 1x 1x 1x 1x                         2x 2x   1x     1x         88x 88x   88x                                                                                                                   4x                                                                               8x                                                   4x         1020x                                                                   3x                           4x                                                                                                                                                                               6x                                     1x                   1x              
import { useQueryClient } from "@tanstack/react-query";
import { Link, useNavigate, useParams } from "@tanstack/react-router";
import type { LucideIcon } from "lucide-react";
import {
	AlertTriangle,
	ArrowDownLeft,
	ArrowRight,
	ArrowUpRight,
	Ban,
	Bot,
	CheckCircle2,
	ClipboardList,
	Clock,
	Download,
	ExternalLink,
	Eye,
	FileText,
	History,
	Link2,
	MessageCircle,
	MousePointerClick,
	RotateCcw,
	Send,
	StickyNote,
	Trash2,
	XCircle,
} from "lucide-react";
import { useMemo, useState } from "react";
 
import { Button } from "../../../components/ui/button";
import {
	Card,
	CardContent,
	CardHeader,
	CardTitle,
} from "../../../components/ui/card";
import { ConfirmDialog } from "../../../components/ui/confirm-dialog";
import { EmptyState } from "../../../components/ui/empty-state";
import { Skeleton } from "../../../components/ui/skeleton";
import { StatusBadge } from "../../../components/ui/status-badge";
import {
	useRrmDeleteProspect,
	useRrmProspect,
} from "../../../hooks/queries/useRrmQueries";
import {
	adminRrmApi,
	type RrmEvent,
	type RrmMessage,
	type RrmProspect,
	type RrmStage,
	type RrmSubmissionSummary,
} from "../../../lib/api/admin/rrm";
import { getErrorMessage } from "../../../lib/api/base";
import { useAuth } from "../../../lib/auth-context";
import { queryKeys } from "../../../lib/query-keys";
import { partnerInviteUrl } from "../../../lib/rrm/invite-link";
import { cn } from "../../../lib/utils";
import {
	formatDateTime,
	formatRelative,
	LOCALE_LABELS,
	RrmStageBadge,
	STAGE_LABELS,
	STAGE_OPTIONS,
} from "./prospects";
 
/** Recorded against every operator-driven stage write, so the event log says who moved it. */
const MANUAL_STAGE_REASON = "Changed by an operator from the prospect screen";
 
/** `rrm_dnc_reasons` is an enum column; free text here would be a guaranteed 400. */
const MANUAL_DNC_REASON = "manual";
 
const SNOOZE_DAYS = 60;
 
const SOURCE_LABELS: Record<string, string> = {
	maps: "Google Maps listing",
	justdial: "Justdial listing",
	field: "Field visit",
	referral: "Referral",
	manual: "Entered by hand",
	organic: "Signed up on the partner page",
};
 
// ─── Merged timeline ─────────────────────────────────────────────────────────
 
/** What draws the dot next to an entry. Messages have no label of their own. */
type Marker = { icon: LucideIcon; tone: string };
type EventStyle = Marker & { label: string };
 
const EVENT_STYLES: Record<string, EventStyle> = {
	imported: {
		icon: Download,
		label: "Imported into the campaign",
		tone: "text-foreground-muted bg-background-muted",
	},
	queued: {
		icon: Clock,
		label: "Queued to send",
		tone: "text-info bg-info-light",
	},
	message_sent: {
		icon: ArrowUpRight,
		label: "Message sent",
		tone: "text-primary-600 bg-primary-100",
	},
	message_delivered: {
		icon: CheckCircle2,
		label: "Message delivered",
		tone: "text-info bg-info-light",
	},
	message_read: {
		icon: Eye,
		label: "Message read",
		tone: "text-info bg-info-light",
	},
	message_failed: {
		icon: XCircle,
		label: "Message failed",
		tone: "text-error bg-error-light",
	},
	message_received: {
		icon: ArrowDownLeft,
		label: "Message received",
		tone: "text-success bg-success-light",
	},
	window_opened: {
		icon: Clock,
		label: "24-hour window opened",
		tone: "text-success bg-success-light",
	},
	window_closed: {
		icon: Clock,
		label: "24-hour window closed",
		tone: "text-foreground-muted bg-background-muted",
	},
	page_visited: {
		icon: MousePointerClick,
		label: "Opened the partner page",
		tone: "text-secondary-600 bg-secondary-100",
	},
	bot_preview: {
		icon: Bot,
		label: "Link preview fetched by a bot",
		tone: "text-foreground-subtle bg-background-muted",
	},
	form_submitted: {
		icon: FileText,
		label: "Submitted the form",
		tone: "text-secondary-600 bg-secondary-100",
	},
	cta_clicked: {
		icon: MousePointerClick,
		label: "Clicked a call to action",
		tone: "text-secondary-600 bg-secondary-100",
	},
	link_clicked: {
		icon: Link2,
		label: "Clicked a link",
		tone: "text-secondary-600 bg-secondary-100",
	},
	stage_changed: {
		icon: ArrowRight,
		label: "Stage changed",
		tone: "text-foreground-default bg-background-muted",
	},
	opted_out: {
		icon: Ban,
		label: "Opted out",
		tone: "text-error bg-error-light",
	},
	snoozed: {
		icon: Clock,
		label: "Snoozed",
		tone: "text-warning bg-warning-light",
	},
	task_created: {
		icon: ClipboardList,
		label: "Task raised",
		tone: "text-info bg-info-light",
	},
	task_completed: {
		icon: CheckCircle2,
		label: "Task completed",
		tone: "text-success bg-success-light",
	},
	note_added: {
		icon: StickyNote,
		label: "Note added",
		tone: "text-foreground-default bg-background-muted",
	},
	deletion_requested: {
		icon: AlertTriangle,
		label: "Deletion requested",
		tone: "text-warning bg-warning-light",
	},
	deleted: {
		icon: Trash2,
		label: "Personal data erased",
		tone: "text-error bg-error-light",
	},
	send_blocked: {
		icon: Ban,
		label: "Send blocked",
		tone: "text-error bg-error-light",
	},
	requeued: {
		icon: RotateCcw,
		label: "Requeued",
		tone: "text-info bg-info-light",
	},
	confirm_intent_requested: {
		icon: ClipboardList,
		label: "Intent confirmation requested",
		tone: "text-warning bg-warning-light",
	},
	intent_confirmed: {
		icon: CheckCircle2,
		label: "Referral intent confirmed",
		tone: "text-success bg-success-light",
	},
};
 
const FALLBACK_STYLE: EventStyle = {
	icon: History,
	label: "Event",
	tone: "text-foreground-muted bg-background-muted",
};
 
/**
 * These events restate what a message row already shows — the body, and its
 * latest status. Rendering both makes the operator read the same send twice.
 * They are kept when `messages` is empty so a response that only populates
 * `timeline` still shows its sends rather than nothing at all.
 */
const MESSAGE_LIFECYCLE_EVENTS = new Set([
	"message_sent",
	"message_delivered",
	"message_read",
	"message_failed",
	"message_received",
]);
 
type TimelineEntry = {
	key: string;
	at: string;
	style: Marker;
	title: string;
	body: string | null;
	meta: string | null;
};
 
/** Flattens the primitive payload keys an operator can act on into one line. */
function summarisePayload(
	payload: Record<string, unknown> | null,
): string | null {
	if (!payload) return null;
	const parts: string[] = [];
	for (const [key, value] of Object.entries(payload)) {
		if (value === null || value === undefined) continue;
		if (typeof value === "object") continue;
		parts.push(`${key.replace(/_/g, " ")}: ${String(value)}`);
	}
	return parts.length > 0 ? parts.join(" · ") : null;
}
 
function humaniseType(type: string): string {
	const word = type.replace(/_/g, " ");
	return word.charAt(0).toUpperCase() + word.slice(1);
}
 
function messageEntry(message: RrmMessage): TimelineEntry {
	const outbound = message.direction === "outbound";
	return {
		key: `msg-${message.id}`,
		at: message.dateCreated,
		style: outbound
			? { icon: ArrowUpRight, tone: "text-primary-600 bg-primary-100" }
			: { icon: ArrowDownLeft, tone: "text-success bg-success-light" },
		title: outbound ? "We sent" : "They sent",
		body: message.body,
		meta: [
			message.templateName ? `template ${message.templateName}` : null,
			message.status,
			message.stepKey ? `step ${message.stepKey}` : null,
		]
			.filter(Boolean)
			.join(" · "),
	};
}
 
function eventEntry(event: RrmEvent): TimelineEntry {
	const style = EVENT_STYLES[event.type] ?? {
		...FALLBACK_STYLE,
		label: humaniseType(event.type),
	};
	return {
		key: `evt-${event.id}`,
		at: event.occurredAt,
		style,
		title: style.label,
		body: null,
		meta: [
			summarisePayload(event.payload),
			event.channel,
			`by ${event.actorType}`,
		]
			.filter(Boolean)
			.join(" · "),
	};
}
 
/**
 * Newest first. Two lists — messages and events — are one story, and an
 * operator answering "what happened to this person?" must never have to
 * reconcile them by hand.
 */
export function buildTimeline(
	events: RrmEvent[],
	messages: RrmMessage[],
): TimelineEntry[] {
	const suppress = messages.length > 0;
	const entries = [
		...messages.map(messageEntry),
		...events
			.filter((e) => !(suppress && MESSAGE_LIFECYCLE_EVENTS.has(e.type)))
			.map(eventEntry),
	];
	return entries.sort(
		(a, b) => new Date(b.at).getTime() - new Date(a.at).getTime(),
	);
}
 
function TimelineRow({ entry }: { entry: TimelineEntry }) {
	const Icon = entry.style.icon;
	return (
		<li
			className="relative flex gap-3 pb-5 last:pb-0"
			data-testid="rrm-timeline-entry"
		>
			<div
				className={cn(
					"flex h-7 w-7 items-center justify-center rounded-full flex-shrink-0",
					entry.style.tone,
				)}
			>
				<Icon className="h-3.5 w-3.5" aria-hidden="true" />
			</div>
			<div className="flex-1 min-w-0">
				<p className="text-sm font-medium text-foreground-default">
					{entry.title}
				</p>
				{entry.body && (
					<p className="mt-1 text-sm text-foreground-default whitespace-pre-wrap break-words rounded-md bg-background-subtle p-2">
						{entry.body}
					</p>
				)}
				{entry.meta && (
					<p className="mt-1 text-xs text-foreground-subtle break-words">
						{entry.meta}
					</p>
				)}
				<span
					className="text-xs text-foreground-subtle"
					title={formatDateTime(entry.at)}
				>
					{formatRelative(entry.at)}
				</span>
			</div>
		</li>
	);
}
 
// ─── Window ──────────────────────────────────────────────────────────────────
 
/**
 * One boolean drives both the badge and the reply box, so they can never
 * disagree. A non-null expiry that has already passed is a closed window — a
 * page left open across the boundary must not keep offering a free-form reply.
 */
export function isWindowOpen(windowExpiresAt: string | null): boolean {
	if (!windowExpiresAt) return false;
	return new Date(windowExpiresAt).getTime() > Date.now();
}
 
// ─── Page ────────────────────────────────────────────────────────────────────
 
type ActionResult = { tone: "success" | "info" | "error"; message: string };
 
const RESULT_TONES: Record<ActionResult["tone"], string> = {
	success: "text-success",
	info: "text-foreground-default",
	error: "text-error",
};
 
function IdentityBadges({
	prospect,
	windowOpen,
	windowExpiresAt,
}: {
	prospect: RrmProspect;
	windowOpen: boolean;
	windowExpiresAt: string | null;
}) {
	return (
		<div className="flex flex-wrap items-center gap-2">
			<RrmStageBadge stage={prospect.stage} />
			<StatusBadge
				status={prospect.tier ? `Tier ${prospect.tier}` : "Untiered"}
				variant={prospect.tier ? "info" : "default"}
			/>
			<StatusBadge status={LOCALE_LABELS[prospect.locale]} variant="default" />
			<span data-testid="rrm-window-badge">
				<StatusBadge
					status={windowOpen ? "24h window open" : "24h window closed"}
					variant={windowOpen ? "success" : "default"}
				/>
			</span>
			{windowOpen && windowExpiresAt && (
				<span className="text-xs text-foreground-subtle">
					closes {formatDateTime(windowExpiresAt)}
				</span>
			)}
			{prospect.doNotContact && (
				<StatusBadge status="Do not contact" variant="error" />
			)}
		</div>
	);
}
 
/**
 * What they told us on the form (3.3) — the referral's contact details
 * otherwise exist only as free text in a Tasks note.
 */
function SubmissionRow({ submission }: { submission: RrmSubmissionSummary }) {
	const isReferral = submission.cta === "have_contact";
	return (
		<li
			className="space-y-1 border-b border-border-default pb-4 last:border-0 last:pb-0"
			data-testid="rrm-submission-row"
		>
			<div className="flex items-center justify-between gap-2">
				<span className="text-sm font-medium text-foreground-default">
					{isReferral ? "Referral" : "Interested"}
				</span>
				<span
					className="text-xs text-foreground-subtle"
					title={formatDateTime(submission.dateCreated)}
				>
					{formatRelative(submission.dateCreated)}
				</span>
			</div>
			{isReferral && (
				<p className="text-sm text-foreground-default">
					{submission.contactName ?? "Unnamed contact"}
					{submission.contactPhoneNorm
						? ` · ${submission.contactPhoneNorm}`
						: ""}
					{submission.contactProject ? ` · ${submission.contactProject}` : ""}
				</p>
			)}
			<div className="flex flex-wrap items-center gap-2 text-xs text-foreground-subtle">
				<span className="font-mono">
					{submission.sourceDetail ?? "no source captured"}
				</span>
				{submission.contactConsentAsserted && (
					<span className="inline-flex items-center gap-1 text-success">
						<CheckCircle2 className="h-3.5 w-3.5" aria-hidden="true" />
						Consent asserted
					</span>
				)}
			</div>
			{submission.duplicateOfSubmissionId && (
				<p className="text-xs text-warning">
					Already referred — first submission wins
				</p>
			)}
		</li>
	);
}
 
function DetailSkeleton() {
	return (
		<div className="space-y-6" data-testid="rrm-prospect-detail-skeleton">
			<Skeleton className="h-24 w-full" />
			<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
				<Skeleton className="h-72 w-full lg:col-span-2" />
				<Skeleton className="h-72 w-full" />
			</div>
		</div>
	);
}
 
export function AdminRrmProspectDetailPage() {
	const { prospectId } = useParams({ strict: false });
	const navigate = useNavigate();
	const queryClient = useQueryClient();
	const { isSuperAdmin } = useAuth();
	const { data, isLoading, error } = useRrmProspect(prospectId);
	const deleteProspect = useRrmDeleteProspect();
 
	const [reply, setReply] = useState("");
	const [nextStage, setNextStage] = useState("");
	const [pending, setPending] = useState<string | null>(null);
	const [result, setResult] = useState<ActionResult | null>(null);
	const [dncOpen, setDncOpen] = useState(false);
	const [deleteOpen, setDeleteOpen] = useState(false);
 
	const detail = data?.data;
	const timeline = useMemo(
		() => buildTimeline(detail?.timeline ?? [], detail?.messages ?? []),
		[detail],
	);
 
	if (isLoading) return <DetailSkeleton />;
 
	if (error || !detail) {
		return (
			<Card data-testid="rrm-prospect-detail-error">
				<CardContent className="pt-6">
					<EmptyState
						icon={AlertTriangle}
						title={
							error ? "Could not load this prospect" : "Prospect not found"
						}
						description={
							error
								? getErrorMessage(error)
								: "This prospect may have been erased under a deletion request."
						}
					>
						<Link
							to="/admin/rrm/prospects"
							className="text-sm font-medium text-primary-600 hover:underline"
						>
							Back to prospects
						</Link>
					</EmptyState>
				</CardContent>
			</Card>
		);
	}
 
	const { prospect, windowExpiresAt } = detail;
	const windowOpen = isWindowOpen(windowExpiresAt);
	const id = prospect.id;
 
	const replyBlockedReason = prospect.doNotContact
		? "This person is marked do-not-contact, so nothing may be sent to them — not a template, not a reply."
		: windowOpen
			? null
			: "The 24-hour service window is closed. WhatsApp only allows a free-form reply within 24 hours of their last message, so this box stays disabled until they message again.";
 
	function invalidate() {
		queryClient.invalidateQueries({ queryKey: queryKeys.admin.rrm.all });
	}
 
	async function run(action: string, work: () => Promise<ActionResult>) {
		setPending(action);
		setResult(null);
		try {
			setResult(await work());
		} catch (err) {
			setResult({ tone: "error", message: getErrorMessage(err) });
		} finally {
			setPending(null);
		}
	}
 
	async function handleSend() {
		const body = reply.trim();
		// The Send button is already disabled for this, but the guard is what a
		// second caller — a keyboard shortcut, a canned-reply chip — will hit.
		Iif (!body) return;
		await run("reply", async () => {
			await adminRrmApi.sendMessage(id, body);
			setReply("");
			invalidate();
			return { tone: "success", message: "Reply sent." };
		});
	}
 
	async function handleStage() {
		// Same reasoning as handleSend: the disabled Apply button is the
		// affordance, this is the rule.
		Iif (!nextStage) return;
		await run("stage", async () => {
			const response = await adminRrmApi.setStage(
				id,
				nextStage as RrmStage,
				MANUAL_STAGE_REASON,
			);
			// A refusal is the stage machine working, not a failure. Saying so is
			// the difference between "the rule held" and "the button is broken".
			if (response.data && !response.data.changed) {
				return {
					tone: "info",
					message: `Stage left at ${STAGE_LABELS[prospect.stage]} — ${
						response.data.reason ?? "the stage rule refused this move"
					}.`,
				};
			}
			invalidate();
			return {
				tone: "success",
				message: `Stage set to ${STAGE_LABELS[nextStage as RrmStage]}.`,
			};
		});
	}
 
	async function handleSnooze() {
		await run("snooze", async () => {
			await adminRrmApi.snooze(id, SNOOZE_DAYS);
			invalidate();
			return {
				tone: "success",
				message: `Snoozed for ${SNOOZE_DAYS} days. Nothing will be sent until then.`,
			};
		});
	}
 
	async function handleDnc() {
		setDncOpen(false);
		await run("dnc", async () => {
			await adminRrmApi.markDnc(id, MANUAL_DNC_REASON);
			invalidate();
			return {
				tone: "success",
				message: "Marked do-not-contact. This cannot be undone.",
			};
		});
	}
 
	/**
	 * Navigates away on success rather than waiting on `invalidate()` — the
	 * row is gone, so the detail query it would trigger can only come back
	 * 404 and flash an error state on a page that is about to unmount anyway.
	 */
	function handleDelete() {
		setDeleteOpen(false);
		deleteProspect.mutate(id, {
			onSuccess: () => {
				navigate({ to: "/admin/rrm/signups" });
			},
			onError: (err) => {
				setResult({ tone: "error", message: getErrorMessage(err) });
			},
		});
	}
 
	const markets = prospect.microMarkets ?? [];
	const sourceDetail = prospect.sourceDetail;
 
	return (
		<div className="space-y-6" data-testid="rrm-prospect-detail">
			<Link
				to="/admin/rrm/prospects"
				className="inline-block text-sm text-foreground-muted hover:text-foreground-default"
			>
				← All prospects
			</Link>
 
			<Card data-testid="rrm-prospect-identity">
				<CardContent className="pt-6 space-y-3">
					<div>
						<h1 className="font-heading text-xl sm:text-2xl font-bold text-foreground-default">
							{prospect.name ?? "Unnamed prospect"}
						</h1>
						<p className="text-sm text-foreground-muted">
							{prospect.firmName ?? "No firm recorded"}
							{markets.length > 0 ? ` · ${markets.join(", ")}` : ""}
						</p>
						<p className="mt-1 font-mono text-sm text-foreground-default">
							+{prospect.phoneNorm}
						</p>
					</div>
					{/* Never offer a by-hand opener to someone who has opted out. */}
					{!prospect.doNotContact && (
						<Button asChild variant="outline" size="sm">
							<a
								href={partnerInviteUrl(prospect)}
								target="_blank"
								rel="noopener noreferrer"
								data-testid="rrm-prospect-whatsapp-invite"
							>
								<MessageCircle aria-hidden="true" />
								Invite on WhatsApp
							</a>
						</Button>
					)}
					<IdentityBadges
						prospect={prospect}
						windowOpen={windowOpen}
						windowExpiresAt={windowExpiresAt}
					/>
				</CardContent>
			</Card>
 
			<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
				<div className="lg:col-span-2 space-y-6">
					<Card data-testid="rrm-reply-box">
						<CardHeader>
							<CardTitle className="text-lg">Reply</CardTitle>
						</CardHeader>
						<CardContent className="space-y-3">
							<textarea
								aria-label="Reply message"
								data-testid="rrm-reply-input"
								rows={3}
								value={reply}
								disabled={replyBlockedReason !== null}
								onChange={(e) => setReply(e.target.value)}
								placeholder={
									replyBlockedReason ? "" : "Type a reply in their language…"
								}
								className="w-full rounded-md border border-border-default bg-background-elevated px-3 py-2 text-sm text-foreground-default placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
							/>
							{replyBlockedReason && (
								<p
									className="text-sm text-warning"
									data-testid="rrm-reply-blocked-reason"
								>
									{replyBlockedReason}
								</p>
							)}
							<Button
								data-testid="rrm-reply-send"
								disabled={replyBlockedReason !== null || reply.trim() === ""}
								isLoading={pending === "reply"}
								onClick={handleSend}
							>
								<Send aria-hidden="true" />
								Send
							</Button>
						</CardContent>
					</Card>
 
					<Card>
						<CardHeader>
							<CardTitle className="text-lg">History</CardTitle>
						</CardHeader>
						<CardContent>
							{timeline.length === 0 ? (
								<EmptyState
									icon={History}
									title="Nothing has happened yet"
									description="Messages, page visits, stage changes and tasks all appear here as one list."
								/>
							) : (
								<ul className="space-y-0" data-testid="rrm-timeline">
									{timeline.map((entry) => (
										<TimelineRow key={entry.key} entry={entry} />
									))}
								</ul>
							)}
						</CardContent>
					</Card>
				</div>
 
				<div className="space-y-6">
					<Card data-testid="rrm-quick-actions">
						<CardHeader>
							<CardTitle className="text-lg">Actions</CardTitle>
						</CardHeader>
						<CardContent className="space-y-4">
							<div className="space-y-2">
								<label
									htmlFor="rrm-stage-select"
									className="block text-sm font-medium text-foreground-default"
								>
									Move stage
								</label>
								<div className="flex gap-2">
									<select
										id="rrm-stage-select"
										data-testid="rrm-stage-select"
										value={nextStage}
										onChange={(e) => setNextStage(e.target.value)}
										className="h-10 flex-1 rounded-md border border-border-default bg-background-base px-3 py-2 text-sm text-foreground-default focus:outline-none focus:ring-2 focus:ring-primary-500"
									>
										<option value="">Choose a stage…</option>
										{STAGE_OPTIONS.map((value) => (
											<option key={value} value={value}>
												{STAGE_LABELS[value]}
											</option>
										))}
									</select>
									<Button
										variant="outline"
										data-testid="rrm-stage-apply"
										disabled={!nextStage}
										isLoading={pending === "stage"}
										onClick={handleStage}
									>
										Apply
									</Button>
								</div>
							</div>
 
							<Button
								variant="outline"
								className="w-full"
								data-testid="rrm-snooze"
								isLoading={pending === "snooze"}
								onClick={handleSnooze}
							>
								<Clock aria-hidden="true" />
								Snooze {SNOOZE_DAYS} days
							</Button>
 
							<Button
								variant="destructive"
								className="w-full"
								data-testid="rrm-mark-dnc"
								disabled={prospect.doNotContact}
								isLoading={pending === "dnc"}
								onClick={() => setDncOpen(true)}
							>
								<Ban aria-hidden="true" />
								{prospect.doNotContact
									? "Already do-not-contact"
									: "Mark do-not-contact"}
							</Button>
 
							{isSuperAdmin && (
								<Button
									variant="destructive"
									className="w-full"
									data-testid="rrm-delete-test-data"
									isLoading={deleteProspect.isPending}
									onClick={() => setDeleteOpen(true)}
								>
									<Trash2 aria-hidden="true" />
									Delete (test data)
								</Button>
							)}
 
							{result && (
								<p
									role="status"
									data-testid="rrm-action-result"
									className={cn("text-sm", RESULT_TONES[result.tone])}
								>
									{result.message}
								</p>
							)}
						</CardContent>
					</Card>
 
					<Card data-testid="rrm-provenance">
						<CardHeader>
							<CardTitle className="text-lg">Provenance</CardTitle>
						</CardHeader>
						<CardContent className="space-y-2 text-sm">
							{/* "Where did you get my number?" is the likeliest question in this
							    campaign, so the answer sits on the screen the operator is
							    already looking at. */}
							<p className="text-foreground-muted">
								If they ask where their number came from, read this out.
							</p>
							<p className="text-foreground-default">
								{SOURCE_LABELS[prospect.source] ?? prospect.source}
							</p>
							{sourceDetail?.sourceLabel && (
								<p
									data-testid="rrm-provenance-source-label"
									className="text-foreground-muted"
								>
									Came in via{" "}
									<span className="font-mono text-foreground-default">
										{sourceDetail.sourceLabel}
									</span>
								</p>
							)}
							{sourceDetail?.listingUrl && (
								<a
									href={sourceDetail.listingUrl}
									target="_blank"
									rel="noreferrer"
									data-testid="rrm-provenance-listing"
									className="inline-flex items-center gap-1 text-primary-600 hover:underline break-all"
								>
									<ExternalLink className="h-3.5 w-3.5" aria-hidden="true" />
									{sourceDetail.listingUrl}
								</a>
							)}
							{sourceDetail?.scrapedAt && (
								<p className="text-foreground-muted">
									Captured {formatDateTime(sourceDetail.scrapedAt)}
								</p>
							)}
							{sourceDetail?.page !== undefined && (
								<p className="text-foreground-muted">
									Results page {sourceDetail.page}
								</p>
							)}
							{!sourceDetail?.listingUrl && !sourceDetail?.sourceLabel && (
								<p className="text-foreground-muted">
									No listing was captured for this row — only the source above.
								</p>
							)}
						</CardContent>
					</Card>
 
					<Card data-testid="rrm-submissions">
						<CardHeader>
							<CardTitle className="text-lg">Submissions</CardTitle>
						</CardHeader>
						<CardContent>
							{detail.submissions.length === 0 ? (
								<EmptyState
									icon={FileText}
									title="No submissions"
									description="This prospect has not filled in the partner page form."
								/>
							) : (
								<ul className="space-y-4" data-testid="rrm-submissions-list">
									{detail.submissions.map((submission) => (
										<SubmissionRow
											key={submission.id}
											submission={submission}
										/>
									))}
								</ul>
							)}
						</CardContent>
					</Card>
				</div>
			</div>
 
			<ConfirmDialog
				open={dncOpen}
				title="Mark do-not-contact?"
				description="This is permanent. They are removed from every sequence, no message of any kind can be sent to them again, and this cannot be undone from the portal."
				confirmLabel="Mark do-not-contact"
				variant="destructive"
				onConfirm={handleDnc}
				onCancel={() => setDncOpen(false)}
			/>
 
			<ConfirmDialog
				open={deleteOpen}
				title="Delete this test prospect?"
				description="This is a hard delete for cleaning up test data — it removes the row and everything attached to it (submissions, events, messages) with no undo. It is NOT the DPDP erasure a real prospect can request, which scrubs personal data but keeps the record. Only use this on rows you know are test data."
				confirmLabel="Delete permanently"
				variant="destructive"
				onConfirm={handleDelete}
				onCancel={() => setDeleteOpen(false)}
			/>
		</div>
	);
}
 
export default AdminRrmProspectDetailPage;