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

97.26% Statements 142/146
91.85% Branches 124/135
100% Functions 45/45
99.23% Lines 129/130

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                                                                    6x                     6x         6x                               6x                                           6x                             6x           6x     303x                                   6x 6x 6x       518x                     571x 571x 571x 570x 569x 568x 97x 97x 39x                 6x 6x     1x     8x                     6x                         165x 165x   165x           1x       3x 3x 2x 2x                   12x 12x                               1x                                                                                         6x         132x   132x 132x 132x 132x 132x     132x 132x 132x       132x 132x         132x 132x 132x     132x 132x     4x 4x 4x 4x 4x 3x   1x   4x 4x                   14x 14x 14x       5x 5x     132x   132x                 132x   132x                 132x 132x 44x 44x 44x 61x   44x                 132x 132x 132x   132x     132x       132x     8x 8x 8x       1x 1x 1x 1x 1x 1x       3x       2x   3x 2x         12x 12x 12x     12x   12x         4x 4x 4x 4x 4x 4x         3x 4x   1x         132x   132x                           5x 5x               4x                                                                           2x                                                       1x                 3x       1584x                     3x       528x                     1x       82x                                                                                                                                                                           175x                                                               1x                 4x                                                     1x                                                                                    
import { useNavigate } from "@tanstack/react-router";
import { MessageCircle, Upload, Users } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
 
import { Button } from "../../../components/ui/button";
import {
	Card,
	CardContent,
	CardHeader,
	CardTitle,
} from "../../../components/ui/card";
import { EmptyState } from "../../../components/ui/empty-state";
import { Input } from "../../../components/ui/input";
import { PageHeader } from "../../../components/ui/page-header";
import { StatusBadge } from "../../../components/ui/status-badge";
import { useDebouncedValue } from "../../../hooks";
import {
	useRrmBulkStage,
	useRrmImportProspects,
	useRrmProspects,
} from "../../../hooks/queries/useRrmQueries";
import type {
	RrmImportResult,
	RrmLocale,
	RrmProspect,
	RrmProspectFilters,
	RrmStage,
	RrmTier,
} from "../../../lib/api/admin/rrm";
import { getErrorMessage } from "../../../lib/api/base";
import { partnerInviteUrl } from "../../../lib/rrm/invite-link";
import { cn } from "../../../lib/utils";
 
/** Prefilled reason for the untracked "sent the link by hand" send (1.4). */
export const DEFAULT_BULK_CONTACTED_REASON = "Sent the partner link by hand";
 
/**
 * RRM prospect list (F-21).
 *
 * The stage vocabulary, its badge styling and the date formatters are exported
 * from here rather than from a fourth module: the detail screen is the only
 * other consumer, and a shared module would be a new untested file for two
 * importers. If a third screen needs them, promote them then.
 */
 
const PAGE_SIZE = 20;
 
// ─── Stage vocabulary ────────────────────────────────────────────────────────
 
/** Ordered as the funnel runs, terminal states last. Drives every stage select. */
export const STAGE_OPTIONS: readonly RrmStage[] = [
	"sourced",
	"queued",
	"contacted",
	"delivered",
	"read",
	"replied",
	"interested",
	"intent_stated",
	"joined",
	"not_now",
	"unreachable",
	"do_not_contact",
];
 
/** Wire values are snake_case; operators read English. */
export 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",
};
 
type StageVariant = "default" | "info" | "warning" | "success" | "error";
 
/**
 * `StatusBadge.getVariantForStatus` knows nothing about RRM stages — it would
 * silently colour "contacted" as a warning and everything else grey — so the
 * variant is always passed explicitly.
 */
const STAGE_VARIANTS: Record<RrmStage, StageVariant> = {
	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",
};
 
export const LOCALE_LABELS: Record<RrmLocale, string> = {
	en: "English",
	te: "Telugu",
	"te-Latn": "Telugu (Latin)",
};
 
export const TIER_OPTIONS: readonly RrmTier[] = ["A", "B", "C", "D"];
 
