File size: 65,193 Bytes
e9a4c3e
 
 
 
 
 
 
 
7f72224
868b75a
e88a3a3
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
868b75a
992a41f
e9a4c3e
e13472e
e9a4c3e
868b75a
c72f0a1
4b54047
 
e13472e
992a41f
e9a4c3e
8145bee
3e19b1e
868b75a
a5981db
e9a4c3e
 
 
e88a3a3
a83fcff
992a41f
c72f0a1
7f72224
9e15897
e9a4c3e
7f72224
 
 
 
 
 
e9a4c3e
868b75a
e88a3a3
868b75a
e88a3a3
 
 
7f72224
e88a3a3
 
e9a4c3e
868b75a
 
 
 
 
 
 
7f72224
868b75a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
868b75a
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
c72f0a1
 
e9a4c3e
 
 
 
7f72224
 
 
 
e9a4c3e
 
 
 
 
a83fcff
 
992a41f
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
e9a4c3e
 
 
 
 
 
 
 
 
7f72224
e9a4c3e
 
 
 
 
 
7f72224
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa8541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
4b54047
792ee39
 
 
 
e9a4c3e
792ee39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
e9a4c3e
e13472e
 
 
 
e9a4c3e
 
9a6cb9a
 
 
 
 
 
 
 
868b75a
 
e9a4c3e
 
 
 
 
 
 
 
 
 
cfa8541
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
 
 
 
e9a4c3e
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
 
 
 
8145bee
9a6cb9a
8145bee
9a6cb9a
 
 
e9a4c3e
 
 
9a6cb9a
e9a4c3e
868b75a
 
 
 
9a6cb9a
 
 
 
 
 
a83fcff
4b54047
dcd43e2
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
e9a4c3e
 
 
 
a83fcff
992a41f
e9a4c3e
 
 
 
 
 
7f72224
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
 
e9a4c3e
 
 
 
 
 
 
 
 
 
7f72224
e9a4c3e
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
792ee39
 
 
 
 
 
e9a4c3e
 
 
9a6cb9a
 
cfa8541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
4b54047
 
 
 
792ee39
 
 
 
 
 
 
e13472e
e9a4c3e
e13472e
 
 
 
 
e9a4c3e
 
9a6cb9a
 
868b75a
e9a4c3e
cfa8541
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
8145bee
 
 
 
 
 
 
 
 
9a6cb9a
 
e9a4c3e
 
 
 
 
9a6cb9a
 
 
 
 
e9a4c3e
9a6cb9a
 
 
 
 
e9a4c3e
 
 
 
 
 
 
c72f0a1
e9a4c3e
 
 
868b75a
 
a83fcff
dcd43e2
 
 
4b54047
 
 
 
 
e9a4c3e
 
 
 
 
0e600b9
 
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
e9a4c3e
 
3e19b1e
e9a4c3e
 
 
 
868b75a
 
 
 
 
 
e9a4c3e
8145bee
 
c72f0a1
 
 
 
e9a4c3e
868b75a
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
8145bee
 
 
c72f0a1
 
 
 
e9a4c3e
868b75a
 
 
c72f0a1
 
 
264a352
 
 
b2aa446
264a352
b2aa446
 
 
 
868b75a
e9a4c3e
868b75a
c72f0a1
868b75a
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
 
 
264a352
 
 
c72f0a1
868b75a
c72f0a1
a5981db
3e19b1e
c72f0a1
868b75a
8145bee
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
868b75a
 
a83fcff
 
 
868b75a
a83fcff
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
 
 
 
e9a4c3e
 
9a6cb9a
e9a4c3e
 
992a41f
9a6cb9a
992a41f
 
 
 
 
 
a93637f
 
 
 
 
 
 
 
 
 
 
9a6cb9a
992a41f
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
9a6cb9a
992a41f
 
e13472e
 
e9a4c3e
 
 
 
 
 
 
 
8145bee
e9a4c3e
 
 
7f72224
e9a4c3e
868b75a
792ee39
8145bee
e9a4c3e
992a41f
e9a4c3e
0e600b9
7f72224
868b75a
 
992a41f
 
 
868b75a
e13472e
 
 
 
7f72224
c72f0a1
e13472e
e9a4c3e
 
 
 
 
 
 
7f72224
868b75a
 
 
 
 
 
 
 
 
e13472e
 
992a41f
 
e13472e
 
992a41f
c72f0a1
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
dcd43e2
e9a4c3e
 
 
 
dcd43e2
 
3e19b1e
e9a4c3e
e13472e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
e13472e
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
dcd43e2
e9a4c3e
dcd43e2
 
 
 
e9a4c3e
 
dcd43e2
e9a4c3e
 
 
 
e13472e
e9a4c3e
9a6cb9a
 
 
 
e9a4c3e
dcd43e2
 
 
 
e9a4c3e
dcd43e2
 
 
e9a4c3e
dcd43e2
e9a4c3e
 
 
 
 
0e600b9
 
 
 
 
e9a4c3e
 
868b75a
992a41f
 
 
868b75a
 
992a41f
 
 
 
 
 
868b75a
 
992a41f
 
 
 
 
 
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a93637f
9a6cb9a
 
 
 
 
 
 
8145bee
 
 
 
 
 
 
9a6cb9a
 
e9a4c3e
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
 
 
e9a4c3e
 
992a41f
 
e9a4c3e
 
992a41f
 
e9a4c3e
 
 
 
992a41f
 
e9a4c3e
868b75a
 
9a6cb9a
992a41f
 
 
 
 
 
 
 
 
 
e9a4c3e
7f72224
 
 
e9a4c3e
 
 
 
 
 
c72f0a1
 
0e600b9
e9a4c3e
 
 
 
992a41f
 
 
 
 
 
e9a4c3e
 
7f72224
 
 
 
 
 
 
 
 
 
e9a4c3e
c72f0a1
a83fcff
 
c72f0a1
7f72224
 
c72f0a1
e13472e
 
 
 
81a8217
e13472e
 
 
dcd43e2
e13472e
9a6cb9a
e13472e
c72f0a1
a83fcff
 
e9a4c3e
c72f0a1
7f72224
e13472e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
e13472e
e9a4c3e
992a41f
 
e9a4c3e
 
 
 
 
 
 
 
 
 
0e600b9
e9a4c3e
 
 
 
 
0e600b9
8145bee
c72f0a1
992a41f
8145bee
992a41f
8145bee
e9a4c3e
c72f0a1
e13472e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
e13472e
 
 
 
 
e9a4c3e
 
0e600b9
e9a4c3e
 
 
e13472e
 
e9a4c3e
 
 
 
 
e88a3a3
e9a4c3e
 
 
 
 
 
 
 
e13472e
 
e9a4c3e
 
 
 
 
 
 
 
 
 
7f72224
e9a4c3e
868b75a
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
 
 
 
 
 
 
dcd43e2
e13472e
e9a4c3e
 
 
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
// ---------------------------------------------------------------------------
// connectors/ConnectorModal.tsx β€” W49-T12, ruling R26, contract C4.
//
// ⭐⭐ R26, verbatim: *"The connector popup is a centered MODAL with tabs Overview,
// Keychain, Databases, Relationships, opened from the card. The Keychain moves
// INTO it and Settings > Keychains becomes a link to the modal (one door). Field
// enablement moves into the Databases tab."*
//
// Overview and Setup are the only tabs. Retired keys open Setup.
// The C7 status reader stays mounted independently of the paged detail read.
//
// β›” NO REUSABLE MODAL COMPONENT EXISTS IN THIS REPO. `CustomerGrid.tsx`'s
// `LinkGridModal` owns the portal-plus-focus-trap pattern and is NOT exported, so
// it is READ as the model and never imported. What IS shared is the layer
// contract underneath it, `customer-grid/OverlaySurface`, which already carries
// the four behaviours the done-when names: focus trap, Escape, outside-pointer
// dismiss, and focus restored to whatever was focused when the overlay mounted.
// Re-implementing those here would be a second answer to one question.
//
// β›”β›” TWO TRAPS, BOTH PAID FOR ALREADY, BOTH RESOLVED IN `styles/wave49/connectors.css`:
//   (a) a portalled overlay paints its OWN background, or it renders transparent
//       over whatever it covers ([[a-portal-overlay-carries-its-own-surface]]);
//   (b) z-order is a THREE-WAY order, so the modal sits on the DIALOG step
//       (`--cg-z-record`) and the portal step (`--cg-z-overlay`) stays above it
//       ([[z-layering-is-a-three-way-order]]). Tokens, never a number.
//
// ⚠ NO CLIENT UNION OVER A SERVER VOCABULARY (the wave-9 law, and this directory's
// own header). `status` and `scope` arrive as STRINGS: a state the server adds
// later renders in the neutral tone instead of dropping the panel.
// ---------------------------------------------------------------------------

