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

100% Statements 114/114
96.32% Branches 131/136
100% Functions 46/46
100% Lines 107/107

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 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009                                                                                                                    1x   24x             1x     1x           2904x       3146x       5929x 5928x           121x 121x                                                                                 121x                                                                                                   242x                                     2904x 2904x 2904x                                                                               360x 121x 360x     121x   360x     121x                                                               2904x 2904x                                                         1x                   353x 353x     353x                                                                                                                                     121x 353x   121x                                                                                                     3x             353x                         236x                                                                                                 236x 121x                                       236x                                 93x 4x 3x 1x   2x               124x 124x 124x 124x     124x   124x 124x 124x   124x 124x 124x 124x 124x 124x 124x     13x 13x 13x 13x 13x 9x 9x         4x   13x 13x                     7x 7x 5x 7x 7x 7x         2x 2x 1x 2x 2x   2x         4x 4x 4x 3x 3x 4x       124x 1x                         123x 2x                                             121x 121x                           121x   124x 124x   124x   124x                                                                                                                           2x                                                                                                       11x                                                 6x                                                               8x                                                                                                             8x                         6x                                                                 1x   7x                 1x   2x               1x   2x            
import { useQueryClient } from "@tanstack/react-query";
import {
	AlertTriangle,
	CheckCircle2,
	Gauge,
	PauseCircle,
	PlayCircle,
	RefreshCw,
	ShieldAlert,
	XCircle,
} from "lucide-react";
import { useId, 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 { PageHeader } from "../../../components/ui/page-header";
import { Skeleton } from "../../../components/ui/skeleton";
import { StatusBadge } from "../../../components/ui/status-badge";
import {
	useRrmRamp,
	useRrmTemplates,
	useSyncRrmTemplates,
} from "../../../hooks/queries/useRrmQueries";
import {
	adminRrmApi,
	type RrmGateCondition,
	type RrmRampState,
	type RrmTemplateSummary,
} from "../../../lib/api/admin/rrm";
import { getErrorMessage } from "../../../lib/api/base";
import { formatRelativeDate } from "../../../lib/format-date";
import { queryKeys } from "../../../lib/query-keys";
 
/**
 * Send pacing and the release gate — F-21, `/admin/rrm/ramp`.
 *
 * The five-tranche ramp the original spec described is gone: the campaign
 * sends at a flat, configurable rate inside a business window, so there is no
 * escalating schedule left to draw. What survived is the gate — conditions
 * evaluated server-side that decide whether anything is released at all — and
 * that is the half worth a screen.
 */
 
/**
 * Mirrors `DEFAULT_QUIET_HOURS` in `apps/api/src/lib/rrm/time.ts`.
 *
 * PRESENTATIONAL ONLY: it hatches the hours the scheduler will not send in.
 * `RrmRampState` does not carry the window, so drift between the two mis-draws
 * the hatching — it can never let a send through, because admission control
 * lives entirely on the server.
 */
const SEND_WINDOW = { startHour: 10, endHour: 19 };
 
const HOURS = Array.from({ length: 24 }, (_, hour) => hour);
 
/**
 * Mirrors `parseOverride` in `apps/api/src/routes/admin/rrm/ramp.routes.ts`.
 * The server enforces it too — this is only so an operator is told before the
 * round trip rather than after it.
 */
const OVERRIDE_REASON_MIN = 20;
 
/** 45° hatch drawn in `currentColor` so it inherits a token, never a hex. */
const HATCH_STYLE = {
	backgroundImage:
		"repeating-linear-gradient(45deg, currentColor 0, currentColor 1px, transparent 1px, transparent 5px)",
};
 
function isQuietHour(hour: number): boolean {
	return hour < SEND_WINDOW.startHour || hour >= SEND_WINDOW.endHour;
}
 
function formatHour(hour: number): string {
	return `${String(hour).padStart(2, "0")}:00`;
}
 
function percentOf(value: number, total: number): number {
	if (total <= 0) return 0;
	return Math.min(100, (value / total) * 100);
}
 
// ─── Rolling 24h ─────────────────────────────────────────────────────────────
 
function RollingWindowCard({ used, tier }: RrmRampState["rollingWindow"]) {
	const pct = percentOf(used, tier);
	return (
		<Card data-testid="rrm-ramp-rolling-window">
			<CardHeader>
				<CardTitle className="font-heading text-lg">Rolling 24 hours</CardTitle>
			</CardHeader>
			<CardContent className="space-y-3">
				<p className="text-3xl font-semibold text-foreground-default">
					{used.toLocaleString()}
					<span className="ml-2 text-base font-normal text-foreground-muted">
						of {tier.toLocaleString()} unique recipients
					</span>
				</p>
				<div className="h-2 w-full rounded-full bg-background-muted">
					<div
						role="progressbar"
						aria-label="Rolling 24-hour unique recipients against WABA tier"
						aria-valuemin={0}
						aria-valuemax={tier}
						aria-valuenow={used}
						className="h-2 rounded-full bg-primary-500"
						style={{ width: `${pct}%` }}
					/>
				</div>
				<p className="text-sm text-foreground-muted">
					{pct.toFixed(1)}% of the tier. Read this as reassurance, not as a
					budget: at this volume the tier is nowhere near binding. Supply of
					sourced numbers and block risk are the constraints that actually bite,
					and those are what the gate below measures.
				</p>
			</CardContent>
		</Card>
	);
}
 
// ─── Pace ────────────────────────────────────────────────────────────────────
 
function PaceCard({
	hourlyRate,
	dailyCap,
	halted,
}: Pick<RrmRampState, "hourlyRate" | "dailyCap" | "halted">) {
	return (
		<Card data-testid="rrm-ramp-pace">
			<CardHeader>
				<CardTitle className="font-heading text-lg">Configured pace</CardTitle>
			</CardHeader>
			<CardContent className="space-y-3">
				<p className="text-3xl font-semibold text-foreground-default">
					{hourlyRate.toLocaleString()}
					<span className="ml-2 text-base font-normal text-foreground-muted">
						sends per hour
					</span>
				</p>
				<dl className="space-y-1 text-sm">
					<div className="flex justify-between gap-4">
						<dt className="text-foreground-muted">Daily cap</dt>
						<dd className="text-foreground-default">
							{dailyCap.toLocaleString()}
						</dd>
					</div>
					<div className="flex justify-between gap-4">
						<dt className="text-foreground-muted">Send window (IST)</dt>
						<dd className="text-foreground-default">
							{formatHour(SEND_WINDOW.startHour)}–
							{formatHour(SEND_WINDOW.endHour)}
						</dd>
					</div>
					<div className="flex justify-between gap-4">
						<dt className="text-foreground-muted">Sending</dt>
						<dd>
							<StatusBadge
								status={halted ? "Halted" : "Running"}
								variant={halted ? "error" : "success"}
							/>
						</dd>
					</div>
				</dl>
			</CardContent>
		</Card>
	);
}
 
// ─── Hourly histogram ────────────────────────────────────────────────────────
 
function LegendSwatch({
	className,
	label,
}: {
	className: string;
	label: string;
}) {
	return (
		<span className="inline-flex items-center gap-2 text-sm text-foreground-muted">
			<span className={`h-3 w-3 rounded-sm ${className}`} />
			{label}
		</span>
	);
}
 
function HourColumn({
	hour,
	newOpeners,
	followUps,
	peak,
}: {
	hour: number;
	newOpeners: number;
	followUps: number;
	peak: number;
}) {
	const quiet = isQuietHour(hour);
	const total = newOpeners + followUps;
	return (
		<div
			className="flex w-8 shrink-0 flex-col items-center gap-1"
			data-testid={`rrm-ramp-hour-${hour}`}
			data-quiet={quiet ? "true" : "false"}
		>
			<div
				className="relative flex h-32 w-full flex-col justify-end overflow-hidden rounded-sm bg-background-subtle"
				title={`${formatHour(hour)} — ${newOpeners} new, ${followUps} follow-up${
					quiet ? ", quiet hour" : ""
				}`}
			>
				{quiet && (
					<span
						aria-hidden="true"
						className="absolute inset-0 text-foreground-subtle"
						style={HATCH_STYLE}
					/>
				)}
				<span
					className="relative w-full bg-secondary-500"
					style={{ height: `${percentOf(followUps, peak)}%` }}
				/>
				<span
					className="relative w-full bg-primary-500"
					style={{ height: `${percentOf(newOpeners, peak)}%` }}
				/>
			</div>
			<span className="text-xs tabular-nums text-foreground-subtle">
				{total > 0 ? total : "·"}
			</span>
			<span className="text-xs text-foreground-subtle">{hour}</span>
		</div>
	);
}
 
function HistogramCard({
	todayByHour,
	dailyCap,
}: Pick<RrmRampState, "todayByHour" | "dailyCap">) {
	const byHour = new Map(todayByHour.map((row) => [row.hour, row]));
	const sentToday = todayByHour.reduce(
		(sum, row) => sum + row.newOpeners + row.followUps,
		0,
	);
	const peak = Math.max(
		1,
		...todayByHour.map((row) => row.newOpeners + row.followUps),
	);
 
	return (
		<Card data-testid="rrm-ramp-histogram">
			<CardHeader className="gap-2">
				<CardTitle className="font-heading text-lg">Today, by hour</CardTitle>
				<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
					<p className="text-sm text-foreground-muted">
						<span
							className="text-base font-semibold text-foreground-default"
							data-testid="rrm-ramp-sent-today"
						>
							{sentToday.toLocaleString()}
						</span>{" "}
						of {dailyCap.toLocaleString()} daily cap
					</p>
					<div className="flex flex-wrap items-center gap-4">
						<LegendSwatch className="bg-primary-500" label="New openers" />
						<LegendSwatch className="bg-secondary-500" label="Follow-ups" />
						<span className="inline-flex items-center gap-2 text-sm text-foreground-muted">
							<span
								aria-hidden="true"
								className="h-3 w-3 rounded-sm bg-background-subtle text-foreground-subtle"
								style={HATCH_STYLE}
							/>
							Quiet hours
						</span>
					</div>
				</div>
			</CardHeader>
			<CardContent>
				<div className="overflow-x-auto pb-1">
					<div className="flex min-w-max items-end gap-1">
						{HOURS.map((hour) => {
							const row = byHour.get(hour);
							return (
								<HourColumn
									key={hour}
									hour={hour}
									newOpeners={row?.newOpeners ?? 0}
									followUps={row?.followUps ?? 0}
									peak={peak}
								/>
							);
						})}
					</div>
				</div>
				<p className="mt-3 text-sm text-foreground-muted">
					Hours are IST. Hatched columns are outside the send window, so a bar
					there means something bypassed the scheduler and is worth chasing.
				</p>
			</CardContent>
		</Card>
	);
}
 
// ─── Template approval ───────────────────────────────────────────────────────
 
/**
 * Meta's verdicts on the badge palette. Only APPROVED is green: PENDING is not
 * "nearly there", it is "the ladder still sends nothing". An unrecognised
 * status falls to warning rather than quietly reading as fine.
 */
const TEMPLATE_STATUS_VARIANT: Record<string, "success" | "warning" | "error"> =
	{
		APPROVED: "success",
		PENDING: "warning",
		NOT_SUBMITTED: "warning",
		REJECTED: "error",
		PAUSED: "error",
		DISABLED: "error",
	};
 
function TemplateRow({ template }: { template: RrmTemplateSummary }) {
	const approved = template.status === "APPROVED";
	const synced = template.updatedAt
		? formatRelativeDate(template.updatedAt, { granularity: "time" })
		: null;
	return (
		<li
			className="flex flex-col gap-2 py-3 sm:flex-row sm:items-start sm:justify-between"
			data-testid={`rrm-template-${template.name}`}
		>
			<div className="flex items-start gap-3">
				{approved ? (
					<CheckCircle2
						className="mt-0.5 h-5 w-5 shrink-0 text-success"
						aria-hidden="true"
					/>
				) : (
					<XCircle
						className="mt-0.5 h-5 w-5 shrink-0 text-error"
						aria-hidden="true"
					/>
				)}
				<div>
					<p className="text-sm font-medium text-foreground-default">
						{template.name}
						<span className="sr-only">
							{approved ? " — approved" : " — not approved"}
						</span>
					</p>
					<p className="text-sm text-foreground-muted">
						{template.language} · {template.category} ·{" "}
						{synced ? `synced ${synced}` : "never synced"}
					</p>
					{template.rejectedReason && (
						<p className="text-sm text-error">
							Meta&apos;s reason: {template.rejectedReason}
						</p>
					)}
				</div>
			</div>
			<StatusBadge
				status={template.status}
				variant={TEMPLATE_STATUS_VARIANT[template.status] ?? "warning"}
			/>
		</li>
	);
}
 
/**
 * The approval strip, above the gate — because it is the gate the gate cannot
 * see. The scheduler re-checks template approval every tick and enrols nobody
 * while any of these is unapproved, so an operator staring at a passing gate
 * and zero enrolments needs this in the same eyeline.
 *
 * Its own load and error states, deliberately: the ramp underneath it is a
 * separate query and must not go blank because Meta's statuses are slow.
 */
function TemplateStripCard({
	templates,
	isLoading,
	error,
	onSync,
	syncing,
	busy,
}: {
	templates: RrmTemplateSummary[] | undefined;
	isLoading: boolean;
	error: unknown;
	onSync: () => void;
	syncing: boolean;
	busy: boolean;
}) {
	const unapproved = (templates ?? []).filter(
		(template) => template.status !== "APPROVED",
	);
	return (
		<Card data-testid="rrm-ramp-templates">
			<CardHeader className="gap-2">
				<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
					<div>
						<CardTitle className="font-heading text-lg">
							Template approval
						</CardTitle>
						<p className="text-sm text-foreground-muted">
							Meta must approve every template before the ladder sends anything.
							Approving is done in WhatsApp Manager — Sync only reads the
							verdict back.
						</p>
					</div>
					<Button
						type="button"
						variant="outline"
						size="sm"
						onClick={onSync}
						disabled={busy}
						data-testid="rrm-templates-sync-button"
					>
						<RefreshCw
							className={`h-4 w-4 ${syncing ? "animate-spin" : ""}`}
							aria-hidden="true"
						/>
						Sync from Meta
					</Button>
				</div>
			</CardHeader>
			<CardContent>
				{isLoading ? (
					<div data-testid="rrm-templates-loading">
						<Skeleton className="h-24 w-full" />
					</div>
				) : error || !templates || templates.length === 0 ? (
					<p className="text-sm text-error" data-testid="rrm-templates-error">
						{error
							? getErrorMessage(error)
							: "The templates endpoint returned nothing."}{" "}
						Approval status is unknown — assume the ladder is sending nothing
						until this loads.
					</p>
				) : (
					<div className="space-y-2">
						{unapproved.length > 0 && (
							<p
								className="text-sm text-error"
								data-testid="rrm-templates-blocked"
							>
								{unapproved.length} of {templates.length} not approved:{" "}
								{unapproved.map((template) => template.name).join(", ")}. The
								ladder enrols nobody and sends nothing until every one of them
								is approved.
							</p>
						)}
						<ul className="divide-y divide-border-default">
							{templates.map((template) => (
								<TemplateRow key={template.name} template={template} />
							))}
						</ul>
					</div>
				)}
			</CardContent>
		</Card>
	);
}
 
// ─── Gate ────────────────────────────────────────────────────────────────────
 
function GateConditionRow({ condition }: { condition: RrmGateCondition }) {
	return (
		<li
			className="flex flex-col gap-2 py-3 sm:flex-row sm:items-center sm:justify-between"
			data-testid={`rrm-gate-condition-${condition.key}`}
		>
			<div className="flex items-start gap-3">
				{condition.pass ? (
					<CheckCircle2
						className="mt-0.5 h-5 w-5 shrink-0 text-success"
						aria-hidden="true"
					/>
				) : (
					<XCircle
						className="mt-0.5 h-5 w-5 shrink-0 text-error"
						aria-hidden="true"
					/>
				)}
				<div>
					<p className="text-sm font-medium text-foreground-default">
						{condition.label}
						<span className="sr-only">
							{condition.pass ? " — passing" : " — failing"}
						</span>
					</p>
					<p className="text-sm text-foreground-muted">
						Now{" "}
						<span
							className={
								condition.pass
									? "font-semibold text-success"
									: "font-semibold text-error"
							}
						>
							{condition.value}
						</span>{" "}
						· needs {condition.threshold}
					</p>
				</div>
			</div>
			{!condition.pass && condition.fixHref && (
				<Button variant="outline" size="sm" asChild>
					<a href={condition.fixHref}>Fix this</a>
				</Button>
			)}
		</li>
	);
}
 
function GateCard({ conditions }: Pick<RrmRampState, "conditions">) {
	const failing = conditions.filter((condition) => !condition.pass);
	return (
		<Card data-testid="rrm-ramp-gate">
			<CardHeader>
				<CardTitle className="font-heading text-lg">Release gate</CardTitle>
				<p className="text-sm text-foreground-muted">
					{conditions.length === 0
						? "The server returned no conditions."
						: `${conditions.length - failing.length} of ${conditions.length} conditions passing.`}
				</p>
			</CardHeader>
			<CardContent>
				{conditions.length === 0 ? (
					<EmptyState
						icon={ShieldAlert}
						title="No gate conditions returned"
						description="The gate is evaluated server-side. An empty list means the ramp endpoint could not evaluate it — treat release as closed and escalate."
					/>
				) : (
					<ul className="divide-y divide-border-default">
						{conditions.map((condition) => (
							<GateConditionRow key={condition.key} condition={condition} />
						))}
					</ul>
				)}
			</CardContent>
		</Card>
	);
}
 
// ─── Blocking copy ───────────────────────────────────────────────────────────
 
/**
 * A bare "gate not met" tells an operator nothing they can act on. Prefer the
 * server's reason, fall back to naming the failing conditions, and only if
 * both are missing admit that we do not know — which is itself actionable.
 */
function blockingText(ramp: RrmRampState): string {
	if (ramp.blockingReason) return ramp.blockingReason;
	const failing = ramp.conditions.filter((condition) => !condition.pass);
	if (failing.length > 0) {
		return `Blocked by: ${failing.map((condition) => condition.label).join(", ")}.`;
	}
	return "Release is closed and the server named no failing condition. Refresh, and escalate if it stays closed.";
}
 
// ─── Page ────────────────────────────────────────────────────────────────────
 
type DialogKind = "release" | "halt" | "resume";
 
export function AdminRrmRampPage() {
	const queryClient = useQueryClient();
	const { data, isLoading, error } = useRrmRamp();
	const templatesQuery = useRrmTemplates();
	const syncTemplates = useSyncRrmTemplates();
	// `request()` keeps the `{ success, data }` envelope, so the state is one
	// level down — same shape every other admin page unwraps.
	const ramp = data?.data;
 
	const acknowledgeId = useId();
	const reasonId = useId();
	const overrideId = useId();
 
	const [acknowledged, setAcknowledged] = useState(false);
	const [reasonDraft, setReasonDraft] = useState("");
	const [overrideDraft, setOverrideDraft] = useState("");
	const [dialog, setDialog] = useState<DialogKind | null>(null);
	const [busy, setBusy] = useState(false);
	const [actionError, setActionError] = useState<string | null>(null);
	const [notice, setNotice] = useState<string | null>(null);
 
	async function run(action: () => Promise<string>) {
		setBusy(true);
		setActionError(null);
		setNotice(null);
		try {
			const message = await action();
			setNotice(message);
			queryClient.invalidateQueries({ queryKey: queryKeys.admin.rrm.all });
		} catch (err) {
			// The contract says a refusal is a normal outcome carrying the failing
			// condition. Swallowing it into the console would leave the operator
			// staring at a button that did nothing.
			setActionError(getErrorMessage(err));
		} finally {
			setBusy(false);
			setDialog(null);
		}
	}
 
	/**
	 * `override` is passed ONLY when the screen is actually offering one and the
	 * reason clears the minimum. The key's presence is what makes the server
	 * stamp an override into the audit row, so a reason left in the box after a
	 * 30s poll re-opened the gate must not ride along with an ordinary release.
	 */
	function handleRelease(count: number, override?: { reason: string }) {
		return run(async () => {
			const response = await adminRrmApi.openRamp(count, true, override);
			const released = response.data?.released ?? 0;
			setAcknowledged(false);
			setOverrideDraft("");
			return `Released ${released.toLocaleString()} prospect${released === 1 ? "" : "s"} into eligibility.`;
		});
	}
 
	function handleSyncTemplates() {
		return run(async () => {
			const response = await syncTemplates.mutateAsync();
			const rows = response.data ?? [];
			const approved = rows.filter(
				(template) => template.status === "APPROVED",
			).length;
			return `Synced ${rows.length} template${rows.length === 1 ? "" : "s"} from Meta — ${approved} approved.`;
		});
	}
 
	function handleHalt(on: boolean) {
		const reason = reasonDraft.trim();
		return run(async () => {
			const response = await adminRrmApi.setHalt(on, reason);
			setReasonDraft("");
			const halted = response.data?.halted ?? on;
			return halted ? "All sending is halted." : "Sending resumed.";
		});
	}
 
	if (isLoading) {
		return (
			<div className="space-y-6" data-testid="rrm-ramp-loading">
				<Skeleton className="h-9 w-64" />
				<div className="grid gap-6 md:grid-cols-2">
					<Skeleton className="h-44 w-full" />
					<Skeleton className="h-44 w-full" />
				</div>
				<Skeleton className="h-64 w-full" />
				<Skeleton className="h-52 w-full" />
			</div>
		);
	}
 
	if (error || !ramp) {
		return (
			<div className="space-y-6">
				<PageHeader
					title="Send pacing"
					description="Rolling window, hourly pacing and the release gate."
				/>
				<Card>
					<CardContent className="pt-6">
						<EmptyState
							icon={AlertTriangle}
							title="Could not load the ramp"
							description={
								error
									? getErrorMessage(error)
									: "The ramp endpoint returned nothing. Sending state is unknown — do not release until this loads."
							}
						/>
					</CardContent>
				</Card>
			</div>
		);
	}
 
	const reasonRequired = reasonDraft.trim().length === 0;
	const releaseBlocked = !ramp.canRelease;
 
	/**
	 * The override is offered against something an operator can point at — a
	 * failing condition, or the halt. `canRelease` alone is not that: the server
	 * can close the gate while naming nothing, and a box to force past "we do
	 * not know why" is not a decision anyone should be asked to sign.
	 *
	 * The reserve-after-release condition is the one this exists for. It is
	 * (sourced non-DNC minus this release) over all non-DNC, and on a list of a
	 * few hundred any release fails it — which is exactly when the campaign
	 * still has to start.
	 */
	const overrideOffered =
		releaseBlocked &&
		(ramp.halted || ramp.conditions.some((condition) => !condition.pass));
	const overrideReason = overrideDraft.trim();
	const overrideValid = overrideReason.length >= OVERRIDE_REASON_MIN;
	const override =
		overrideOffered && overrideValid ? { reason: overrideReason } : undefined;
 
	return (
		<div className="space-y-6" data-testid="rrm-ramp-page">
			<PageHeader
				title="Send pacing"
				description="A flat, configurable rate inside the business window — plus the gate that decides whether anything goes out at all."
				icon={<Gauge className="h-6 w-6 text-primary-500" aria-hidden="true" />}
			/>
 
			{ramp.halted && (
				<div
					className="flex items-start gap-3 rounded-lg border border-error bg-error-light p-4"
					data-testid="rrm-ramp-halt-banner"
				>
					<PauseCircle
						className="mt-0.5 h-5 w-5 shrink-0 text-error"
						aria-hidden="true"
					/>
					<div>
						<p className="font-semibold text-error">All sending is halted.</p>
						<p className="text-sm text-foreground-default">
							{ramp.haltReason ?? "No reason was recorded with the halt."}
						</p>
					</div>
				</div>
			)}
 
			{notice && (
				<p
					className="rounded-lg border border-notification-success-border bg-notification-success-bg p-3 text-sm text-notification-success-text"
					data-testid="rrm-ramp-notice"
				>
					{notice}
				</p>
			)}
			{actionError && (
				<p
					className="rounded-lg border border-notification-error-border bg-notification-error-bg p-3 text-sm text-notification-error-text"
					data-testid="rrm-ramp-error"
				>
					{actionError}
				</p>
			)}
 
			<div className="grid gap-6 md:grid-cols-2">
				<RollingWindowCard
					used={ramp.rollingWindow.used}
					tier={ramp.rollingWindow.tier}
				/>
				<PaceCard
					hourlyRate={ramp.hourlyRate}
					dailyCap={ramp.dailyCap}
					halted={ramp.halted}
				/>
			</div>
 
			<HistogramCard todayByHour={ramp.todayByHour} dailyCap={ramp.dailyCap} />
 
			<TemplateStripCard
				templates={templatesQuery.data?.data}
				isLoading={templatesQuery.isLoading}
				error={templatesQuery.error}
				onSync={() => {
					void handleSyncTemplates();
				}}
				syncing={syncTemplates.isPending}
				busy={busy}
			/>
 
			<GateCard conditions={ramp.conditions} />
 
			<div className="grid gap-6 md:grid-cols-2">
				{/* Release */}
				<Card data-testid="rrm-ramp-release">
					<CardHeader>
						<CardTitle className="font-heading text-lg">
							Release next batch
						</CardTitle>
						<p className="text-sm text-foreground-muted">
							Releasing adds prospects to the eligible pool. It does not send:
							the hourly rate and daily cap still throttle, and a halt still
							stops delivery.
						</p>
					</CardHeader>
					<CardContent className="space-y-4">
						<dl className="space-y-1 text-sm">
							<div className="flex justify-between gap-4">
								<dt className="text-foreground-muted">Next release</dt>
								<dd className="font-medium text-foreground-default">
									{ramp.nextReleaseCount.toLocaleString()} prospects
								</dd>
							</div>
							<div className="flex justify-between gap-4">
								<dt className="text-foreground-muted">Sendable remaining</dt>
								<dd className="font-medium text-foreground-default">
									{ramp.sendableRemaining.toLocaleString()}
								</dd>
							</div>
							<div className="flex justify-between gap-4">
								<dt className="text-foreground-muted">Reserve after release</dt>
								<dd className="font-medium text-foreground-default">
									{ramp.reservePercentAfterRelease}%
								</dd>
							</div>
						</dl>
 
						<label
							className="flex items-start gap-3 text-sm text-foreground-default"
							htmlFor={acknowledgeId}
						>
							<input
								id={acknowledgeId}
								type="checkbox"
								className="mt-1 h-4 w-4 rounded border-border-default text-primary-500 focus:ring-2 focus:ring-primary-500"
								checked={acknowledged}
								onChange={(e) => setAcknowledged(e.target.checked)}
							/>
							I have read today&apos;s metrics — block rate, opt-outs and the
							reply backlog — and I am releasing on that basis.
						</label>
 
						{overrideOffered && (
							<div className="space-y-1" data-testid="rrm-ramp-override">
								<label
									className="text-sm font-medium text-foreground-default"
									htmlFor={overrideId}
								>
									Override reason
								</label>
								<p className="text-sm text-foreground-muted">
									These gates are our own policy, and you can release past them.
									Say why, in at least {OVERRIDE_REASON_MIN} characters. It is
									stored on the release against your name, together with every
									condition you went past, and it is the only record that this
									release happened against a failing gate.
								</p>
								<textarea
									id={overrideId}
									rows={3}
									value={overrideDraft}
									onChange={(e) => setOverrideDraft(e.target.value)}
									placeholder="e.g. List is only 300 names; starting the campaign is worth the thin reserve"
									className="w-full rounded-md border border-border-default bg-background-base px-3 py-2 text-sm text-foreground-default placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-primary-500"
								/>
								{!overrideValid && overrideReason.length > 0 && (
									<p
										className="text-sm text-error"
										data-testid="rrm-ramp-override-too-short"
									>
										{OVERRIDE_REASON_MIN - overrideReason.length} more character
										{OVERRIDE_REASON_MIN - overrideReason.length === 1
											? ""
											: "s"}{" "}
										needed.
									</p>
								)}
								{ramp.halted && (
									<p
										className="text-sm text-foreground-muted"
										data-testid="rrm-ramp-override-halt-note"
									>
										Sending is halted. Releasing past a halt queues these
										prospects up and delivers nothing — turn the halt off if
										what you want is sends.
									</p>
								)}
							</div>
						)}
 
						<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
							<Button
								type="button"
								onClick={() => setDialog("release")}
								disabled={
									(releaseBlocked && !override) || !acknowledged || busy
								}
								data-testid="rrm-ramp-release-button"
							>
								{override ? "Override and release" : "Release next"}{" "}
								{ramp.nextReleaseCount.toLocaleString()}
							</Button>
							{releaseBlocked ? (
								<p
									className="text-sm text-error"
									data-testid="rrm-ramp-blocking-reason"
								>
									{blockingText(ramp)}
								</p>
							) : (
								!acknowledged && (
									<p
										className="text-sm text-foreground-muted"
										data-testid="rrm-ramp-ack-hint"
									>
										The gate is open. Tick the acknowledgement to enable
										release.
									</p>
								)
							)}
						</div>
					</CardContent>
				</Card>
 
				{/* Halt */}
				<Card data-testid="rrm-ramp-halt">
					<CardHeader>
						<CardTitle className="font-heading text-lg">
							{ramp.halted ? "Resume sending" : "Halt all sending"}
						</CardTitle>
						<p className="text-sm text-foreground-muted">
							The halt is global and immediate. A reason is required in both
							directions — it is the audit trail for why the campaign stopped or
							restarted.
						</p>
					</CardHeader>
					<CardContent className="space-y-4">
						<div className="space-y-1">
							<label
								className="text-sm font-medium text-foreground-default"
								htmlFor={reasonId}
							>
								Reason
							</label>
							<textarea
								id={reasonId}
								rows={3}
								value={reasonDraft}
								onChange={(e) => setReasonDraft(e.target.value)}
								placeholder={
									ramp.halted
										? "e.g. Block rate back under 1% for 24h"
										: "e.g. Two blocks in an hour — pausing to inspect"
								}
								className="w-full rounded-md border border-border-default bg-background-base px-3 py-2 text-sm text-foreground-default placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-primary-500"
							/>
						</div>
						<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
							<Button
								type="button"
								variant={ramp.halted ? "default" : "destructive"}
								onClick={() => setDialog(ramp.halted ? "resume" : "halt")}
								disabled={reasonRequired || busy}
								data-testid="rrm-ramp-halt-button"
							>
								{ramp.halted ? (
									<PlayCircle className="h-4 w-4" aria-hidden="true" />
								) : (
									<PauseCircle className="h-4 w-4" aria-hidden="true" />
								)}
								{ramp.halted ? "Resume sending" : "Halt all sending"}
							</Button>
							{reasonRequired && (
								<p
									className="text-sm text-foreground-muted"
									data-testid="rrm-ramp-reason-hint"
								>
									A reason is required before this button is usable.
								</p>
							)}
						</div>
					</CardContent>
				</Card>
			</div>
 
			<ConfirmDialog
				open={dialog === "release"}
				title={`Release ${ramp.nextReleaseCount.toLocaleString()} prospects?`}
				description={
					override
						? `This releases past a failing gate. Your reason and the failing conditions are recorded against you. ${ramp.sendableRemaining.toLocaleString()} remain sendable, leaving a ${ramp.reservePercentAfterRelease}% reserve.`
						: `They become eligible immediately. ${ramp.sendableRemaining.toLocaleString()} remain sendable, leaving a ${ramp.reservePercentAfterRelease}% reserve.`
				}
				confirmLabel="Release"
				onCancel={() => setDialog(null)}
				onConfirm={() => {
					void handleRelease(ramp.nextReleaseCount, override);
				}}
			/>
			<ConfirmDialog
				open={dialog === "halt"}
				variant="destructive"
				title="Halt all sending?"
				description="Every queued send stops until someone resumes. Replies still arrive and still need answering."
				confirmLabel="Halt sending"
				onCancel={() => setDialog(null)}
				onConfirm={() => {
					void handleHalt(true);
				}}
			/>
			<ConfirmDialog
				open={dialog === "resume"}
				title="Resume sending?"
				description="Queued sends restart at the configured hourly rate, inside the send window."
				confirmLabel="Resume"
				onCancel={() => setDialog(null)}
				onConfirm={() => {
					void handleHalt(false);
				}}
			/>
		</div>
	);
}