export function RrmStageBadge({ stage }: { stage: RrmStage }) {
	return (
		<span data-testid="rrm-stage-badge" data-stage={stage}>
			<StatusBadge
				status={STAGE_LABELS[stage]}
				variant={STAGE_VARIANTS[stage]}
				// `intent_stated` is the program's single success criterion. In a
				// table of hundreds of rows a same-shaped green pill disappears, so
				// this one gets a ring to pull the eye to it.
				className={cn(
					stage === "intent_stated" && "font-semibold ring-1 ring-success",
				)}
			/>
		</span>
	);
}
 
// ─── Date formatting ─────────────────────────────────────────────────────────
 
const MINUTE_MS = 60_000;
const HOUR_MS = 60 * MINUTE_MS;
const DAY_MS = 24 * HOUR_MS;
 
/** Absolute, for tooltips and anywhere the exact instant is evidence. */
export function formatDateTime(iso: string): string {
	return new Date(iso).toLocaleString("en-IN", {
		day: "numeric",
		month: "short",
		year: "numeric",
		hour: "numeric",
		minute: "2-digit",
	});
}
 
/** "How stale is this?" is the question a CRM row actually answers. */
export function formatRelative(iso: string): string {
	const then = new Date(iso).getTime();
	const diff = Date.now() - then;
	if (diff < 0) return formatDateTime(iso);
	if (diff < MINUTE_MS) return "just now";
	if (diff < HOUR_MS) return `${Math.floor(diff / MINUTE_MS)}m ago`;
	if (diff < DAY_MS) return `${Math.floor(diff / HOUR_MS)}h ago`;
	const days = Math.floor(diff / DAY_MS);
	if (days < 30) return `${days}d ago`;
	return new Date(iso).toLocaleDateString("en-IN", {
		day: "numeric",
		month: "short",
		year: "numeric",
	});
}
 
// ─── Table pieces ────────────────────────────────────────────────────────────
 
const COLUMN_COUNT = 7;
const SKELETON_KEYS = ["a", "b", "c", "d", "e", "f", "g", "h"];
 
function SkeletonRows() {
	return (
		<>
			{SKELETON_KEYS.map((key) => (
				<tr key={key} data-testid="rrm-prospects-skeleton-row">
					<td colSpan={COLUMN_COUNT} className="px-4 py-3">
						<div className="h-5 bg-background-muted rounded animate-pulse" />
					</td>
				</tr>
			))}
		</>
	);
}
 
const HEADER_CELL =
	"px-4 py-3 text-left text-xs font-medium text-foreground-muted uppercase tracking-wider";
 
function ProspectRow({
	prospect,
	onOpen,
	selected,
	onToggleSelect,
}: {
	prospect: RrmProspect;
	onOpen: (id: string) => void;
	selected: boolean;
	onToggleSelect: (id: string) => void;
}) {
	const markets = prospect.microMarkets ?? [];
	const marketLabel = markets.length > 0 ? markets.join(", ") : "—";
 
	return (
		<tr
			data-testid="rrm-prospect-row"
			data-prospect-id={prospect.id}
			tabIndex={0}
			className="cursor-pointer hover:bg-background-muted focus-visible:outline-none focus-visible:bg-background-muted transition-colors"
			onClick={() => onOpen(prospect.id)}
			onKeyDown={(e) => {
				// The checkbox cell is focusable too — only the row itself, not
				// something focused inside it, should open the detail page.
				Iif (e.target !== e.currentTarget) return;
				if (e.key === "Enter" || e.key === " ") {
					e.preventDefault();
					onOpen(prospect.id);
				}
			}}
		>
			<td className="px-4 py-3">
				<input
					type="checkbox"
					aria-label={`Select ${prospect.name ?? prospect.phoneNorm}`}
					data-testid="rrm-prospect-select"
					checked={selected}
					onChange={() => onToggleSelect(prospect.id)}
					onClick={(e) => e.stopPropagation()}
					className="h-4 w-4 rounded border-border-default text-primary-600 focus:ring-primary-500/40"
				/>
			</td>
			<td className="px-4 py-3">
				<p className="flex items-center gap-2 text-sm font-medium text-foreground-default">
					{prospect.name ?? "Unnamed"}
					{/* Never offer a by-hand opener to someone who has opted out. */}
					{!prospect.doNotContact && (
						<a
							href={partnerInviteUrl(prospect)}
							target="_blank"
							rel="noopener noreferrer"
							title="Invite on WhatsApp"
							aria-label={`Invite ${prospect.name ?? prospect.phoneNorm} on WhatsApp`}
							data-testid="rrm-prospect-whatsapp-invite"
							onClick={(e) => e.stopPropagation()}
							className="text-success hover:text-success/80"
						>
							<MessageCircle aria-hidden="true" className="size-4" />
						</a>
					)}
				</p>
				<p className="text-xs text-foreground-muted">
					{prospect.firmName ?? prospect.phoneNorm}
				</p>
				{/* The columns hidden on narrow screens fold into this cell instead. */}
				<p className="text-xs text-foreground-subtle md:hidden">
					{prospect.tier ? `Tier ${prospect.tier} · ` : ""}
					{marketLabel}
				</p>
			</td>
			<td className="hidden md:table-cell px-4 py-3 text-sm text-foreground-muted">
				{prospect.tier ?? "—"}
			</td>
			<td className="hidden lg:table-cell px-4 py-3 text-sm text-foreground-muted max-w-xs truncate">
				{marketLabel}
			</td>
			<td className="px-4 py-3">
				<RrmStageBadge stage={prospect.stage} />
			</td>
			<td className="hidden md:table-cell px-4 py-3 text-sm text-foreground-muted">
				{LOCALE_LABELS[prospect.locale]}
			</td>
			<td
				className="hidden sm:table-cell px-4 py-3 text-xs text-foreground-muted whitespace-nowrap"
				data-testid="rrm-prospect-last-contact"
			>
				{prospect.lastContactedAt ? (
					<span title={formatDateTime(prospect.lastContactedAt)}>
						{formatRelative(prospect.lastContactedAt)}
					</span>
				) : (
					"Never"
				)}
			</td>
		</tr>
	);
}
 