import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT } from "../apiContract";
import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { brandForConnector } from "./brandMarks";
import DatabasesTab, { parseDatabaseSyncHealth, useSyncNow } from "./DatabasesTab";
import type { SyncNowReceipt } from "./DatabasesTab";
import type { MaterializationCapability } from "./materializationJobs";
import "../styles/wave58/connectors.css";
import type { DatabaseReveal, DatabasesTabHandle } from "./DatabasesTab";
import KeychainTab, { amazonRotationNotice, RotationNotice, useRotationClock } from "./KeychainTab";
import MonidRunDialog from "./MonidRunDialog";
import AmazonDeletionNotice from "./AmazonDeletionNotice";
import AmazonWritesSwitch from "./AmazonWritesSwitch";
import { OdooSyncEvery } from "./OdooConfig";
import { AmazonSyncOverview, ConnectorSyncStatusLine, useConnectorSyncStatus, tileText } from "./ConnectorsPage";
import type { ConnectorRelationshipGraph, ConnectorRow } from "./ConnectorsPage";
import { parseRelationshipGraph } from "./ConnectorsPage";
import "../styles/wave49/connectors.css";
import "../styles/wave52/connectors.css";
import "../styles/wave55/connectors.css";
import "../styles/wave59/connectors.css";
import "../styles/sdlc74/connectors.css";
import "../styles/sdlc80/connector-setup.css";
import "../styles/sdlc81/connectors-type.css";

/** Retired tab keys remain aliases for existing deep links to Setup. */
export type ConnectorTab = "overview" | "setup" | "keychain" | "databases" | "relationships" | "cadence";

export function connectorTab(tab: ConnectorTab): "overview" | "setup" {
  return tab === "overview" ? "overview" : "setup";
}

/** Every connector keeps the same two tabs. */
export function connectorTabs(
  _row: ConnectorRow
): ReadonlyArray<{ key: ConnectorTab; label: string }> {
  return [
    { key: "overview", label: "Overview" },
    { key: "setup", label: "Setup" },
  ];
}

interface ConnectorSyncCapability {
  provider: string;
  supported: boolean;
  syncNow: ConnectorDetail["syncNow"];
}

/** Discover sync support without reading database pages or duplicating the provider registry. */
function useConnectorSyncCapability(connectorKey: string, refreshKey: number, directoryRow: ConnectorRow) {
  const identity = JSON.stringify([connectorKey, refreshKey]);
  const [reading, setReading] = useState<{
    identity: string; capability: ConnectorSyncCapability | null; problem: string;
  } | null>(null);
  useEffect(() => {
    const controller = new AbortController();
    void (async () => {
      try {
        const response = await fetch(`${API_V1}/connectors/${encodeURIComponent(connectorKey)}/sync-capability`, {
          credentials: CREDENTIALS, signal: controller.signal,
        });
        const body = obj(await response.json().catch(() => null));
        if (controller.signal.aborted) return;
        if (response.status === 401) window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
        if (!response.ok || body.provider !== connectorKey || typeof body.supported !== "boolean") {
          throw new Error("Sync status unavailable.");
        }
        const now = obj(body.syncNow);
        setReading({ identity, problem: "", capability: { provider: connectorKey, supported: body.supported,
          syncNow: body.supported && now.provider === connectorKey && now.path === `/connectors/${connectorKey}/sync/now`
            ? { provider: connectorKey, path: now.path } : null } });
      } catch {
        if (!controller.signal.aborted) setReading({ identity, capability: null, problem: "Sync status unavailable." });
      }
    })();
    return () => controller.abort();
  }, [connectorKey, identity, refreshKey]);
  const current = reading?.identity === identity ? reading : null;
  const declaredSupport = obj(directoryRow).syncSupported;
  // Directory support starts a fresh read. Only this open's capability response grants Sync now.
  const declaredCapability: ConnectorSyncCapability | null = directoryRow.key === connectorKey
    && typeof declaredSupport === "boolean"
    ? { provider: connectorKey, supported: declaredSupport, syncNow: null } : null;
  return { capability: current ? current.capability : declaredCapability, problem: current?.problem ?? "" };
}

/** Only a server-declared sync provider mounts the C7 reader. */
function ConnectorOverviewSyncStatus({ connectorKey, refreshKey, onReady }: {
  connectorKey: string; refreshKey: number;
  onReady?: (connectorKey: string, refreshKey: number) => void;
}) {
  const sync = useConnectorSyncStatus(connectorKey, undefined, refreshKey);
  useEffect(() => {
    if (sync.status || sync.problem) onReady?.(connectorKey, refreshKey);
  }, [connectorKey, refreshKey, onReady, sync.status, sync.problem]);
  return <ConnectorSyncStatusLine status={sync.status} problem={sync.problem} />;
}

export interface ConnectorOverview {
  key: string;
  label: string;
  /** The server's own word for the state. Read as a string, never a union. */
  status: string;
  account: string;
  source: string;
  creates: string[];
  /** Connection health is independent of the current database cursor page. */
  syncHealth?: unknown;
}

export interface ConnectorKeychainEntry {
  id: string;
  connectionId?: string;
  type?: string;
  slot?: number;
  status?: string;
  label: string;
  /** The masked preview, or "" when this reader is not allowed one (R4). */
  masked: string;
  scope: string;
  testable: boolean;
  /** Server-owned admin permission for the write-only replacement flow. */
  replaceable: boolean;
  /** Public Amazon-issued timestamp, empty or absent when unknown. Never a credential field. */
  client_secret_rotation_deadline?: string;
}

/**
 * What the Connect form must ask for, and what the server will accept.
 *
 * ⭐ AN ADDITION TO C4's `keychain` HALF, and the alternative is worse: the contract pins
 * `entries`, `canConnect` and `canDisconnect` but says nothing about where a form gets its
 * fields, and the only other answer is a client-side `type -> fields` map β€” a second copy of a
 * credential shape that already lives in the connector layer.
 */
export interface ConnectorConnectField {
  key: string;
  label: string;
  /** Renders as a password box, and is never echoed back. */
  secret: boolean;
  default?: string;
}

export interface ConnectorConnectSpec {
  /** The keychain entry type this connector stores, in the server's own word. */
  type: string;
  fields: ConnectorConnectField[];
  /** The scopes THIS reader may choose, already narrowed by R4 and by `TENANT_WIDE_TYPES`. */
  scopes: string[];
  tenantWide: boolean;
  defaultLabel?: string;
}

export interface ConnectorKeychainHalf {
  entries: ConnectorKeychainEntry[];
  canConnect: boolean;
  canDisconnect: boolean;
  migrationPending?: boolean;
  /** `null` when this connector has no credential door at all (Webhooks, the Scraper, OAuth). */
  connect: ConnectorConnectSpec | null;
}

export interface ConnectorDatabaseField {
  key: string;
  label: string;
  type: string;
  /** C4 spells this `source_field` on the wire; the client speaks camelCase. */
  sourceField: string;
  enabled: boolean;
}

export interface ConnectorDatabaseExclusion {
  sourceField: string;
  reason: string;
}

export interface ScraperRecipe {
  kind: string;
  source: string;
  seed: string | { search: string; geography: string };
  limits: { posts?: number; postType?: string; records?: number };
  schedule: { mode: string };
}

export interface ScraperRunReceipt {
  id: string;
  state: string;
  provider: string;
  rows: number;
  startedAt: string;
  finishedAt: string;
  estimatedUsd: number;
  costCapUsd: number;
  note: string;
}

