All files / src/components/settings ConnectorsTab.tsx

72.3% Statements 154/213
61.73% Branches 142/230
67.03% Functions 61/91
73.03% Lines 149/204

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 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468                                                                11x                                                   12x                                     12x 12x 12x 12x 12x 12x                               1x 1x 1x 1x 1x                                           1x           1x   1x       1x       12x                           1x                             1x                                               1x                                                                                                   1x                               1x                                                                                                                                                                                                                                                                                                                                                                                                                                                           9x                                             9x                               9x 9x     1x 1x 1x 1x 1x                                     1x     1x   1x       1x       9x                           1x                                                                         1x                                                                                                   1x                               1x                                                                                                                                                                                           42x 42x 42x 42x 42x     42x 12x 6x     5x 5x 5x     1x         42x 7x       4x 4x 4x 4x 4x 2x             2x           2x   2x   4x       35x                                   8x                               11x                                                         169x           169x           169x                               194x   194x 194x     194x 194x 194x             194x     2x 2x 2x 2x                         1x 1x 1x 1x                                                     194x                       5x                                 1x 1x   1x                             105x                                                           1x                                                                                               9x               2x               1x 1x                                 1x                                                       105x 105x 40x       105x 105x     105x 105x 105x 105x     105x     2x 2x 2x 2x             1x 1x 1x 1x             3x 3x 2x 2x   1x       105x                       4x                                 1x 1x   1x                             68x 67x   68x 68x                                                               1x                                 2x                                 1x                                       66x           1x 1x 1x     1x 1x                                   6x 6x               4x                               1x 1x 1x                       6x 6x                                                     1x             3x                        
import { Fragment, useEffect, useState } from "react";
import {
	api,
	type CreateInboundConnectorRequest,
	type CreateOutboundConnectorRequest,
	type Identity,
	type InboundConnector,
	type OutboundConnector,
} from "../../api";
import { useAsync } from "../../hooks";
import { ConnectorTransitionWizard } from "./ConnectorTransitionWizard";
import { SyncStatusPanel } from "./SyncStatusPanel";
 
// ── Inbound Connector Form ─────────────────────────────────────────────────
 
interface InboundFormData {
	name: string;
	type: "imap" | "cloudflare-r2";
	imap_host: string;
	imap_port: number;
	imap_tls: number;
	imap_user: string;
	imap_pass: string;
	sync_delete_from_server: number;
	cf_r2_account_id: string;
	cf_r2_bucket_name: string;
	cf_r2_access_key_id: string;
	cf_r2_secret_access_key: string;
	cf_r2_prefix: string;
}
 
function defaultInboundForm(): InboundFormData {
	return {
		name: "",
		type: "imap",
		imap_host: "",
		imap_port: 993,
		imap_tls: 1,
		imap_user: "",
		imap_pass: "",
		sync_delete_from_server: 0,
		cf_r2_account_id: "",
		cf_r2_bucket_name: "",
		cf_r2_access_key_id: "",
		cf_r2_secret_access_key: "",
		cf_r2_prefix: "pending/",
	};
}
 