const SELECT_CLASS =
	"h-10 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";
 
// ─── Page ────────────────────────────────────────────────────────────────────
 
export function AdminRrmProspectsPage() {
	const navigate = useNavigate();
 
	const [search, setSearch] = useState("");
	const [stage, setStage] = useState("");
	const [tier, setTier] = useState("");
	const [microMarket, setMicroMarket] = useState("");
	const [page, setPage] = useState(1);
 
	// Bulk selection (1.4) — the untracked "sent the link by hand" send.
	const [selected, setSelected] = useState<Set<string>>(new Set());
	const [bulkReason, setBulkReason] = useState(DEFAULT_BULK_CONTACTED_REASON);
	const [bulkResult, setBulkResult] = useState<{
		moved: number;
		skipped: { id: string; reason: string }[];
	} | null>(null);
	const [bulkError, setBulkError] = useState<string | null>(null);
	const bulkStage = useRrmBulkStage();
 
	// CSV import (§5.3). The file input is cleared after every run: without it
	// the browser refuses to re-fire `change` for the same filename, so an
	// operator who fixes two rows and re-picks the file gets nothing.
	const fileInputRef = useRef<HTMLInputElement>(null);
	const [importFile, setImportFile] = useState<File | null>(null);
	const [importResult, setImportResult] = useState<RrmImportResult | null>(
		null,
	);
	const [importError, setImportError] = useState<string | null>(null);
	const importProspects = useRrmImportProspects();
 
	async function handleImport() {
		Iif (!importFile) return;
		setImportError(null);
		setImportResult(null);
		try {
			const response = await importProspects.mutateAsync(importFile);
			setImportResult(response.data ?? null);
		} catch (err) {
			setImportError(getErrorMessage(err));
		} finally {
			setImportFile(null);
			Eif (fileInputRef.current) fileInputRef.current.value = "";
		}
	}
 
	/**
	 * A selection made on one page or one set of filters must never ride along
	 * into a bulk action fired after the list underneath it has changed —
	 * every filter and page change clears it.
	 */
	function resetSelection() {
		setSelected(new Set());
		setBulkResult(null);
		setBulkError(null);
	}
 
	function changePage(updater: (current: number) => number) {
		setPage(updater);
		resetSelection();
	}
 
	const debouncedSearch = useDebouncedValue(search);
 
	const filters: RrmProspectFilters = {
		page,
		limit: PAGE_SIZE,
		q: debouncedSearch || undefined,
		stage: (stage as RrmStage) || undefined,
		tier: (tier as RrmTier) || undefined,
		microMarket: microMarket || undefined,
	};
 
	const { data, isLoading, error } = useRrmProspects(filters);
 
	const items = useMemo(() => data?.data ?? [], [data]);
 
	/**
	 * There is no micro-market vocabulary endpoint, so the options can only come
	 * from rows already fetched. They accumulate instead of being recomputed per
	 * page: filtering to one market narrows the response to that market, which
	 * would otherwise collapse the select to a single option and strand the
	 * operator with no way back to another market.
	 */
	const [seenMarkets, setSeenMarkets] = useState<string[]>([]);
	useEffect(() => {
		setSeenMarkets((prev) => {
			const next = new Set(prev);
			for (const prospect of items) {
				for (const market of prospect.microMarkets ?? []) next.add(market);
			}
			return next.size === prev.length ? prev : [...next].sort();
		});
	}, [items]);
 
	/**
	 * The count is whatever the API says it is. An assumed or client-derived
	 * figure here has already sent planning down the wrong road once — the list
	 * is 455 rows, not the 1,000 that was budgeted for.
	 */
	const total = data?.meta?.total;
	const totalPages = data?.meta?.totalPages;
	const hasPrev = page > 1;
	const hasNext =
		totalPages !== undefined ? page < totalPages : items.length === PAGE_SIZE;
 
	const countLabel =
		total === undefined
			? `${items.length} prospect${items.length === 1 ? "" : "s"} on this page`
			: `${total.toLocaleString("en-IN")} prospect${total === 1 ? "" : "s"}`;
 
	const hasFilters = Boolean(search || stage || tier || microMarket);
 
	function applyFilter(setter: (value: string) => void, value: string) {
		setter(value);
		setPage(1);
		resetSelection();
	}
 
	function clearFilters() {
		setSearch("");
		setStage("");
		setTier("");
		setMicroMarket("");
		setPage(1);
		resetSelection();
	}
 
	function openProspect(id: string) {
		navigate({ to: `/admin/rrm/prospects/${id}` });
	}
 
	function toggleSelectAll() {
		setSelected((prev) => {
			const allSelected =
				items.length > 0 && items.every((p) => prev.has(p.id));
			return allSelected ? new Set() : new Set(items.map((p) => p.id));
		});
	}
 
	function toggleSelectOne(id: string) {
		setSelected((prev) => {
			const next = new Set(prev);
			Iif (next.has(id)) {
				next.delete(id);
			} else {
				next.add(id);
			}
			return next;
		});
	}
 
	async function handleMarkContacted() {
		const reason = bulkReason.trim();
		Iif (!reason || selected.size === 0) return;
		setBulkError(null);
		setBulkResult(null);
		try {
			const response = await bulkStage.mutateAsync({
				ids: [...selected],
				stage: "contacted",
				reason,
			});
			setBulkResult(response.data ?? { moved: 0, skipped: [] });
			setSelected(new Set());
		} catch (err) {
			setBulkError(getErrorMessage(err));
		}
	}
 
	const allOnPageSelected =
		items.length > 0 && items.every((p) => selected.has(p.id));
 
	return (
		<div className="space-y-6" data-testid="rrm-prospects-page">
			<PageHeader
				title="Prospects"
				description="Every Hyderabad channel partner in the recruitment campaign."
				actions={
					<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
						<input
							ref={fileInputRef}
							type="file"
							accept=".csv,text/csv"
							aria-label="Prospect CSV"
							data-testid="rrm-prospects-import-file"
							onChange={(e) => {
								setImportFile(e.target.files?.[0] ?? null);
								setImportError(null);
							}}
							className="text-sm text-foreground-muted file:mr-3 file:rounded-md file:border file:border-border-default file:bg-background-subtle file:px-3 file:py-1.5 file:text-sm file:text-foreground-default"
						/>
						<Button
							type="button"
							variant="outline"
							onClick={() => {
								void handleImport();
							}}
							disabled={!importFile || importProspects.isPending}
							data-testid="rrm-prospects-import-button"
						>
							<Upload className="h-4 w-4" aria-hidden="true" />
							{importProspects.isPending ? "Importing…" : "Import CSV"}
						</Button>
					</div>
				}
			/>
 
			{importError && (
				<p
					className="rounded-lg border border-notification-error-border bg-notification-error-bg p-3 text-sm text-notification-error-text"
					data-testid="rrm-prospects-import-error"
				>
					{importError}
				</p>
			)}
 
			{importResult && (
				<Card data-testid="rrm-prospects-import-result">
					<CardHeader>
						<CardTitle className="text-lg">
							Imported {importResult.rowsOk.toLocaleString("en-IN")} of{" "}
							{importResult.rowsTotal.toLocaleString("en-IN")} rows
						</CardTitle>
						<p className="text-sm text-foreground-muted">
							{importResult.rowsRejected.toLocaleString("en-IN")} rejected.
							Nothing partial is lost — re-uploading the fixed file re-imports
							only the rows that are still missing.
						</p>
					</CardHeader>
					{importResult.rejects.length > 0 && (
						<CardContent>
							<ul className="space-y-1 text-sm">
								{importResult.rejects.map((reject) => (
									<li
										key={`${reject.row}-${reject.reason}`}
										className="text-foreground-muted"
										data-testid={`rrm-prospects-import-reject-${reject.row}`}
									>
										<span className="font-medium text-foreground-default">
											Line {reject.row}
										</span>
										{reject.phone ? ` · ${reject.phone}` : ""} · {reject.reason}
										{reject.detail ? ` — ${reject.detail}` : ""}
									</li>
								))}
							</ul>
						</CardContent>
					)}
				</Card>
			)}
 
			<Card>
				<CardContent className="pt-6">
					<div className="flex flex-col sm:flex-row flex-wrap gap-3">
						<div className="sm:w-64">
							<Input
								type="search"
								aria-label="Search prospects"
								placeholder="Name, firm or phone"
								data-testid="rrm-prospects-search"
								value={search}
								onChange={(e) => applyFilter(setSearch, e.target.value)}
							/>
						</div>
 
						<select
							aria-label="Filter by stage"
							data-testid="rrm-prospects-stage-filter"
							className={SELECT_CLASS}
							value={stage}
							onChange={(e) => applyFilter(setStage, e.target.value)}
						>
							<option value="">All stages</option>
							{STAGE_OPTIONS.map((value) => (
								<option key={value} value={value}>
									{STAGE_LABELS[value]}
								</option>
							))}
						</select>
 
						<select
							aria-label="Filter by tier"
							data-testid="rrm-prospects-tier-filter"
							className={SELECT_CLASS}
							value={tier}
							onChange={(e) => applyFilter(setTier, e.target.value)}
						>
							<option value="">All tiers</option>
							{TIER_OPTIONS.map((value) => (
								<option key={value} value={value}>
									Tier {value}
								</option>
							))}
						</select>
 
						<select
							aria-label="Filter by micro-market"
							data-testid="rrm-prospects-market-filter"
							className={SELECT_CLASS}
							value={microMarket}
							onChange={(e) => applyFilter(setMicroMarket, e.target.value)}
						>
							<option value="">All micro-markets</option>
							{seenMarkets.map((value) => (
								<option key={value} value={value}>
									{value}
								</option>
							))}
						</select>
 
						{hasFilters && (
							<Button
								variant="outline"
								data-testid="rrm-prospects-clear-filters"
								onClick={clearFilters}
							>
								Clear
							</Button>
						)}
					</div>
				</CardContent>
			</Card>
 
			<Card>
				<CardHeader>
					<CardTitle className="text-lg" data-testid="rrm-prospects-total">
						{isLoading ? "Loading prospects…" : countLabel}
					</CardTitle>
				</CardHeader>
				<CardContent className="p-0">
					{error ? (
						<div
							data-testid="rrm-prospects-error"
							className="p-6 text-sm text-error"
						>
							Could not load prospects. Refresh the page to try again.
						</div>
					) : (
						<div className="overflow-x-auto">
							<table
								className="w-full text-sm"
								data-testid="rrm-prospects-table"
							>
								<thead className="bg-background-subtle border-b border-border-default">
									<tr>
										<th className={cn(HEADER_CELL, "w-10")}>
											<input
												type="checkbox"
												aria-label="Select all prospects on this page"
												data-testid="rrm-prospects-select-all"
												checked={allOnPageSelected}
												onChange={toggleSelectAll}
												className="h-4 w-4 rounded border-border-default text-primary-600 focus:ring-primary-500/40"
											/>
										</th>
										<th className={HEADER_CELL}>Prospect</th>
										<th className={cn(HEADER_CELL, "hidden md:table-cell")}>
											Tier
										</th>
										<th className={cn(HEADER_CELL, "hidden lg:table-cell")}>
											Micro-market
										</th>
										<th className={HEADER_CELL}>Stage</th>
										<th className={cn(HEADER_CELL, "hidden md:table-cell")}>
											Locale
										</th>
										<th className={cn(HEADER_CELL, "hidden sm:table-cell")}>
											Last contact
										</th>
									</tr>
								</thead>
								<tbody className="divide-y divide-border-default">
									{isLoading ? (
										<SkeletonRows />
									) : items.length === 0 ? (
										<tr>
											<td colSpan={COLUMN_COUNT} className="px-4 py-12">
												<EmptyState
													icon={Users}
													title="No prospects found"
													description={
														hasFilters
															? "No prospect matches these filters. Clear them to see the full list."
															: "Nothing has been imported into the campaign yet."
													}
												/>
											</td>
										</tr>
									) : (
										items.map((prospect) => (
											<ProspectRow
												key={prospect.id}
												prospect={prospect}
												onOpen={openProspect}
												selected={selected.has(prospect.id)}
												onToggleSelect={toggleSelectOne}
											/>
										))
									)}
								</tbody>
							</table>
						</div>
					)}
 
					{!isLoading && !error && (hasPrev || hasNext) && (
						<div
							className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 px-4 py-3 border-t border-border-default"
							data-testid="rrm-prospects-pagination"
						>
							<p className="text-sm text-foreground-muted">
								{totalPages === undefined
									? `Page ${page}`
									: `Page ${page} of ${totalPages}`}
								{total !== undefined
									? ` · ${total.toLocaleString("en-IN")} total`
									: ""}
							</p>
							<div className="flex gap-2">
								<Button
									variant="outline"
									size="sm"
									data-testid="rrm-prospects-prev"
									onClick={() => changePage((p) => Math.max(1, p - 1))}
									disabled={!hasPrev}
								>
									Previous
								</Button>
								<Button
									variant="outline"
									size="sm"
									data-testid="rrm-prospects-next"
									onClick={() => changePage((p) => p + 1)}
									disabled={!hasNext}
								>
									Next
								</Button>
							</div>
						</div>
					)}
				</CardContent>
			</Card>
 
			{(selected.size > 0 || bulkResult || bulkError) && (
				<div
					data-testid="rrm-bulk-bar"
					className="sticky bottom-4 z-10 flex flex-col gap-3 rounded-lg border border-border-default bg-background-elevated p-4 shadow-lg"
				>
					<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
						{selected.size > 0 ? (
							<>
								<p className="text-sm font-medium text-foreground-default">
									{selected.size} selected
								</p>
								<div className="flex flex-1 flex-col gap-2 sm:flex-row sm:items-center">
									<Input
										aria-label="Reason for marking contacted"
										data-testid="rrm-bulk-reason"
										value={bulkReason}
										onChange={(e) => setBulkReason(e.target.value)}
										className="sm:max-w-sm"
									/>
									<Button
										data-testid="rrm-bulk-mark-contacted"
										disabled={bulkReason.trim() === "" || bulkStage.isPending}
										isLoading={bulkStage.isPending}
										onClick={handleMarkContacted}
									>
										Mark contacted
									</Button>
								</div>
							</>
						) : (
							bulkResult && (
								<p
									className="text-sm text-foreground-default"
									data-testid="rrm-bulk-result"
								>
									Moved {bulkResult.moved} to Contacted
									{bulkResult.skipped.length > 0
										? ` — skipped ${bulkResult.skipped.length} (the stage rule refused them).`
										: "."}
								</p>
							)
						)}
					</div>
					{/* Rendered independently of the branch above — a failed attempt
					    leaves the selection in place so the operator can retry, and the
					    error must stay visible alongside those controls, not replace them. */}
					{bulkError && (
						<p className="text-sm text-error" data-testid="rrm-bulk-result">
							{bulkError}
						</p>
					)}
				</div>
			)}
		</div>
	);
}
 
export default AdminRrmProspectsPage;