export interface ConnectorDatabase {
  key: string;
  identity?: { provider: string; connectionId: string; databaseKey: string; model: string };
  /**
   * What this database is CALLED today: the tenant's override when there is one, our shipped
   * default otherwise. Resolved on the server (`core/schema_overlay.database_label`), never here.
   */
  label: string;
  /**
   * ⭐⭐ W53-T27 Β· R9 / C2 β€” THREE NAMES, THREE DIFFERENT FACTS, AND THE TAB SHOWS ALL THREE.
   *
   * `native` is the VENDOR's own identifier for the table (`res.partner`, or an Amazon report
   * type). It is never editable by anybody: it is how the source names its own thing, and a
   * workspace that could rewrite it would be describing a table that does not exist over there.
   */
  native: string;
  /** OUR shipped default name (C2's `label`). It survives an override rather than being replaced,
   *  which is what lets the tab offer a way back to it. */
  defaultLabel: string;
  /** This tenant's own name, or `""` when none is set. Absent means inherit the default, and it
   *  is the SAME override the navigation rail's rename writes (R9), not a second one. */
  override: string;
  /** May THIS reader rename it? The server's own `may_open` answer, per row, because a control
   *  the write door would refuse is a button that always fails. */
  canRename: boolean;
  /** Does the governed database exist yet? This is separate from the reader's permission. */
  exists: boolean;
  enabled: boolean;
  /** Exact rows in the Odoo source model, or null until that model was counted successfully. */
  sourceRows: number | null;
  /** Tri-state on purpose: a model nobody counted is unknown, never empty. */
  populated: boolean | null;
  fields: ConnectorDatabaseField[];
  excluded: ConnectorDatabaseExclusion[];
  /**
   * S66-T39 / D-723: true on a `fields=summary` page. The empty `fields` and `excluded` then mean
   * NOT READ YET, never "this database has no fields"; the Databases tab reads them on expansion
   * from `GET /connectors/{key}/databases/{database_key}/fields`.
   */
  fieldsDeferred?: boolean;
  /** The row's raw `syncHealth`, parsed by the Databases tab (`parseDatabaseSyncHealth`). */
  syncHealth?: unknown;
  /** Provider sync facts retain the connection's C1 history notice. */
  sync?: unknown;
  /**
   * ⭐⭐ W49-T14 β€” THE OTHER DATABASES READING THE SAME SOURCE MODEL, by key.
   *
   * β›” MEASURED, AND THE DATABASES TAB WOULD LIE WITHOUT IT: `ut_odoo_invoices` and
   * `ut_odoo_bills` are both `account.move`; `ut_odoo_agents` and `ut_odoo_vendors` are both
   * `res.partner`. The enablement flag is keyed `"<model>.<rawName>"`, so one field switch flips
   * the field under both names, and a screen that printed the same rows twice in silence would be
   * offering a per-database control that is not per-database.
   */
  sharesFieldsWith: string[];
  /** Present only on databases created by the Scraper connector. Credentials never ride here. */
  scraperRecipe?: ScraperRecipe;
  scraperRuns?: ScraperRunReceipt[];
  runPath?: string;
  canRun?: boolean;
}

/**
 * ⭐ W49-T14 Β· R24 β€” MAY THE DATABASES TAB DISCLOSE ANYTHING, AND TO THIS READER?
 *
 * β›” AN ADDITION TO C4, DECLARED, exactly as `keychain.connect` is. Without it an empty
 * `databases` list means "this connector has no schema" and "this connector's schema could not be
 * read" at the same time, and the tab has to pick one. The server knows which; it says so.
 */
export interface ConnectorIntrospection {
  introspectable: boolean;
  /** Why not, in a sentence the tab prints. Empty when it is. */
  reason: string;
  fieldsVisible: boolean;
  canToggleFields: boolean;
  canToggleTables: boolean;
  catalogueComplete: boolean;
  capturedAt: string;
  censusAt: string;
  censusComplete: boolean;
  censusDurationMs: number;
  censusModelsCounted: number;
  censusModelsWithRows: number;
  /** What an EMPTY `excluded` list actually means, composed where the diff is computed. */
  excludedBasis: string;
}

/** W55-T19 / R7 β€” one provider's own database-enablement door. */
export interface ConnectorEnablement {
  /** Must match the connector detail envelope that carried it. */
  provider: string;
  /** Read as a string so a future provider mode fails closed instead of widening this UI. */
  mode: string;
  canManage: boolean;
  updatePath: string;
  /** The Amazon route changes only config; stored database rows remain in place. */
  preservesData: boolean;
  available: boolean;
}

/** S66-T39 / D-723: the server's `databasesPage`; `next` is null on the last page. */
export interface ConnectorDatabasesPage {
  offset: number;
  limit: number;
  returned?: number;
  total: number;
  hasMore?: boolean;
  next: number | null;
}

export interface ConnectorDetail {
  overview: ConnectorOverview;
  keychain: ConnectorKeychainHalf;
  /** Every database read SO FAR. On a paged read `databasesPage.total` is the true count. */
  databases: ConnectorDatabase[];
  /** C1 is parsed by the Amazon consumer, including every report detail. */
  firstLoad?: unknown;
  /** Summary pages from the preceding release use this connection-level name. */
  amazonFirstLoad?: unknown;
  /** Present only on a paged read. Absent means `databases` is the whole list. */
  databasesPage?: ConnectorDatabasesPage | null;
  /** The graph's own read, `GET /api/v1` + this path, when a summary read deferred it. */
  relationshipsPath?: string;
  /** True when `relationships` is a placeholder the summary read did not fill. */
  relationshipsDeferred?: boolean;
  enablement: ConnectorEnablement | null;
  materialization?: MaterializationCapability | null;
  /** Present only when the server says this administrator can request a provider sync. */
  syncNow?: { provider: string; path: string } | null;
  introspection: ConnectorIntrospection;
  relationships: ConnectorRelationshipGraph;
}

const str = (v: unknown): string => (typeof v === "string" ? v : "");
const obj = (v: unknown): Record<string, unknown> =>
  v && typeof v === "object" ? (v as Record<string, unknown>) : {};

function parseStrings(raw: unknown): string[] {
  if (!Array.isArray(raw)) return [];
  return raw.map((item) => str(item).trim()).filter((item) => item.length > 0);
}

function parseKeychainHalf(raw: unknown): ConnectorKeychainHalf {
  const source = obj(raw);
  const entries: ConnectorKeychainEntry[] = [];
  for (const item of Array.isArray(source.entries) ? source.entries : []) {
    const entry = obj(item);
    const id = str(entry.id).trim();
    // A credential row with no id has nothing a later tab could act on, so it is dropped
    // rather than rendered as a row that refuses every control.
    if (!id) continue;
    entries.push({
      id,
      connectionId: str(entry.connectionId).trim() || id,
      type: str(entry.type).trim(),
      slot: typeof entry.slot === "number" ? entry.slot : undefined,
      status: str(entry.status).trim(),
      label: str(entry.label).trim() || id,
      masked: str(entry.masked),
      scope: str(entry.scope).trim(),
      testable: entry.testable === true,
      replaceable: entry.replaceable === true,
      client_secret_rotation_deadline: str(entry.client_secret_rotation_deadline).trim(),
    });
  }
  return {
    entries,
    canConnect: source.canConnect === true,
    canDisconnect: source.canDisconnect === true,
    migrationPending: source.migrationPending === true,
    connect: parseConnectSpec(source.connect),
  };
}

/**
 * The Connect descriptor, or `null`.
 *
 * β›” A SPEC WITH NO FIELDS IS `null`, NOT AN EMPTY FORM. A form that asks for nothing and then
 * POSTs an empty `fields` object is refused by `keychain.add_entry` ("fields must be a non-empty
 * object"), so it would be a Connect button that always fails β€” R7's banned shape, arrived at by
 * degrading gracefully instead of honestly.
 */
export function parseConnectSpec(raw: unknown): ConnectorConnectSpec | null {
  const source = obj(raw);
  const type = str(source.type).trim();
  if (!type) return null;
  const fields: ConnectorConnectField[] = [];
  for (const item of Array.isArray(source.fields) ? source.fields : []) {
    const field = obj(item);
    const key = str(field.key).trim();
    if (!key) continue;
    const parsed: ConnectorConnectField = { key, label: str(field.label).trim() || key, secret: field.secret === true };
    if (typeof field.default === "string" && field.default.trim()) parsed.default = field.default;
    fields.push(parsed);
  }
  if (!fields.length) return null;
  const scopes = parseStrings(source.scopes);
  return {
    type,
    fields,
    // An empty list would render a picker with no options; `business` is what every connection
    // stored before this wave actually is, which is the same read default the scope bucket uses.
    scopes: scopes.length ? scopes : ["business"],
    tenantWide: source.tenantWide === true,
    defaultLabel: str(source.defaultLabel).trim() || undefined,
  };
}

/**
 * One database's field list. Shared by the detail read and the per-database fields read
 * (S66-T39), so a deferred row loaded on expansion is parsed by the same rule as a full one.
 */
export function parseDatabaseFields(raw: unknown): ConnectorDatabaseField[] {
  const fields: ConnectorDatabaseField[] = [];
  for (const rawField of Array.isArray(raw) ? raw : []) {
    const field = obj(rawField);
    const fieldKey = str(field.key).trim();
    if (!fieldKey) continue;
    fields.push({
      key: fieldKey,
      label: str(field.label).trim() || fieldKey,
      type: str(field.type).trim(),
      sourceField: str(field.source_field).trim(),
      enabled: field.enabled === true,
    });
  }
  return fields;
}

/** One database's exclusions, shared the same way as `parseDatabaseFields`. */
export function parseDatabaseExclusions(raw: unknown): ConnectorDatabaseExclusion[] {
  const excluded: ConnectorDatabaseExclusion[] = [];
  for (const rawItem of Array.isArray(raw) ? raw : []) {
    const item2 = obj(rawItem);
    const reason = str(item2.reason).trim();
    if (!reason) continue;
    excluded.push({ sourceField: str(item2.source_field).trim(), reason });
  }
  return excluded;
}