function InboundConnectorForm({
	initial,
	onSave,
	onCancel,
}: {
	initial?: InboundConnector;
	onSave: () => void;
	onCancel: () => void;
}) {
	const [form, setForm] = useState<InboundFormData>(
		initial
			? {
					name: initial.name,
					type: initial.type,
					imap_host: initial.imap_host ?? "",
					imap_port: initial.imap_port,
					imap_tls: initial.imap_tls,
					imap_user: initial.imap_user ?? "",
					imap_pass: "",
					sync_delete_from_server: initial.sync_delete_from_server ?? 0,
					cf_r2_account_id: initial.cf_r2_account_id ?? "",
					cf_r2_bucket_name: initial.cf_r2_bucket_name ?? "",
					cf_r2_access_key_id: initial.cf_r2_access_key_id ?? "",
					cf_r2_secret_access_key: "",
					cf_r2_prefix: initial.cf_r2_prefix ?? "pending/",
				}
			: defaultInboundForm(),
	);
	const [saving, setSaving] = useState(false);
	const [error, setError] = useState<string | null>(null);
	const [showConnectorWarning, setShowConnectorWarning] = useState(false);
	const [showTransitionWizard, setShowTransitionWizard] = useState(false);
	const [cleanAfterSave, setCleanAfterSave] = useState(false);
	const wasInConnectorMode = initial ? (initial.sync_delete_from_server ?? 0) === 1 : false;
 
	function handleSelectConnectorMode() {
		if (!wasInConnectorMode && initial) {
			// Existing connector switching from mirror → connector: show wizard
			setShowTransitionWizard(true);
		} else {
			// New connector or already in connector mode — just toggle
			setForm((f) => ({ ...f, sync_delete_from_server: 1 }));
			if (!wasInConnectorMode) {
				setShowConnectorWarning(true);
			}
		}
	}
 
	async function handleSubmit(e: React.FormEvent) {
		e.preventDefault();
		setSaving(true);
		setError(null);
		try {
			const payload: CreateInboundConnectorRequest = {
				name: form.name,
				type: form.type,
				...(form.type === "imap"
					? {
							imap_host: form.imap_host,
							imap_port: form.imap_port,
							imap_tls: form.imap_tls,
							imap_user: form.imap_user,
							sync_delete_from_server: form.sync_delete_from_server,
							...(form.imap_pass ? { imap_pass: form.imap_pass } : {}),
						}
					: {
							cf_r2_account_id: form.cf_r2_account_id,
							cf_r2_bucket_name: form.cf_r2_bucket_name,
							cf_r2_access_key_id: form.cf_r2_access_key_id,
							cf_r2_prefix: form.cf_r2_prefix || "pending/",
							...(form.cf_r2_secret_access_key
								? { cf_r2_secret_access_key: form.cf_r2_secret_access_key }
								: {}),
						}),
			};
			Iif (initial) {
				await api.connectors.inbound.update(initial.id, payload);
				if (cleanAfterSave) {
					await api.connectors.inbound.cleanServer(initial.id);
				}
			} else {
				await api.connectors.inbound.create(payload);
			}
			onSave();
		} catch (err) {
			setError(err instanceof Error ? err.message : String(err));
		} finally {
			setSaving(false);
		}
	}
 
	return (
		<form onSubmit={handleSubmit} className="space-y-3">
			<div>
				<label
					htmlFor="ib-name"
					className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
				>
					Name
				</label>
				<input
					id="ib-name"
					type="text"
					required
					value={form.name}
					onChange={(e) => setForm({ ...form, name: e.target.value })}
					className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
				/>
			</div>
 
			<div>
				<label
					htmlFor="ib-type"
					className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
				>
					Type
				</label>
				<select
					id="ib-type"
					value={form.type}
					onChange={(e) => setForm({ ...form, type: e.target.value as "imap" | "cloudflare-r2" })}
					className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
				>
					<option value="imap">IMAP</option>
					<option value="cloudflare-r2">Cloudflare R2 (queue/poll)</option>
				</select>
			</div>
 
			{/* "Two minutes" philosophy box moved below IMAP fields — see below */}
 
			{form.type === "imap" && (
				<>
					<div>
						<label
							htmlFor="ib-imap-host"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							IMAP Host
						</label>
						<input
							id="ib-imap-host"
							type="text"
							required
							value={form.imap_host}
							onChange={(e) => setForm({ ...form, imap_host: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					<div className="grid grid-cols-2 gap-3">
						<div>
							<label
								htmlFor="ib-imap-port"
								className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
							>
								Port
							</label>
							<input
								id="ib-imap-port"
								type="number"
								value={form.imap_port}
								onChange={(e) => setForm({ ...form, imap_port: Number(e.target.value) })}
								className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
							/>
						</div>
						<div>
							<label
								htmlFor="ib-imap-tls"
								className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
							>
								TLS
							</label>
							<select
								id="ib-imap-tls"
								value={form.imap_tls}
								onChange={(e) => setForm({ ...form, imap_tls: Number(e.target.value) })}
								className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
							>
								<option value={1}>Enabled</option>
								<option value={0}>Disabled</option>
							</select>
						</div>
					</div>
					<div>
						<label
							htmlFor="ib-imap-user"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							Username
						</label>
						<input
							id="ib-imap-user"
							type="text"
							required
							value={form.imap_user}
							onChange={(e) => setForm({ ...form, imap_user: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					<div>
						<label
							htmlFor="ib-imap-pass"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							Password{initial ? " (leave blank to keep existing)" : ""}
						</label>
						<input
							id="ib-imap-pass"
							type="password"
							required={!initial}
							value={form.imap_pass}
							onChange={(e) => setForm({ ...form, imap_pass: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					{/* Philosophy + Mirror vs Connector mode */}
					<div className="rounded-lg border-2 border-stork-300 dark:border-stork-700 bg-stork-50 dark:bg-stork-950 px-4 py-3 space-y-2">
						{!initial && (
							<>
								<p className="text-sm font-bold text-stork-800 dark:text-stork-200">
									⚡ Two minutes to understand how Stork thinks about email
								</p>
								<p className="text-xs text-stork-700 dark:text-stork-300">
									Most email clients treat your mail provider (Gmail, Fastmail, etc.) as the
									permanent home for your email. Stork{"'"}s philosophy is different:{" "}
									<strong>your provider is just the delivery edge</strong>. Mail arrives there,
									Stork picks it up and stores it encrypted on your own hardware, and — when you
									{"'"}re ready — clears it from the provider.
								</p>
								<p className="text-xs text-stork-700 dark:text-stork-300">
									<strong>Mirror mode (default):</strong> Stork reads alongside your provider. Both
									have copies. Perfect for trying Stork — your provider stays your safety net. Heads
									up: actions you take in Stork (delete, label, archive) stay local and don
									{"'"}t sync back.
								</p>
								<p className="text-xs text-stork-700 dark:text-stork-300">
									<strong>Connector mode:</strong> Once you{"'"}re confident, flip the switch. Stork
									becomes your permanent encrypted email home. Your provider is just a pipe — mail
									arrives, Stork grabs it and erases it from the server. Back up your Stork
									database.
								</p>
							</>
						)}
						<div className="space-y-1.5 pt-1">
							<label className="flex items-start gap-2 text-sm text-stork-800 dark:text-stork-200 cursor-pointer">
								<input
									type="radio"
									name="ib-sync-mode"
									value="mirror"
									checked={form.sync_delete_from_server === 0}
									onChange={() => {
										setForm((f) => ({ ...f, sync_delete_from_server: 0 }));
										setShowConnectorWarning(false);
									}}
									className="mt-0.5 shrink-0"
								/>
								<span>
									<span className="font-medium">Mirror mode</span> — Stork reads alongside your
									provider; your IMAP mailbox stays intact.
								</span>
							</label>
							<label className="flex items-start gap-2 text-sm text-stork-800 dark:text-stork-200 cursor-pointer">
								<input
									type="radio"
									name="ib-sync-mode"
									value="connector"
									checked={form.sync_delete_from_server === 1}
									onChange={handleSelectConnectorMode}
									className="mt-0.5 shrink-0"
								/>
								<span>
									<span className="font-medium">Connector mode</span> — After syncing, Stork deletes
									messages from your IMAP server and becomes your permanent encrypted email home.
								</span>
							</label>
							{showConnectorWarning && (
								<p className="text-xs text-emerald-700 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-900/20 rounded px-3 py-2">
									Great choice! Just so you know: Stork will remove messages from your IMAP mailbox
									after importing them — Stork becomes the single source of truth for your email.
									Make sure to keep your Stork database backed up.
								</p>
							)}
						</div>
					</div>
				</>
			)}
 
			{form.type === "cloudflare-r2" && (
				<>
					<div className="text-xs text-blue-700 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20 rounded px-3 py-2 space-y-1">
						<p className="font-medium">Cloudflare R2 queue/poll model</p>
						<p>
							A Cloudflare Email Worker writes each inbound email as an object to an R2 bucket.
							Stork polls the bucket on a regular interval, downloads and stores each message, then
							deletes the object. This works reliably behind a VPN or without a public-facing
							webhook endpoint.
						</p>
					</div>
					<div>
						<label
							htmlFor="ib-r2-account"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							Cloudflare Account ID
						</label>
						<input
							id="ib-r2-account"
							type="text"
							required
							value={form.cf_r2_account_id}
							onChange={(e) => setForm({ ...form, cf_r2_account_id: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					<div>
						<label
							htmlFor="ib-r2-bucket"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							R2 Bucket Name
						</label>
						<input
							id="ib-r2-bucket"
							type="text"
							required
							value={form.cf_r2_bucket_name}
							onChange={(e) => setForm({ ...form, cf_r2_bucket_name: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					<div>
						<label
							htmlFor="ib-r2-aki"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							R2 Access Key ID
						</label>
						<input
							id="ib-r2-aki"
							type="text"
							required
							value={form.cf_r2_access_key_id}
							onChange={(e) => setForm({ ...form, cf_r2_access_key_id: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					<div>
						<label
							htmlFor="ib-r2-sak"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							R2 Secret Access Key{initial ? " (leave blank to keep existing)" : ""}
						</label>
						<input
							id="ib-r2-sak"
							type="password"
							required={!initial}
							value={form.cf_r2_secret_access_key}
							onChange={(e) => setForm({ ...form, cf_r2_secret_access_key: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					<div>
						<label
							htmlFor="ib-r2-prefix"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							Object Prefix <span className="text-gray-400 font-normal">(default: pending/)</span>
						</label>
						<input
							id="ib-r2-prefix"
							type="text"
							value={form.cf_r2_prefix}
							onChange={(e) => setForm({ ...form, cf_r2_prefix: e.target.value })}
							placeholder="pending/"
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
				</>
			)}
 
			{error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
 
			<div className="flex gap-2 pt-1">
				<button
					type="submit"
					disabled={saving}
					className="px-4 py-1.5 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 disabled:opacity-50"
				>
					{saving ? "Saving…" : "Save"}
				</button>
				<button
					type="button"
					onClick={onCancel}
					className="px-4 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
				>
					Cancel
				</button>
			</div>
 
			{showTransitionWizard && initial && (
				<ConnectorTransitionWizard
					connectorId={initial.id}
					connectorName={initial.name}
					onConfirm={(shouldClean) => {
						setForm((f) => ({ ...f, sync_delete_from_server: 1 }));
						setShowConnectorWarning(true);
						setShowTransitionWizard(false);
						setCleanAfterSave(shouldClean);
					}}
					onCancel={() => setShowTransitionWizard(false)}
				/>
			)}
		</form>
	);
}
 
// ── Outbound Connector Form ────────────────────────────────────────────────
 
interface OutboundFormData {
	name: string;
	type: "smtp" | "ses";
	smtp_host: string;
	smtp_port: number;
	smtp_tls: number;
	smtp_user: string;
	smtp_pass: string;
	ses_region: string;
	ses_access_key_id: string;
	ses_secret_access_key: string;
}
 
function defaultOutboundForm(): OutboundFormData {
	return {
		name: "",
		type: "smtp",
		smtp_host: "",
		smtp_port: 587,
		smtp_tls: 1,
		smtp_user: "",
		smtp_pass: "",
		ses_region: "",
		ses_access_key_id: "",
		ses_secret_access_key: "",
	};
}
 
function OutboundConnectorForm({
	initial,
	onSave,
	onCancel,
}: {
	initial?: OutboundConnector;
	onSave: () => void;
	onCancel: () => void;
}) {
	const [form, setForm] = useState<OutboundFormData>(
		initial
			? {
					name: initial.name,
					type: initial.type,
					smtp_host: initial.smtp_host ?? "",
					smtp_port: initial.smtp_port,
					smtp_tls: initial.smtp_tls,
					smtp_user: initial.smtp_user ?? "",
					smtp_pass: "",
					ses_region: initial.ses_region ?? "",
					ses_access_key_id: initial.ses_access_key_id ?? "",
					ses_secret_access_key: "",
				}
			: defaultOutboundForm(),
	);
	const [saving, setSaving] = useState(false);
	const [error, setError] = useState<string | null>(null);
 
	async function handleSubmit(e: React.FormEvent) {
		e.preventDefault();
		setSaving(true);
		setError(null);
		try {
			const payload: CreateOutboundConnectorRequest = {
				name: form.name,
				type: form.type,
				...(form.type === "smtp"
					? {
							smtp_host: form.smtp_host,
							smtp_port: form.smtp_port,
							smtp_tls: form.smtp_tls,
							smtp_user: form.smtp_user,
							...(form.smtp_pass ? { smtp_pass: form.smtp_pass } : {}),
						}
					: {
							ses_region: form.ses_region,
							ses_access_key_id: form.ses_access_key_id,
							...(form.ses_secret_access_key
								? { ses_secret_access_key: form.ses_secret_access_key }
								: {}),
						}),
			};
			Iif (initial) {
				await api.connectors.outbound.update(initial.id, payload);
			} else {
				await api.connectors.outbound.create(payload);
			}
			onSave();
		} catch (err) {
			setError(err instanceof Error ? err.message : String(err));
		} finally {
			setSaving(false);
		}
	}
 
	return (
		<form onSubmit={handleSubmit} className="space-y-3">
			<div>
				<label
					htmlFor="ob-name"
					className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
				>
					Name
				</label>
				<input
					id="ob-name"
					type="text"
					required
					value={form.name}
					onChange={(e) => setForm({ ...form, name: e.target.value })}
					className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
				/>
			</div>
 
			<div>
				<label
					htmlFor="ob-type"
					className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
				>
					Type
				</label>
				<select
					id="ob-type"
					value={form.type}
					onChange={(e) => setForm({ ...form, type: e.target.value as "smtp" | "ses" })}
					className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
				>
					<option value="smtp">SMTP</option>
					<option value="ses">AWS SES</option>
				</select>
			</div>
 
			{form.type === "smtp" && (
				<>
					<div>
						<label
							htmlFor="ob-smtp-host"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							SMTP Host
						</label>
						<input
							id="ob-smtp-host"
							type="text"
							required
							value={form.smtp_host}
							onChange={(e) => setForm({ ...form, smtp_host: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					<div className="grid grid-cols-2 gap-3">
						<div>
							<label
								htmlFor="ob-smtp-port"
								className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
							>
								Port
							</label>
							<input
								id="ob-smtp-port"
								type="number"
								value={form.smtp_port}
								onChange={(e) => setForm({ ...form, smtp_port: Number(e.target.value) })}
								className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
							/>
						</div>
						<div>
							<label
								htmlFor="ob-smtp-tls"
								className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
							>
								TLS
							</label>
							<select
								id="ob-smtp-tls"
								value={form.smtp_tls}
								onChange={(e) => setForm({ ...form, smtp_tls: Number(e.target.value) })}
								className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
							>
								<option value={1}>Enabled</option>
								<option value={0}>Disabled</option>
							</select>
						</div>
					</div>
					<div>
						<label
							htmlFor="ob-smtp-user"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							Username
						</label>
						<input
							id="ob-smtp-user"
							type="text"
							required
							value={form.smtp_user}
							onChange={(e) => setForm({ ...form, smtp_user: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					<div>
						<label
							htmlFor="ob-smtp-pass"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							Password{initial ? " (leave blank to keep existing)" : ""}
						</label>
						<input
							id="ob-smtp-pass"
							type="password"
							required={!initial}
							value={form.smtp_pass}
							onChange={(e) => setForm({ ...form, smtp_pass: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
				</>
			)}
 
			{form.type === "ses" && (
				<>
					<div>
						<label
							htmlFor="ob-ses-region"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							AWS Region
						</label>
						<input
							id="ob-ses-region"
							type="text"
							required
							placeholder="us-east-1"
							value={form.ses_region}
							onChange={(e) => setForm({ ...form, ses_region: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					<div>
						<label
							htmlFor="ob-ses-aki"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							Access Key ID (optional — uses instance role if omitted)
						</label>
						<input
							id="ob-ses-aki"
							type="text"
							value={form.ses_access_key_id}
							onChange={(e) => setForm({ ...form, ses_access_key_id: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
					<div>
						<label
							htmlFor="ob-ses-sak"
							className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
						>
							Secret Access Key{initial ? " (leave blank to keep existing)" : ""}
						</label>
						<input
							id="ob-ses-sak"
							type="password"
							value={form.ses_secret_access_key}
							onChange={(e) => setForm({ ...form, ses_secret_access_key: e.target.value })}
							className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
						/>
					</div>
				</>
			)}
 
			{error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
 
			<div className="flex gap-2 pt-1">
				<button
					type="submit"
					disabled={saving}
					className="px-4 py-1.5 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 disabled:opacity-50"
				>
					{saving ? "Saving…" : "Save"}
				</button>
				<button
					type="button"
					onClick={onCancel}
					className="px-4 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
				>
					Cancel
				</button>
			</div>
		</form>
	);
}
 
// ── Identity Form ──────────────────────────────────────────────────────────
 
function IdentityForm({
	outboundConnectorId,
	identityId,
	onSave,
	onCancel,
}: {
	outboundConnectorId: number;
	identityId: number | null;
	onSave: () => void;
	onCancel: () => void;
}) {
	const [name, setName] = useState("");
	const [email, setEmail] = useState("");
	const [saving, setSaving] = useState(false);
	const [error, setError] = useState<string | null>(null);
	const [loaded, setLoaded] = useState(identityId === null);
 
	// Load existing identity data when editing
	useEffect(() => {
		if (identityId === null) return;
		api.identities
			.get(identityId)
			.then((detail) => {
				setName(detail.name);
				setEmail(detail.email);
				setLoaded(true);
			})
			.catch((err) => {
				setError(err instanceof Error ? err.message : String(err));
			});
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [identityId]);
 
	if (!loaded) {
		return <div className="p-3 text-sm text-gray-400 dark:text-gray-500">Loading...</div>;
	}
 
	async function handleSubmit(e: React.FormEvent) {
		e.preventDefault();
		setSaving(true);
		setError(null);
		try {
			if (identityId === null) {
				await api.identities.create({
					name,
					email,
					outbound_connector_id: outboundConnectorId,
					default_view: "inbox",
				});
			} else {
				await api.identities.update(identityId, {
					name,
					email,
					outbound_connector_id: outboundConnectorId,
				});
			}
			onSave();
		} catch (err) {
			setError(err instanceof Error ? err.message : String(err));
		} finally {
			setSaving(false);
		}
	}
 
	return (
		<form
			onSubmit={handleSubmit}
			className="space-y-3 p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700 mt-2"
		>
			<div className="grid grid-cols-2 gap-3">
				<div>
					<label
						htmlFor="id-name"
						className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1"
					>
						Name
					</label>
					<input
						id="id-name"
						type="text"
						required
						value={name}
						onChange={(e) => setName(e.target.value)}
						className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
					/>
				</div>
				<div>
					<label
						htmlFor="id-email"
						className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1"
					>
						Email
					</label>
					<input
						id="id-email"
						type="email"
						required
						value={email}
						onChange={(e) => setEmail(e.target.value)}
						className="w-full rounded border border-gray-300 dark:border-gray-600 px-3 py-1.5 text-sm dark:bg-gray-800 dark:text-gray-100"
					/>
				</div>
			</div>
			{error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
			<div className="flex gap-2">
				<button
					type="submit"
					disabled={saving}
					className="px-4 py-1.5 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 disabled:opacity-50"
				>
					{saving ? "Saving…" : "Save"}
				</button>
				<button
					type="button"
					onClick={onCancel}
					className="px-4 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
				>
					Cancel
				</button>
			</div>
		</form>
	);
}
 
// ── Connector List Item ────────────────────────────────────────────────────
 
function ConnectorBadge({ type }: { type: string }) {
	const colors: Record<string, string> = {
		imap: "bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300",
		"cloudflare-r2": "bg-orange-100 text-orange-700 dark:bg-orange-900 dark:text-orange-300",
		smtp: "bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300",
		ses: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900 dark:text-yellow-300",
	};
	const label: Record<string, string> = {
		imap: "IMAP",
		"cloudflare-r2": "Cloudflare R2",
		smtp: "SMTP",
		ses: "SES",
	};
	return (
		<span
			className={`inline-block px-1.5 py-0.5 rounded text-xs font-medium ${colors[type] ?? "bg-gray-100 text-gray-600"}`}
		>
			{label[type] ?? type}
		</span>
	);
}
 
// ── Inbound Connectors Tab ─────────────────────────────────────────────────
 
export function InboundConnectorsTab() {
	const {
		data: inbound,
		refetch: refetchInbound,
		loading: loadingInbound,
	} = useAsync(() => api.connectors.inbound.list(), []);
 
	const [editingInbound, setEditingInbound] = useState<number | "new" | null>(null);
	const [testResult, setTestResult] = useState<{ id: number; ok: boolean; msg: string } | null>(
		null,
	);
	const [deleting, setDeleting] = useState<number | null>(null);
	const [syncStatusConnectorId, setSyncStatusConnectorId] = useState<number | null>(null);
	const [cleanServer, setCleanServer] = useState<{
		connectorId: number;
		step: "loading" | "confirm" | "deleting";
		count?: number;
	} | null>(null);
 
	const inboundEditing =
		editingInbound === "new" ? undefined : inbound?.find((c) => c.id === editingInbound);
 
	async function handleTestInbound(id: number) {
		setTestResult(null);
		try {
			const r = await api.connectors.inbound.test(id);
			setTestResult({
				id,
				ok: r.ok,
				msg: r.ok
					? `OK${r.details?.folders != null ? ` — ${r.details.folders} folders` : ""}`
					: (r.error ?? "Test failed"),
			});
		} catch (err) {
			setTestResult({ id, ok: false, msg: String(err) });
		}
	}
 
	async function handleDeleteInbound(id: number) {
		try {
			await api.connectors.inbound.delete(id);
			setDeleting(null);
			refetchInbound();
		} catch (err) {
			alert(err instanceof Error ? err.message : String(err));
		}
	}
 
	async function handleInitCleanServer(id: number) {
		setCleanServer({ connectorId: id, step: "loading" });
		try {
			const { count } = await api.connectors.inbound.syncedCount(id);
			setCleanServer({ connectorId: id, step: "confirm", count });
		} catch (err) {
			alert(err instanceof Error ? err.message : String(err));
			setCleanServer(null);
		}
	}
 
	async function handleConfirmCleanServer(id: number) {
		setCleanServer((s) => (s ? { ...s, step: "deleting" } : null));
		try {
			await api.connectors.inbound.cleanServer(id);
		} catch (err) {
			alert(err instanceof Error ? err.message : String(err));
		}
		setCleanServer(null);
	}
 
	return (
		<div className="space-y-4 p-4 sm:p-6">
			<div className="flex items-center justify-between mb-1">
				<div>
					<h3 className="font-semibold text-gray-900 dark:text-gray-100">Inbound Connectors</h3>
					<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
						Receive email via IMAP polling or Cloudflare R2 queue/poll
					</p>
				</div>
				{editingInbound === null && (
					<button
						type="button"
						onClick={() => setEditingInbound("new")}
						className="px-3 py-1.5 text-sm bg-blue-600 text-white rounded hover:bg-blue-700"
					>
						Add
					</button>
				)}
			</div>
 
			{editingInbound !== null && (
				<div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg bg-gray-50 dark:bg-gray-800/50">
					<h4 className="text-sm font-medium text-gray-800 dark:text-gray-200 mb-3">
						{editingInbound === "new" ? "New Inbound Connector" : "Edit Inbound Connector"}
					</h4>
					<InboundConnectorForm
						key={editingInbound}
						initial={inboundEditing}
						onSave={() => {
							setEditingInbound(null);
							refetchInbound();
						}}
						onCancel={() => setEditingInbound(null)}
					/>
				</div>
			)}
 
			{loadingInbound && <p className="text-sm text-gray-500 dark:text-gray-400">Loading…</p>}
 
			{!loadingInbound && inbound?.length === 0 && (
				<p className="text-sm text-gray-500 dark:text-gray-400 italic">
					No inbound connectors configured yet.
				</p>
			)}
 
			<ul className="space-y-2">
				{inbound?.map((c) => (
					<Fragment key={c.id}>
						<li
							className={`flex items-center justify-between gap-3 p-3 rounded-lg border ${editingInbound === c.id ? "border-blue-400 dark:border-blue-500 bg-blue-50 dark:bg-blue-900/20" : "border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800"}`}
						>
							<div className="min-w-0">
								<div className="flex items-center gap-2">
									<span className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
										{c.name}
									</span>
									<ConnectorBadge type={c.type} />
								</div>
								<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate">
									{c.type === "imap"
										? `${c.imap_user ?? ""}@${c.imap_host ?? ""}:${c.imap_port}`
										: `R2: ${c.cf_r2_bucket_name ?? "bucket not set"}`}
								</p>
								{testResult?.id === c.id && (
									<p
										className={`text-xs mt-0.5 ${testResult.ok ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}`}
									>
										{testResult.msg}
									</p>
								)}
							</div>
							<div className="flex items-center gap-1.5 shrink-0">
								{deleting === c.id ? (
									<>
										<span className="text-xs text-red-600 dark:text-red-400">Delete?</span>
										<button
											type="button"
											onClick={() => handleDeleteInbound(c.id)}
											className="text-xs text-red-600 dark:text-red-400 hover:underline"
										>
											Yes
										</button>
										<button
											type="button"
											onClick={() => setDeleting(null)}
											className="text-xs text-gray-500 hover:underline"
										>
											No
										</button>
									</>
								) : cleanServer?.connectorId === c.id ? (
									<>
										{cleanServer.step === "loading" && (
											<span className="text-xs text-gray-500 dark:text-gray-400">Loading…</span>
										)}
										{cleanServer.step === "confirm" && (
											<>
												<span className="text-xs text-orange-700 dark:text-orange-400">
													~{cleanServer.count} messages on server. Remove? This cannot be undone.
												</span>
												<button
													type="button"
													onClick={() => handleConfirmCleanServer(c.id)}
													className="text-xs text-red-600 dark:text-red-400 hover:underline"
												>
													Yes, remove
												</button>
												<button
													type="button"
													onClick={() => setCleanServer(null)}
													className="text-xs text-gray-500 hover:underline"
												>
													Keep
												</button>
											</>
										)}
										{cleanServer.step === "deleting" && (
											<span className="text-xs text-gray-500 dark:text-gray-400">Removing…</span>
										)}
									</>
								) : (
									<>
										<button
											type="button"
											onClick={() =>
												setSyncStatusConnectorId(syncStatusConnectorId === c.id ? null : c.id)
											}
											className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 px-2 py-1 rounded border border-gray-200 dark:border-gray-600"
										>
											Sync Status
										</button>
										<button
											type="button"
											onClick={() => handleTestInbound(c.id)}
											className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 px-2 py-1 rounded border border-gray-200 dark:border-gray-600"
										>
											Test
										</button>
										<button
											type="button"
											onClick={() => {
												setEditingInbound(c.id);
												setTestResult(null);
											}}
											className={`text-xs ${editingInbound === c.id ? "text-blue-800 dark:text-blue-300 font-medium" : "text-blue-600 dark:text-blue-400 hover:underline"}`}
										>
											{editingInbound === c.id ? "Editing" : "Edit"}
										</button>
										{c.type === "imap" && c.sync_delete_from_server === 1 && (
											<button
												type="button"
												onClick={() => handleInitCleanServer(c.id)}
												className="text-xs text-orange-500 dark:text-orange-400 hover:text-orange-700 dark:hover:text-orange-200 px-2 py-1 rounded border border-orange-200 dark:border-orange-700"
											>
												Clean Server
											</button>
										)}
										<button
											type="button"
											onClick={() => setDeleting(c.id)}
											className="text-xs text-gray-400 hover:text-red-600 dark:hover:text-red-400"
										>
											Delete
										</button>
									</>
								)}
							</div>
						</li>
						{syncStatusConnectorId === c.id && (
							<li className="rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 overflow-hidden">
								<SyncStatusPanel connectorId={c.id} />
							</li>
						)}
					</Fragment>
				))}
			</ul>
		</div>
	);
}
 
// ── Outbound Connectors Tab ────────────────────────────────────────────────
 
export function OutboundConnectorsTab() {
	const {
		data: outbound,
		refetch: refetchOutbound,
		loading: loadingOutbound,
	} = useAsync(() => api.connectors.outbound.list(), []);
	const { data: identities, refetch: refetchIdentities } = useAsync(
		() => api.identities.list(),
		[],
	);
 
	const [editingOutbound, setEditingOutbound] = useState<number | "new" | null>(null);
	const [testResult, setTestResult] = useState<{ id: number; ok: boolean; msg: string } | null>(
		null,
	);
	const [deleting, setDeleting] = useState<number | null>(null);
	const [editingIdentityFor, setEditingIdentityFor] = useState<number | null>(null);
	const [editingIdentityId, setEditingIdentityId] = useState<number | "new" | null>(null);
	const [deletingIdentity, setDeletingIdentity] = useState<Identity | null>(null);
 
	const outboundEditing =
		editingOutbound === "new" ? undefined : outbound?.find((c) => c.id === editingOutbound);
 
	async function handleTestOutbound(id: number) {
		setTestResult(null);
		try {
			const r = await api.connectors.outbound.test(id);
			setTestResult({ id, ok: r.ok, msg: r.ok ? "OK" : (r.error ?? "Test failed") });
		} catch (err) {
			setTestResult({ id, ok: false, msg: String(err) });
		}
	}
 
	async function handleDeleteOutbound(id: number) {
		try {
			await api.connectors.outbound.delete(id);
			setDeleting(null);
			refetchOutbound();
		} catch (err) {
			alert(err instanceof Error ? err.message : String(err));
		}
	}
 
	async function handleDeleteIdentity(id: number) {
		try {
			await api.identities.delete(id);
			setDeletingIdentity(null);
			refetchIdentities();
		} catch (err) {
			alert(err instanceof Error ? err.message : String(err));
		}
	}
 
	return (
		<div className="space-y-4 p-4 sm:p-6">
			<div className="flex items-center justify-between mb-1">
				<div>
					<h3 className="font-semibold text-gray-900 dark:text-gray-100">Outbound Connectors</h3>
					<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
						Send email via SMTP or AWS SES. Each connector can have one or more sending identities.
					</p>
				</div>
				{editingOutbound === null && (
					<button
						type="button"
						onClick={() => setEditingOutbound("new")}
						className="px-3 py-1.5 text-sm bg-blue-600 text-white rounded hover:bg-blue-700"
					>
						Add
					</button>
				)}
			</div>
 
			{editingOutbound !== null && (
				<div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg bg-gray-50 dark:bg-gray-800/50">
					<h4 className="text-sm font-medium text-gray-800 dark:text-gray-200 mb-3">
						{editingOutbound === "new" ? "New Outbound Connector" : "Edit Outbound Connector"}
					</h4>
					<OutboundConnectorForm
						key={editingOutbound}
						initial={outboundEditing}
						onSave={() => {
							setEditingOutbound(null);
							refetchOutbound();
						}}
						onCancel={() => setEditingOutbound(null)}
					/>
				</div>
			)}
 
			{loadingOutbound && <p className="text-sm text-gray-500 dark:text-gray-400">Loading…</p>}
 
			{!loadingOutbound && outbound?.length === 0 && (
				<p className="text-sm text-gray-500 dark:text-gray-400 italic">
					No outbound connectors configured yet.
				</p>
			)}
 
			<ul className="space-y-3">
				{outbound?.map((c) => {
					const connectorIdentities = (identities ?? []).filter(
						(a) => a.outbound_connector_id === c.id,
					);
					const isEditingIdentityHere = editingIdentityFor === c.id && editingIdentityId !== null;
					return (
						<li
							key={c.id}
							className={`rounded-lg border ${editingOutbound === c.id ? "border-blue-400 dark:border-blue-500 bg-blue-50 dark:bg-blue-900/20" : "border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800"} overflow-hidden`}
						>
							<div className="flex items-center justify-between gap-3 p-3">
								<div className="min-w-0">
									<div className="flex items-center gap-2">
										<span className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
											{c.name}
										</span>
										<ConnectorBadge type={c.type} />
									</div>
									<p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate">
										{c.type === "smtp"
											? `${c.smtp_user ?? ""}@${c.smtp_host ?? ""}:${c.smtp_port}`
											: `SES — ${c.ses_region ?? "region not set"}`}
									</p>
									{testResult?.id === c.id && (
										<p
											className={`text-xs mt-0.5 ${testResult.ok ? "text-green-600 dark:text-green-400" : "text-red-600 dark:text-red-400"}`}
										>
											{testResult.msg}
										</p>
									)}
								</div>
								<div className="flex items-center gap-1.5 shrink-0">
									{deleting === c.id ? (
										<>
											<span className="text-xs text-red-600 dark:text-red-400">Delete?</span>
											<button
												type="button"
												onClick={() => handleDeleteOutbound(c.id)}
												className="text-xs text-red-600 dark:text-red-400 hover:underline"
											>
												Yes
											</button>
											<button
												type="button"
												onClick={() => setDeleting(null)}
												className="text-xs text-gray-500 hover:underline"
											>
												No
											</button>
										</>
									) : (
										<>
											<button
												type="button"
												onClick={() => handleTestOutbound(c.id)}
												className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 px-2 py-1 rounded border border-gray-200 dark:border-gray-600"
											>
												Test
											</button>
											<button
												type="button"
												onClick={() => {
													setEditingOutbound(c.id);
													setTestResult(null);
												}}
												className={`text-xs ${editingOutbound === c.id ? "text-blue-800 dark:text-blue-300 font-medium" : "text-blue-600 dark:text-blue-400 hover:underline"}`}
											>
												{editingOutbound === c.id ? "Editing" : "Edit"}
											</button>
											<button
												type="button"
												onClick={() => setDeleting(c.id)}
												className="text-xs text-gray-400 hover:text-red-600 dark:hover:text-red-400"
											>
												Delete
											</button>
										</>
									)}
								</div>
							</div>
 
							<div className="border-t border-gray-100 dark:border-gray-700/50 px-3 pb-3 pt-2">
								<p className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">
									Identities
								</p>
								{connectorIdentities.length === 0 && !isEditingIdentityHere && (
									<p className="text-xs text-gray-400 dark:text-gray-500 italic mb-2">
										No identities assigned to this connector.
									</p>
								)}
								{connectorIdentities.map((identity) => (
									<div key={identity.id}>
										{editingIdentityFor === c.id && editingIdentityId === identity.id ? (
											<IdentityForm
												outboundConnectorId={c.id}
												identityId={identity.id}
												onSave={() => {
													setEditingIdentityFor(null);
													setEditingIdentityId(null);
													refetchIdentities();
												}}
												onCancel={() => {
													setEditingIdentityFor(null);
													setEditingIdentityId(null);
												}}
											/>
										) : (
											<div className="mb-1">
												<div className="flex items-center justify-between gap-2 py-1.5 px-2 rounded hover:bg-gray-50 dark:hover:bg-gray-700/30">
													<div className="min-w-0">
														<span className="text-sm text-gray-900 dark:text-gray-100">
															{identity.name}
														</span>
														<span className="text-xs text-gray-400 dark:text-gray-500 ml-2">
															{identity.email}
														</span>
													</div>
													<div className="flex items-center gap-1.5 shrink-0">
														<button
															type="button"
															onClick={() => {
																setEditingIdentityFor(c.id);
																setEditingIdentityId(identity.id);
															}}
															className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
														>
															Edit
														</button>
														<button
															type="button"
															onClick={() => setDeletingIdentity(identity)}
															className="text-xs text-gray-400 hover:text-red-600 dark:hover:text-red-400"
														>
															Delete
														</button>
													</div>
												</div>
											</div>
										)}
									</div>
								))}
								{isEditingIdentityHere && editingIdentityId === "new" && (
									<IdentityForm
										outboundConnectorId={c.id}
										identityId={null}
										onSave={() => {
											setEditingIdentityFor(null);
											setEditingIdentityId(null);
											refetchIdentities();
										}}
										onCancel={() => {
											setEditingIdentityFor(null);
											setEditingIdentityId(null);
										}}
									/>
								)}
								{!isEditingIdentityHere && (
									<button
										type="button"
										onClick={() => {
											setEditingIdentityFor(c.id);
											setEditingIdentityId("new");
										}}
										className="mt-1 text-xs text-blue-600 dark:text-blue-400 hover:underline"
									>
										+ Add Identity
									</button>
								)}
							</div>
						</li>
					);
				})}
			</ul>
 
			{/* Delete identity confirmation */}
			{deletingIdentity && (
				<div className="fixed inset-0 z-60 flex items-center justify-center bg-black/50">
					<div className="bg-white dark:bg-gray-900 rounded-lg p-6 shadow-xl max-w-sm w-full mx-4 space-y-4">
						<h4 className="text-sm font-semibold text-gray-900 dark:text-gray-100">
							Delete identity
						</h4>
						<p className="text-sm text-gray-600 dark:text-gray-400">
							Delete &ldquo;{deletingIdentity.name}&rdquo; ({deletingIdentity.email})? This cannot
							be undone.
						</p>
						<div className="flex gap-2 justify-end">
							<button
								type="button"
								onClick={() => setDeletingIdentity(null)}
								className="px-3 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
							>
								Cancel
							</button>
							<button
								type="button"
								onClick={() => handleDeleteIdentity(deletingIdentity.id)}
								className="px-3 py-1.5 text-sm bg-red-600 text-white rounded hover:bg-red-700"
							>
								Delete Identity
							</button>
						</div>
					</div>
				</div>
			)}
		</div>
	);
}