function parseDatabases(raw: unknown): ConnectorDatabase[] {
  if (!Array.isArray(raw)) return [];
  const out: ConnectorDatabase[] = [];
  for (const item of raw) {
    const row = obj(item);
    const key = str(row.key).trim();
    // ⭐ W53-T27 β€” THE DEFAULT AND THE EFFECTIVE NAME EACH FALL BACK TO THE OTHER, and neither
    // falls back to the KEY. A payload from a server that predates this ticket carries `label`
    // alone, and the tab must then show that name in both columns rather than an empty cell or an
    // internal identifier.
    const defaultLabel = str(row.defaultLabel).trim() || str(row.label).trim();
    const label = str(row.label).trim() || defaultLabel;
    // Same rule as `parseDirectory`: a database with no name is never rendered from its key,
    // which would put an internal identifier on screen.
    if (!key || !label) continue;
    const fields = parseDatabaseFields(row.fields);
    const excluded = parseDatabaseExclusions(row.excluded);
    const recipeRaw = obj(row.scraperRecipe);
    const recipeSeed = recipeRaw.seed;
    const recipeLimits = obj(recipeRaw.limits);
    const recipeSchedule = obj(recipeRaw.schedule);
    const recipe: ScraperRecipe | undefined = str(recipeRaw.kind).trim() &&
      str(recipeRaw.source).trim() && str(recipeSchedule.mode).trim() &&
      (typeof recipeSeed === "string" ||
        (str(obj(recipeSeed).search).trim() && str(obj(recipeSeed).geography).trim()))
      ? {
          kind: str(recipeRaw.kind).trim(), source: str(recipeRaw.source).trim(),
          seed: typeof recipeSeed === "string" ? recipeSeed : {
            search: str(obj(recipeSeed).search).trim(),
            geography: str(obj(recipeSeed).geography).trim(),
          },
          limits: {
            ...(typeof recipeLimits.posts === "number" ? { posts: recipeLimits.posts } : {}),
            ...(str(recipeLimits.postType).trim() ? { postType: str(recipeLimits.postType).trim() } : {}),
            ...(typeof recipeLimits.records === "number" ? { records: recipeLimits.records } : {}),
          },
          schedule: { mode: str(recipeSchedule.mode).trim() },
        } : undefined;
    const scraperRuns: ScraperRunReceipt[] = [];
    for (const rawRun of Array.isArray(row.scraperRuns) ? row.scraperRuns : []) {
      const run = obj(rawRun);
      const id = str(run.id).trim();
      if (!id) continue;
      scraperRuns.push({
        id, state: str(run.state).trim(), provider: str(run.provider).trim(),
        rows: typeof run.rows === "number" && Number.isFinite(run.rows) ? Math.max(0, Math.trunc(run.rows)) : 0,
        startedAt: str(run.startedAt).trim(), finishedAt: str(run.finishedAt).trim(),
        estimatedUsd: typeof run.estimatedUsd === "number" ? run.estimatedUsd : 0,
        costCapUsd: typeof run.costCapUsd === "number" ? run.costCapUsd : 0,
        note: str(run.note).trim(),
      });
    }
    out.push({
      key,
      label,
      identity: str(obj(row.identity).databaseKey) === key ? {
        provider: str(obj(row.identity).provider), connectionId: str(obj(row.identity).connectionId),
        databaseKey: key, model: str(obj(row.identity).model),
      } : undefined,
      // β›” `native` IS NOT DEFAULTED TO ANYTHING. An absent one means the server could not name
      // the source's own identifier for this table, and the tab says so; inventing the key or the
      // label here would put OUR word on screen under the vendor's heading.
      native: str(row.native).trim(),
      defaultLabel,
      override: str(row.override).trim(),
      canRename: row.canRename === true,
      exists: row.exists === true,
      enabled: row.enabled === true,
      sourceRows:
        typeof row.sourceRows === "number" && Number.isFinite(row.sourceRows) && row.sourceRows >= 0
          ? Math.trunc(row.sourceRows)
          : null,
      populated: row.populated === true ? true : row.populated === false ? false : null,
      fields,
      excluded,
      ...(row.fieldsDeferred === true ? { fieldsDeferred: true } : {}),
      ...(row.syncHealth !== undefined ? { syncHealth: row.syncHealth } : {}),
      ...(row.sync !== undefined ? { sync: row.sync } : {}),
      sharesFieldsWith: parseStrings(row.sharesFieldsWith),
      ...(recipe ? { scraperRecipe: recipe } : {}),
      ...(recipe ? { scraperRuns } : {}),
      ...(str(row.runPath).startsWith("/connectors/scraper/databases/") && str(row.runPath).endsWith("/run")
        ? { runPath: str(row.runPath), canRun: row.canRun === true } : {}),
    });
  }
  return out;
}

/**
 * R24's answer, read defensively.
 *
 * β›” THE DEFAULT IS "NOT INTROSPECTABLE", NOT "INTROSPECTABLE WITH NOTHING IN IT". A payload
 * missing this half is a server that predates it, and the fail-closed direction shows the card's
 * own content rather than a disclosure screen with empty lists and live toggles on it.
 */
function parseIntrospection(raw: unknown): ConnectorIntrospection {
  const source = obj(raw);
  return {
    introspectable: source.introspectable === true,
    reason: str(source.reason).trim(),
    fieldsVisible: source.fieldsVisible === true,
    canToggleFields: source.canToggleFields === true,
    canToggleTables: source.canToggleTables === true,
    catalogueComplete: source.catalogueComplete === true,
    capturedAt: str(source.capturedAt).trim(),
    censusAt: str(source.censusAt).trim(),
    censusComplete: source.censusComplete === true,
    censusDurationMs:
      typeof source.censusDurationMs === "number" && Number.isFinite(source.censusDurationMs)
        ? Math.max(0, Math.trunc(source.censusDurationMs))
        : 0,
    censusModelsCounted:
      typeof source.censusModelsCounted === "number" && Number.isFinite(source.censusModelsCounted)
        ? Math.max(0, Math.trunc(source.censusModelsCounted))
        : 0,
    censusModelsWithRows:
      typeof source.censusModelsWithRows === "number" &&
      Number.isFinite(source.censusModelsWithRows)
        ? Math.max(0, Math.trunc(source.censusModelsWithRows))
        : 0,
    excludedBasis: str(source.excludedBasis).trim(),
  };
}

/**
 * Parse a provider capability bound to the selected connector, or refuse it.
 *
 * A path is actionable only when it stays under this provider and carries the one database-key
 * slot the server declared. Missing, cross-provider and unknown modes render no control; the API
 * remains the permission boundary, but the modal never paints a button it knows cannot work.
 */
export function parseConnectorEnablement(
  raw: unknown,
  selectedKey: string
): ConnectorEnablement | null {
  const source = obj(raw);
  const provider = str(source.provider).trim();
  const mode = str(source.mode).trim();
  if (provider !== selectedKey || mode !== "database" || source.preservesData !== true) return null;
  const updatePath = str(source.updatePath).trim();
  const expectedPrefix = `/connectors/${encodeURIComponent(provider)}/databases/`;
  const validPath = updatePath.startsWith(expectedPrefix) && updatePath.endsWith("/enablement")
    && updatePath.includes("{databaseKey}");
  const canManage = source.canManage === true && source.available === true && validPath;
  return {
    provider,
    mode,
    canManage,
    updatePath: canManage ? updatePath : "",
    preservesData: true,
    available: source.available === true,
  };
}

/**
 * Read the detail payload for the card that was actually clicked.
 *
 * β›” THE SELECTED KEY IS A SECOND GUARD, exactly as it is for the relationship graph: a stale
 * response that arrives after the reader opened a different connector is REFUSED rather than
 * painted under the new title. `parseRelationshipGraph` already applies that rule to its own
 * half; this applies it to the envelope.
 */
/**
 * S66-T39 / D-723: the server's page cursor, or `null`.
 *
 * β›” A CURSOR THAT DOES NOT MOVE FORWARD IS REFUSED, because the modal follows `next` in a loop
 * and a `next` at or behind `offset` would read the same page forever.
 */
export function parseDatabasesPage(raw: unknown): ConnectorDatabasesPage | null {
  const page = obj(raw);
  const whole = (v: unknown): v is number => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
  if (!whole(page.offset) || !whole(page.limit) || page.limit < 1 || !whole(page.total)) return null;
  if (page.next !== null && !(whole(page.next) && page.next > page.offset)) return null;
  const returned = Math.min(page.limit, Math.max(0, page.total - page.offset));
  const hasMore = page.offset + returned < page.total;
  if (page.returned !== undefined && (!whole(page.returned) || page.returned !== returned)) return null;
  if (page.hasMore !== undefined && (typeof page.hasMore !== "boolean" || page.hasMore !== hasMore)) return null;
  if ((page.returned !== undefined || page.hasMore !== undefined)
      && page.next !== (hasMore ? page.offset + page.limit : null)) return null;
  return { offset: page.offset, limit: page.limit, total: page.total, next: page.next,
    ...(whole(page.returned) ? { returned: page.returned } : {}),
    ...(typeof page.hasMore === "boolean" ? { hasMore: page.hasMore } : {}) };
}

export function parseConnectorDetail(body: unknown, selectedKey: string): ConnectorDetail | null {
  const source = obj(body);
  const overview = obj(source.overview);
  const key = str(overview.key).trim();
  if (!key || key !== selectedKey) return null;
  // Same bound-to-the-selected-key rule as `syncNow` below: a path naming another connector is
  // not followed.
  const relationshipsPath = str(source.relationshipsPath) ===
    `/connectors/${encodeURIComponent(selectedKey)}/relationships`
    ? str(source.relationshipsPath) : "";
  return {
    ...("databasesPage" in source ? { databasesPage: parseDatabasesPage(source.databasesPage) } : {}),
    ...(relationshipsPath ? {
      relationshipsPath,
      relationshipsDeferred: source.relationships === null || source.relationships === undefined,
    } : {}),
    overview: {
      key,
      label: str(overview.label).trim(),
      status: str(overview.status).trim(),
      account: str(overview.account).trim(),
      source: str(overview.source).trim(),
      creates: parseStrings(overview.creates),
      syncHealth: overview.syncHealth,
    },
    keychain: parseKeychainHalf(source.keychain),
    databases: parseDatabases(source.databases),
    ...(source.firstLoad !== undefined ? { firstLoad: source.firstLoad } : {}),
    ...(source.amazonFirstLoad !== undefined ? { amazonFirstLoad: source.amazonFirstLoad } : {}),
    enablement: parseConnectorEnablement(source.enablement, selectedKey),
    syncNow: obj(source.syncNow).provider === selectedKey &&
      str(obj(source.syncNow).path) === `/connectors/${selectedKey}/sync/now`
      ? { provider: selectedKey, path: `/connectors/${selectedKey}/sync/now` } : null,
    materialization: obj(source.materialization).provider === selectedKey &&
      str(obj(source.materialization).statusPath) === `/connectors/${selectedKey}/jobs` &&
      str(obj(source.materialization).retryPath) === `/connectors/${selectedKey}/sync/retry`
      ? { provider: selectedKey, statusPath: `/connectors/${selectedKey}/jobs`,
          retryPath: `/connectors/${selectedKey}/sync/retry` } : null,
    introspection: parseIntrospection(source.introspection),
    relationships: parseRelationshipGraph(source.relationships, selectedKey),
  };
}

/** R22: access is a status from the detail payload, including connections without keychain rows. */
export function accessSentence(
  keychain: ConnectorKeychainHalf, status: string, connectorKey?: string,
): string {
  if (status === "connected") return "Connected";
  if (status === "reconnect") return connectorKey === "amazon_sp" ? "Needs a test" : "Reconnect";
  if (status === "expired") return "Expired";
  return keychain.entries.length ? "Stored" : "Not connected";
}

/** The brand mark, or the two-letter fallback tile the directory already uses (wave 30, R4). */
export function ConnectorMark({ connectorKey, label }: { connectorKey: string; label: string }) {
  const mark = brandForConnector(connectorKey, 20);
  return (
    <span className="conn-modal-mark" aria-hidden="true">
      {mark ?? <span className="shell-db-chip conn-tile">{tileText(label)}</span>}
    </span>
  );
}

/** Amazon Settings accepts the SP-API connector and the legacy review connector keys. */
export function isAmazonConnector(key: string): boolean {
  const k = String(key || "").toLowerCase();
  return k === "md_amazon" || k === "amazon" || k === "amazon_sp";
}

export function ConnectorOverviewPanel({
  detail,
  row,
  syncCapability,
  syncProblem = "",
  syncReady = true,
  onSyncReady,
  hidden = false,
  onPullReviews,
  isAdmin = false,
  deletionRefreshKey,
  onSyncNow,
  syncBusy = false,
  syncReceipt,
  syncError = "",
}: {
  detail: ConnectorDetail | null;
  row?: ConnectorRow;
  syncCapability?: ConnectorSyncCapability | null;
  syncProblem?: string;
  syncReady?: boolean;
  onSyncReady?: (connectorKey: string, refreshKey: number) => void;
  hidden?: boolean;
  /**
   * ⭐ OPTIONAL, AND THE FILE'S OWN HEADER SAYS WHY. The static proof sheets render this panel
   * with `renderToStaticMarkup` and pass no handlers; a required prop would red `tsc` on files
   * this ticket does not own β€” the same lesson `onOpen` paid for one ticket earlier.
   *
   * β›” ABSENT MEANS NO CONTROL, NOT A DISABLED ONE. This directory's rule is that a reader who
   * may not do a thing sees no door for it rather than one that would 403.
   */
  onPullReviews?: () => void;
  onOpenDatabases?: () => void;
  isAdmin?: boolean;
  deletionRefreshKey?: number;
  onSyncNow?: () => void;
  syncBusy?: boolean;
  syncReceipt?: SyncNowReceipt | null;
  syncError?: string;
}) {
  const overview = detail?.overview;
  const connectorKey = row?.key ?? overview?.key ?? "";
  const health = parseDatabaseSyncHealth(overview?.syncHealth);
  const state = syncReceipt?.state === "queued" ? "queued"
    : syncReceipt?.state === "running" || syncBusy ? "running"
    : syncReceipt?.state === "failed" ? "failed" : health?.state;
  // A partial sync landed most tables. Only a failed one reads as failed, and it names its cause.
  const failed = state === "failed";
  const partial = state === "partial";
  const notOffered = health?.notOffered ?? 0;
  const status = failed ? "Sync failed" : partial ? "Partly synced" : state === "running" ? "Syncing"
    : state === "queued" ? "Queued"
    : state === "succeeded" && notOffered > 0
      ? `Synced with ${notOffered.toLocaleString()} ${notOffered === 1 ? "report" : "reports"} not offered`
    : detail ? accessSentence(detail.keychain, detail.overview.status, connectorKey) : "";
  const showSync = syncCapability?.supported || (!syncCapability && (row?.spawns_tables || syncProblem));
  return (
    <div className="conn-settings-overview" hidden={hidden}>
      <header className="conn-settings-header" aria-label="Connection status">
        {showSync ? <div className="conn-settings-sync-row">
          {syncCapability?.supported
            ? <ConnectorOverviewSyncStatus key={JSON.stringify([connectorKey, deletionRefreshKey ?? 0])}
              connectorKey={connectorKey} refreshKey={deletionRefreshKey ?? 0} onReady={onSyncReady} />
            : <p className="conn-settings-last-success" role="status">{syncProblem || "Loading sync status…"}</p>}
          {isAdmin && onSyncNow ? (
            <button type="button" className="conn-settings-sync set-primary" disabled={syncBusy} aria-busy={syncBusy} onClick={onSyncNow}>
              Sync now
            </button>
          ) : null}
          {syncReady && !hidden && connectorKey === "odoo" && isAdmin ? <OdooSyncEvery /> : null}
        </div> : null}
        {overview ? <div className="conn-settings-account">
          <span className="conn-settings-label">Account</span>
          <span className="conn-settings-account-name">{overview.account || "No account recorded"}</span>
          <div className="conn-settings-health">
            <span className="conn-settings-status" data-sync-state={state || overview.status}
              data-tone={failed ? "error" : state === "running" || state === "queued" ? "active" : "neutral"}
              role="status">{status}</span>
            {health?.warning ? <span className="conn-settings-warning" role="note">{health.warning}</span>
              : (failed || partial) && health?.error ? <span className="conn-settings-warning" role="note">{health.error.message}</span>
              : null}
          </div>
        </div> : null}
      </header>
      {!hidden && connectorKey === "amazon_sp" ? <AmazonSyncOverview refreshKey={deletionRefreshKey} /> : null}
      {!hidden && isAmazonConnector(connectorKey) ? <AmazonWritesSwitch /> : null}
      {syncError ? <p className="conn-settings-error" role="alert">{syncError}</p> : null}
      {syncReady && !hidden && overview?.key === "amazon_sp" && isAdmin ? (
        <AmazonDeletionNotice isAdmin={isAdmin} refreshKey={deletionRefreshKey} />
      ) : null}
      {onPullReviews ? (
        <div className="conn-modal-act">
          <button type="button" className="conn-modal-go" onClick={onPullReviews}>
            Pull reviews
          </button>
        </div>
      ) : null}
    </div>
  );
}

/** Compatibility export for fixtures. Database rows own the enablement controls. */
export function ProviderEnablementPanel(_props: {
  detail: ConnectorDetail;
  onChanged: () => void;
}) {
  return null;
}

// ── The three tabs that are not built yet. β›” EACH IS ITS OWN COMPONENT SLOT so W49-T13, T14 and
// T15 replace a named component rather than editing a sentence out of a branch, and the switch
// below never has to change shape. Plain sentences, no dashes, no emojis.

/* β›”β›” `KeychainTabPlaceholder` STOOD HERE AND IS REPLACED BY W49-T13. The real tab is
   `connectors/KeychainTab.tsx`, mounted below from the loaded detail payload rather than from a
   branch that answers before the fetch β€” which is the one structural change this ticket makes to
   `renderTab`: the keychain half is DATA, so its tab cannot render before the read lands. */

/* β›”β›” `DatabasesTabPlaceholder` STOOD HERE AND IS REPLACED BY W49-T14. The real tab is
   `connectors/DatabasesTab.tsx`, mounted below from the loaded detail payload rather than from a
   branch that answers before the fetch. That is the same structural move the keychain and
   relationship tabs each made, for the third time and for the same reason: the database list, its
   field catalogue and R24's introspectable flag are all DATA on this read, so a tab rendering
   above the load guard could only ever paint an empty disclosure and, worse, would read
   `introspectable: false` on every connector for as long as the fetch was in flight. */

/**
 * `paging` is present only while later database pages are still being read ("loading") or when
 * one of them failed ("failed"); the Databases tab says which instead of implying a short list.
 */
type Load =
  | { phase: "loading" }
  | { phase: "ready"; detail: ConnectorDetail; paging?: "loading" | "failed" }
  | { phase: "error"; message: string };

const CONNECTOR_DETAIL_FRESHNESS_MS = 60_000;
const SIGNED_OUT_EVENT = "aios:signed-out";
// Measured reads take 1.34 s cold and 0.01 s warm, with a boot contended read above 8 s. Twenty seconds caps the wait a person sees.
// This is deliberately shorter than the server's thirty seconds so this component shows its own readable sentence before a bare 504.
const CONNECTOR_DETAIL_DEADLINE_MS = 20_000;
// Closing the modal unmounts it; keep the last successful read for the next open.
const connectorDetailCache = new Map<string, { detail: ConnectorDetail; at: number }>();

// S67-T31: a refused read shows the server's own plain cause, or this component's sentence when
// the server sent none (a bare 500 has no JSON body). A status code never reaches the screen:
// "The server answered 500." was the owner's whole report, and it told him nothing he could act on.
function plainReadFailure(
  body: { error?: { message?: string }; detail?: { error?: { message?: string } } } | null,
  fallback: string,
): string {
  const said = (body?.error?.message || body?.detail?.error?.message || "").trim();
  return said || fallback;
}

// Shell.tsx::signOut emits SIGNED_OUT_EVENT; an unloaded module has no cache to clear.
export function clearConnectorDetailCache(): void {
  connectorDetailCache.clear();
}

// ⭐ S66-T39 / D-723 β€” THE DETAIL IS READ IN PAGES. An unpaged read carried every database with
// every field and the whole relationship graph, which is what made the first open slow and
// heavy after a fresh boot. A summary page carries 50 databases with their fields deferred; the
// rest are read by following `databasesPage.next` until it is null, so every database stays
// reachable. `overview.creates` is already the unsliced list on every page.
// β›” Nothing below may be exported: verify_wiring's S66-T28 runner executes this block as-is.
const CONNECTOR_DETAIL_PAGE_SIZE = 50;

function connectorDetailPageUrl(connectorKey: string, offset: number, revalidate: boolean): string {
  return `${API_V1}/connectors/${encodeURIComponent(connectorKey)}/detail` +
    `?databases_offset=${offset}&databases_limit=${CONNECTOR_DETAIL_PAGE_SIZE}&fields=summary` +
    (revalidate ? "&revalidate=1" : "");
}

// A later page contributes its databases and its cursor. Every other half is the first page's,
// so the overview, keychain and capabilities a reader already sees do not flicker mid-read.
function appendDetailPage(current: ConnectorDetail, page: ConnectorDetail): ConnectorDetail {
  const seen = new Set(current.databases.map((database) => database.key));
  return {
    ...current,
    databases: [...current.databases, ...page.databases.filter((database) => !seen.has(database.key))],
    databasesPage: page.databasesPage,
  };
}

if (typeof window !== "undefined") {
  window.addEventListener(UNAUTHORIZED_EVENT, clearConnectorDetailCache);
  window.addEventListener(SIGNED_OUT_EVENT, clearConnectorDetailCache);
}

type PendingLeave = { kind: "close" } | { kind: "tab"; tab: ConnectorTab } | null;

/**
 * THE MODAL. Centered, portalled to <body>, focus-trapped, dismissed by Escape or a click
 * outside, and it hands focus back to the control that opened it.
 */
export default function ConnectorModal({
  row,
  onClose,
  initialTab = "overview",
  isAdmin = false,
}: {
  row: ConnectorRow;
  onClose: () => void;
  /** Credential links land on Setup, including the retired tab aliases. */
  initialTab?: ConnectorTab;
  /** Retained for callers that still pass the retired Databases-tab callback. */
  onOpenDatabases?: () => void;
  isAdmin?: boolean;
}) {
  const connectorKey = row.key;
  const panelRef = useRef<HTMLDivElement>(null);
  const closeRef = useRef<HTMLButtonElement>(null);
  const [tab, setTab] = useState<"overview" | "setup">(() => connectorTab(initialTab));
  const [loadKey, setLoadKey] = useState(connectorKey);
  const [reading, setLoad] = useState<Load>(() => {
    const cached = connectorDetailCache.get(connectorKey);
    return cached ? { phase: "ready", detail: cached.detail } : { phase: "loading" };
  });
  const load: Load = loadKey === connectorKey ? reading : { phase: "loading" };
  const databasesRef = useRef<DatabasesTabHandle>(null);
  const [databasePendingCount, setDatabasePendingCount] = useState(0);
  const [databaseTabBusy, setDatabaseTabBusy] = useState(false);
  const [databaseSaving, setDatabaseSaving] = useState(false);
  const [setupNotice, setSetupNotice] = useState<{ key: string; message: string } | null>(null);
  const syncWasActive = useRef(false);
  const [pendingLeave, setPendingLeave] = useState<PendingLeave>(null);
  /**
   * ⭐ W49-T13 β€” THE RE-READ, AND IT IS NOT OPTIONAL POLISH. The Keychain tab WRITES: it stores,
   * tests, deletes and disconnects. Keying the fetch on `connectorKey` alone leaves a deleted key
   * on screen until the modal is closed and reopened, which reads as a delete that did not land β€”
   * so the effect below keys on this counter as well and every write bumps it.
   */
  const [reads, setReads] = useState(0);
  const syncSource = useConnectorSyncCapability(connectorKey, reads, row);
  const [syncReady, setSyncReady] = useState<{ connectorKey: string; refreshKey: number } | null>(null);
  const markSyncReady = useCallback((key: string, refreshKey: number) => {
    setSyncReady((current) => current?.connectorKey === key && current.refreshKey === refreshKey
      ? current : { connectorKey: key, refreshKey });
  }, []);
  const detailReadsReady = Boolean(syncSource.problem || (syncSource.capability &&
    (!syncSource.capability.supported || (syncReady?.connectorKey === connectorKey && syncReady.refreshKey === reads))));
  const syncCapability = isAdmin && detailReadsReady ? syncSource.capability?.syncNow : null;
  const syncNow = useSyncNow(syncCapability);
  const [databaseReveal, setDatabaseReveal] = useState<DatabaseReveal | null>(null);
  const reread = useCallback((reveal?: DatabaseReveal) => {
    // Evict immediately so closing just after a write cannot reuse the previous read.
    connectorDetailCache.delete(connectorKey);
    if (reveal) setDatabaseReveal(reveal);
    setReads((n) => n + 1);
  }, [connectorKey]);
  useEffect(() => {
    if (syncNow.busy) syncWasActive.current = true;
    else if (syncWasActive.current && syncNow.receipt && ["done", "failed"].includes(syncNow.receipt.state)) {
      syncWasActive.current = false;
      reread();
    }
  }, [reread, syncNow.busy, syncNow.receipt]);
  /**
   * ⭐⭐ W49-T19 Β· R31 β€” THE AMAZON REVIEWS PULL, OPENED FROM THE OVERVIEW TAB.
   * A second overlay above this one, which is why it takes the PORTAL step and this modal keeps
   * the DIALOG step ([[z-layering-is-a-three-way-order]]).
   */
  const [pulling, setPulling] = useState(false);
  /**
   * β›”β›” THE PULL AND CONFIRM DIALOGS' OWN SURFACES, HELD IN STATE RATHER THAN REFS, because
   * `useOverlayLayer` reads `outsideElements` on every RENDER and a ref that fills in after mount
   * would never reach it. See the dismissal note on the layer below.
   */
  const [pullSurface, setPullSurface] = useState<HTMLElement | null>(null);
  const [tabConfirmSurface, setTabConfirmSurface] = useState<HTMLElement | null>(null);
  const [leaveSurface, setLeaveSurface] = useState<HTMLElement | null>(null);
  const canPull = isAmazonConnector(row.key) && row.key.toLowerCase() !== "amazon_sp";

  const unsavedMessage = databasePendingCount === 1
    ? "You have 1 unsaved change to this connection."
    : `You have ${databasePendingCount} unsaved changes to this connection.`;

  const requestClose = useCallback(() => {
    if (databaseSaving || databaseTabBusy) return;
    if (databasePendingCount) {
      setPendingLeave({ kind: "close" });
      return;
    }
    onClose();
  }, [databasePendingCount, databaseSaving, databaseTabBusy, onClose]);

  const requestTab = useCallback((next: ConnectorTab) => {
    if (databaseSaving || databaseTabBusy) return;
    if (next === tab) return;
    if (databasePendingCount) {
      setPendingLeave({ kind: "tab", tab: next });
      return;
    }
    setTab(connectorTab(next));
  }, [databasePendingCount, databaseSaving, databaseTabBusy, tab]);

  useEffect(() => {
    if (!databasePendingCount) return;
    const warn = (event: BeforeUnloadEvent) => {
      event.preventDefault();
      event.returnValue = unsavedMessage;
    };
    window.addEventListener("beforeunload", warn);
    return () => window.removeEventListener("beforeunload", warn);
  }, [databasePendingCount, unsavedMessage]);

  useOverlayLayer({
    panelRef,
    /**
     * β›”β›” DISMISS THE TOP LAYER, NOT BOTH OF THEM, AND THE HOOK CANNOT DO THIS FOR US HERE.
     *
     * `useOverlayLayer` guards its handlers with `stack.isTop(id)` and that guard is INERT in this
     * app: `OverlaySurface.tsx` exports `OverlayProvider` and nothing mounts it, so the context is
     * null and every layer believes it is the top one. Both layers listen for pointers on `document` in
     * the CAPTURE phase, where `stopPropagation` does not stop a sibling listener on the same
     * node. So a pointer press can dismiss the dialog AND this modal underneath it.
     * Answering here keeps the fix in this ticket's own files: while either confirm is open,
     * this layer refuses dismissal; while the pull dialog is open, it closes THAT and stops.
     * Escape already belongs to the topmost entry in `useEscapeClose`'s shared stack.
     */
    onDismiss: () => {
      if (pendingLeave || tabConfirmSurface) return;
      if (pulling) {
        setPulling(false);
        return;
      }
      requestClose();
    },
    // D-724 (S66-T34 remainder): a stray press outside the panel no longer closes it, so a
    // staged change or a half-read tab is not lost to a missed click (DESIGN.md section 4).
    // Escape and the close button remain the ways out.
    dismissOnOutside: false,
    /**
     * β›” AND THE POINTER HALF OF THE SAME PROBLEM. These dialogs portal as SIBLINGS of this
     * panel, so a press inside one is literally outside `panelRef` and would dismiss this modal
     * out from under a paid pull or a staged change. `outsideElements` is the hook's own answer.
     * Each surface includes its scrim, so a stray press there cannot dismiss this modal either.
     */
    outsideElements: [pullSurface, tabConfirmSurface, leaveSurface].filter(
      (element): element is HTMLElement => element !== null,
    ),
    initialFocus: "[data-overlay-autofocus]",
    trapFocus: pendingLeave === null && tabConfirmSurface === null,
    // The layer captures whatever was focused when it mounted and focuses it again on unmount,
    // which is the card's own open button. That is the done-when's "focus returns to the card".
    restoreFocus: true,
  });

  // The overlay captures the opener first. Focus enters before paint, even while detail is pending.
  useLayoutEffect(() => {
    closeRef.current?.focus({ preventScroll: true });
  }, [connectorKey]);

  useEffect(() => {
    let dead = false;
    setLoadKey(connectorKey);
    const cached = reads === 0 ? connectorDetailCache.get(connectorKey) : undefined;
    if (reads > 0) {
      connectorDetailCache.delete(connectorKey);
      setLoad((current) => current.phase === "ready" && current.detail.overview.key === connectorKey
        ? current : { phase: "loading" });
    } else if (cached) {
      setLoad({ phase: "ready", detail: cached.detail });
      if (Date.now() - cached.at < CONNECTOR_DETAIL_FRESHNESS_MS) return;
    } else {
      setLoad({ phase: "loading" });
    }
    // Status settles before database pages and optional receipt readers compete for the first read.
    if (!detailReadsReady) return;

    const controller = new AbortController();
    let timedOut = false;
    const timeoutMessage = `Reading ${row.label} stopped after ${CONNECTOR_DETAIL_DEADLINE_MS / 1000} seconds because the server did not answer.`;
    const timeout = setTimeout(() => {
      timedOut = true;
      controller.abort();
      if (!dead && !cached) setLoad({ phase: "error", message: timeoutMessage });
    }, CONNECTOR_DETAIL_DEADLINE_MS);
    // Something is already on screen (a cached detail, or the one a re-read keeps painted). Then
    // later pages are gathered off screen and swapped in whole, so a background read never
    // shrinks a complete list to its first page. A first open paints each page as it lands.
    const painted = Boolean(cached) || reads > 0;
    const readPage = async (offset: number): Promise<ConnectorDetail> => {
      const res = await fetch(
        connectorDetailPageUrl(connectorKey, offset, Boolean(cached)),
        { credentials: CREDENTIALS, signal: controller.signal }
      );
      if (res.status === 401 || res.status === 403) clearConnectorDetailCache();
      const body = (await res.json().catch(() => null)) as
        | { error?: { message?: string }; detail?: { error?: { message?: string } } }
        | null;
      if (dead) throw new Error("closed");
      if (timedOut) throw new Error(timeoutMessage);
      if (!res.ok) {
        throw new Error(plainReadFailure(body, `The details for ${row.label} could not be read.`));
      }
      const page = parseConnectorDetail(body, connectorKey);
      if (!page) {
        throw new Error(
          "This connector's details were refused because the answer described a different connection."
        );
      }
      const cursor = page.databasesPage;
      if (cursor !== undefined && (!cursor || cursor.offset !== offset
          || page.databases.length !== Math.min(cursor.limit, Math.max(0, cursor.total - offset))
          || new Set(page.databases.map((database) => database.key)).size !== page.databases.length
          || cursor.next !== (offset + page.databases.length < cursor.total ? offset + cursor.limit : null))) {
        throw new Error("The database list is incomplete. Try again.");
      }
      return page;
    };
    void (async () => {
      try {
        let detail = await readPage(0);
        clearTimeout(timeout);
        // The deadline covers the first page, which is what a person waits on. Later pages run
        // under the same abort, so closing the modal still stops them.
        // A complete list already on screen stays there until the new one is whole; anything
        // else (nothing yet, or a partial list) is replaced page by page.
        const keep = (current: Load) =>
          painted && current.phase === "ready" && current.paging === undefined;
        const fail = (partial: ConnectorDetail) => setLoad((current) =>
          keep(current) ? current : { phase: "ready", detail: partial, paging: "failed" });
        let cursor = detail.databasesPage;
        let next = cursor ? cursor.next : null;
        if (cursor === null) {
          // A paged answer whose cursor could not be read: say so rather than show one page as all.
          fail(detail);
          return;
        }
        if (next === null) {
          connectorDetailCache.set(connectorKey, { detail, at: Date.now() });
          setLoad({ phase: "ready", detail });
          return;
        }
        const firstPage = detail;
        setLoad((current) =>
          keep(current) ? current : { phase: "ready", detail: firstPage, paging: "loading" });
        while (next !== null) {
          const offset: number = next;
          let page: ConnectorDetail;
          // Each later page gets the same deadline; a hung one ends the loop as a failed page.
          const pageTimer = setTimeout(() => controller.abort(), CONNECTOR_DETAIL_DEADLINE_MS);
          try {
            page = await readPage(offset);
          } catch {
            if (!dead) fail(detail);
            return;
          } finally {
            clearTimeout(pageTimer);
          }
          if (dead) return;
          cursor = page.databasesPage;
          detail = appendDetailPage(detail, page);
          if (!cursor || cursor.offset !== offset || cursor.total !== firstPage.databasesPage?.total
              || detail.databases.length !== Math.min(offset + cursor.limit, cursor.total)) {
            fail(detail);
            return;
          }
          next = cursor.next;
          const sofar = detail;
          if (next === null) {
            connectorDetailCache.set(connectorKey, { detail: sofar, at: Date.now() });
            setLoad({ phase: "ready", detail: sofar });
          } else {
            setLoad((current) =>
              keep(current) ? current : { phase: "ready", detail: sofar, paging: "loading" });
          }
        }
      } catch (error) {
        // A failed background read must leave the already painted detail intact.
        if (!dead && !cached) {
          setLoad({
            phase: "error",
            message: timedOut ? timeoutMessage
              : error instanceof Error ? error.message : "Cannot reach the server.",
          });
        }
      } finally {
        clearTimeout(timeout);
      }
    })();
    return () => {
      dead = true;
      clearTimeout(timeout);
      controller.abort();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps -- Omit row.label, which only supplies timeout wording.
  }, [connectorKey, reads, detailReadsReady]);

  const rotationNow = useRotationClock();
  const rotationEntry = row.key === "amazon_sp" && load.phase === "ready"
    ? load.detail.keychain.entries
      .filter((entry) => amazonRotationNotice(entry.client_secret_rotation_deadline, rotationNow))
      .sort((a, b) => Date.parse(a.client_secret_rotation_deadline || "") -
        Date.parse(b.client_secret_rotation_deadline || ""))[0]
    : undefined;
  const rotationNotice = rotationEntry
    ? amazonRotationNotice(rotationEntry.client_secret_rotation_deadline, rotationNow) : null;

  const renderTab = useCallback(() => {
    if (tab === "setup" && !isAdmin) {
      return <p className="conn-setup-refusal">Only an admin can manage connector keys.</p>;
    }
    // β›” THE KEYCHAIN TAB IS BELOW THE LOAD GUARD, and the placeholder it replaces was above it.
    // C4 serves the credential rows on the SAME payload as the overview, so a keychain tab that
    // rendered before the read landed could only render an empty list β€” i.e. "nobody has
    // connected this" about a connection nobody had asked the server about yet.
    if (load.phase === "loading") {
      return (
        <div className="conn-settings-skeleton" role="status" aria-label="Loading connector settings">
          <span /><span /><span /><span />
        </div>
      );
    }
    if (load.phase === "error") {
      return (
        <div className="conn-modal-error">
          <p role="alert">{load.message}</p>
          <button className="conn-modal-retry" type="button" onClick={() => reread()}>
            Try again
          </button>
        </div>
      );
    }
    if (tab === "setup") {
      return <>
        {setupNotice?.key === connectorKey ? <p className="conn-kc-note" role="status">{setupNotice.message}</p> : null}
        <KeychainTab row={row} keychain={load.detail.keychain} onChanged={(message) => {
          setSetupNotice(message ? { key: connectorKey, message } : null);
          reread();
        }}
        isAdmin={isAdmin}
        connectionId={load.detail.databases.find((database) => database.identity?.connectionId)?.identity?.connectionId} />
      </>;
    }
    if (tab === "overview") {
      return (
        <>
          {rotationNotice ? <RotationNotice notice={rotationNotice}
            onRotate={isAdmin && rotationEntry?.replaceable && load.detail.keychain.connect
              ? () => setTab("setup") : undefined} /> : null}
          {row.spawns_tables === true || row.key === "scraper" ? <>
          <DatabasesTab
            ref={databasesRef}
            row={row}
            detail={load.detail}
            isAdmin={isAdmin}
            onChanged={reread}
            onPendingChange={setDatabasePendingCount}
            onBusyChange={setDatabaseTabBusy}
            onConfirmSurface={setTabConfirmSurface}
            reveal={databaseReveal}
            databasesPaging={load.paging}
          />
          </> : <p className="conn-settings-empty">No databases from this connection.</p>}
        </>
      );
    }
    return null;
  }, [connectorKey, databaseReveal, load, reread, rotationEntry, rotationNotice, row, tab, isAdmin, setupNotice]);

  const saveDatabaseChanges = useCallback(async () => {
    if (!databasePendingCount || !databasesRef.current) return;
    setDatabaseSaving(true);
    try {
      await databasesRef.current.savePending();
    } finally {
      setDatabaseSaving(false);
    }
  }, [databasePendingCount]);

  const discardDatabaseChanges = useCallback(() => {
    databasesRef.current?.discardPending();
    setDatabasePendingCount(0);
  }, []);

  const confirmLeave = useCallback(() => {
    if (!pendingLeave) return;
    const destination = pendingLeave;
    discardDatabaseChanges();
    setPendingLeave(null);
    if (destination.kind === "close") onClose();
    else setTab(connectorTab(destination.tab));
  }, [discardDatabaseChanges, onClose, pendingLeave]);

  const expired = rotationNotice?.tone === "expired";
  const status = expired ? "expired" : load.phase === "ready" ? load.detail.overview.status : row.state;
  const title = load.phase === "ready" ? load.detail.overview.label || row.label : row.label;

  return (
    <BodyPortal>
      <div className="conn-modal-backdrop">
        <section
          className="conn-modal"
          ref={panelRef}
          role="dialog"
          aria-modal="true"
          aria-labelledby="conn-modal-title"
          data-overlay-kind="connector-detail"
          tabIndex={-1}
        >
          <header className="conn-modal-head">
            <ConnectorMark connectorKey={row.key} label={row.label} />
            <span className="conn-modal-name" id="conn-modal-title">{title}</span>
            {/* Status words use the same muted type as Keychain metadata. */}
            {status && tab !== "overview" ? (
              <span
                className="conn-kc-meta"
                role={status === "expired" ? "alert" : undefined}
              >{status.charAt(0).toUpperCase() + status.slice(1)}</span>
            ) : null}
            {tab === "overview" && databasePendingCount > 0 ? (
              <div className="conn-modal-save-actions">
                <button
                  type="button"
                  className="conn-db-link"
                  disabled={!databasePendingCount || databaseSaving || databaseTabBusy}
                  onClick={discardDatabaseChanges}
                >
                  Discard
                </button>
                <button
                  type="button"
                  className="conn-modal-go"
                  disabled={!databasePendingCount || databaseSaving || databaseTabBusy}
                  onClick={() => void saveDatabaseChanges()}
                >
                  {databaseSaving ? "Saving" : databasePendingCount
                    ? `Save ${databasePendingCount} ${databasePendingCount === 1 ? "change" : "changes"}`
                    : "Save"}
                </button>
              </div>
            ) : null}
            <button
              type="button"
              ref={closeRef}
              className="conn-modal-close"
              aria-label={`Close the ${row.label} connector`}
              data-overlay-autofocus
              disabled={databaseSaving || databaseTabBusy}
              onClick={requestClose}
            >
              Γ—
            </button>
          </header>
          <div className="conn-modal-tabs" role="tablist" aria-label="Connector sections">
            {connectorTabs(row).map((entry) => (
              <button
                key={entry.key}
                type="button"
                role="tab"
                id={`conn-tab-${entry.key}`}
                className="conn-modal-tab"
                aria-selected={tab === entry.key}
                aria-controls="conn-tab-panel"
                disabled={databaseSaving || databaseTabBusy}
                onClick={() => requestTab(entry.key)}
              >
                {entry.label}
              </button>
            ))}
          </div>
          <div
            className="conn-modal-body"
            id="conn-tab-panel"
            role="tabpanel"
            aria-labelledby={`conn-tab-${tab}`}
            aria-busy={tab === "setup" && isAdmin && load.phase === "loading"}
          >
            <ConnectorOverviewPanel row={row} detail={load.phase === "ready" ? load.detail : null}
              hidden={tab !== "overview"} syncReady={detailReadsReady} onSyncReady={markSyncReady}
              isAdmin={isAdmin} deletionRefreshKey={reads}
              syncCapability={syncSource.capability} syncProblem={syncSource.problem}
              onPullReviews={canPull && load.phase === "ready" ? () => setPulling(true) : undefined}
              onSyncNow={syncCapability ? () => void syncNow.start() : undefined}
              syncBusy={syncNow.busy} syncReceipt={syncNow.receipt} syncError={syncNow.message} />
            {renderTab()}
          </div>
        </section>
      </div>
      {/* β›” RENDERED AS A SIBLING OF THE MODAL, INSIDE THE SAME PORTAL. Nesting it in
          `.conn-modal-body` would put it inside a scrolling, overflow-hidden box and the overlay
          would be clipped by the panel it is supposed to sit above. */}
      {pulling ? (
        <MonidRunDialog
          label={row.label}
          onClose={() => setPulling(false)}
          surfaceRef={setPullSurface}
        />
      ) : null}
      <ConfirmDialog
        open={pendingLeave !== null}
        title="Discard unsaved changes"
        body={<p>{unsavedMessage}</p>}
        confirmLabel="Discard changes"
        tone="destructive"
        onConfirm={confirmLeave}
        onCancel={() => setPendingLeave(null)}
        surfaceRef={setLeaveSurface}
      />
    </BodyPortal>
  );
}