File size: 116,667 Bytes
9e15897
 
85f794d
 
 
 
 
9e15897
d598032
9e15897
 
 
 
d598032
9e15897
 
 
85f794d
 
 
d598032
 
 
 
 
 
 
 
 
 
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
85f794d
 
 
b2aa446
 
85f794d
b2aa446
 
 
 
 
 
 
d598032
 
 
 
7f72224
 
b2aa446
d598032
b2aa446
d598032
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
d598032
b2aa446
d598032
 
 
b2aa446
 
 
 
 
 
85f794d
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
7f72224
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
b2aa446
7f72224
d598032
 
 
 
 
b2aa446
 
 
 
 
 
 
 
d598032
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
85f794d
 
 
 
b2aa446
 
 
 
 
 
85f794d
b2aa446
85f794d
 
 
 
 
b2aa446
 
9e15897
 
85f794d
 
 
9e15897
 
b2aa446
85f794d
 
 
 
9e15897
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
85f794d
 
 
b2aa446
d598032
 
85f794d
 
 
d598032
 
b2aa446
 
 
85f794d
 
 
d598032
 
b2aa446
d598032
b2aa446
 
 
d598032
b2aa446
d598032
b2aa446
d598032
b2aa446
d598032
 
85f794d
 
 
 
 
 
 
d598032
 
b2aa446
 
d598032
b2aa446
 
 
d598032
 
 
 
 
 
9e15897
d598032
7f72224
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
d598032
b2aa446
 
d598032
b2aa446
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
d598032
9e15897
d598032
b2aa446
 
d598032
 
9e15897
d598032
 
 
 
b2aa446
d598032
 
 
9e15897
d598032
 
9e15897
 
d598032
9e15897
d598032
 
 
 
 
 
b2aa446
 
 
 
 
 
9e15897
d598032
 
9e15897
b2aa446
d598032
 
 
 
 
 
 
b2aa446
d598032
9e15897
d598032
b2aa446
 
d598032
 
9e15897
d598032
 
 
 
b2aa446
d598032
 
 
9e15897
d598032
 
9e15897
 
d598032
9e15897
d598032
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
9e15897
d598032
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
7f72224
 
 
9e15897
 
7f72224
 
9e15897
7f72224
 
 
 
d598032
9e15897
d598032
9e15897
b2aa446
 
 
 
 
85f794d
 
d598032
 
7f72224
85f794d
 
 
 
 
 
 
 
 
9e15897
d598032
9e15897
 
 
 
 
b2aa446
9e15897
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
b2aa446
 
9e15897
 
85f794d
9e15897
 
 
d598032
 
 
9e15897
d598032
 
 
 
 
7f72224
 
d598032
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
9e15897
 
b2aa446
85f794d
 
 
 
 
 
9e15897
85f794d
9e15897
 
b2aa446
9e15897
 
85f794d
 
9e15897
85f794d
 
 
9e15897
d598032
 
 
9e15897
 
d598032
b2aa446
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
9e15897
 
 
 
b2aa446
 
 
9e15897
d598032
 
b2aa446
 
9e15897
b2aa446
d598032
 
9e15897
 
 
 
 
d598032
 
9e15897
 
 
 
7f72224
 
 
d598032
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
9e15897
 
 
 
b2aa446
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
 
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
b2aa446
85f794d
 
9e15897
 
 
 
 
 
 
b2aa446
 
 
9e15897
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
d598032
 
9e15897
d598032
 
 
 
 
b2aa446
d598032
 
7f72224
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
85f794d
 
d598032
9e15897
 
 
d598032
9e15897
 
 
d598032
 
9e15897
 
 
 
 
 
 
 
d598032
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
7f72224
 
 
 
d598032
 
 
9e15897
 
 
 
 
7f72224
d598032
7f72224
d598032
 
 
7f72224
d598032
7f72224
d598032
 
 
 
 
9e15897
 
 
 
 
7f72224
d598032
7f72224
d598032
 
 
 
7f72224
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
d598032
b2aa446
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
 
 
 
 
 
 
 
 
 
 
d598032
9e15897
 
d598032
9e15897
 
 
 
 
 
d598032
 
9e15897
 
 
 
 
 
7f72224
 
d598032
 
 
 
 
 
 
 
9e15897
 
 
 
 
d598032
9e15897
 
 
7f72224
 
d598032
 
 
85f794d
 
d598032
 
7f72224
 
 
 
9e15897
 
 
7f72224
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
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
import { Fragment, createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import type { ComponentType, KeyboardEvent, MouseEvent, FocusEvent } from "react";
import { Columns, Funnel, SortAscending, SquaresFour } from "@phosphor-icons/react";
import { ModeIcon } from "../../customer-grid/seam";
import { FieldsHidePanel, FilterBuilderPanel, GroupBuilder, Popover, SortBuilder,
  createFilterRule, runPipeline } from "../../filter-kit";
import type { Field, FilterTree, Row, SortSpec } from "../../filter-kit";
import { API_V1, CREDENTIALS, currentTenant, UNAUTHORIZED_EVENT } from "../../apiContract";
import { useEscapeClose } from "../../ui/useEscapeClose";
import AdsOverview, { OperatorDashboardContext } from "./AdsOverview";
import type { OperatorTab } from "./AdsOverview";
import { operatorDashboardAdapter } from "./DashboardAdapter";
import WastedSpend from "./WastedSpend";
import "../../styles/sdlc79/amazon-operator.css";
import "../../styles/sdlc81/operator-results.css";
import "../../styles/sdlc81/ads-schedule.css";
import "../../styles/sdlc81/ads-change-log.css";
// SortBuilder's "Rows shown" rules (.cg-top-n) live in Table's sheet. Never move this import into
// filter-kit/index.ts: that chunk loads before MapView's sheets and flips Table's .cg-map-zone cursor.
import "../../styles/wave45/data-applications.css";

// S79-T17 (C2, C4, R18): the Amazon operator App screen. The dispatcher draws the App frame, so this view
// draws only the Today batch, History and the item drawer. No chat panel exists here (R18).
// S79-T18 (C7): Today also lists the items other Apps posted. A decision on one goes back to its App.

export interface OperatorApplication {
  id: string;
  name?: string;
  capabilities?: Record<string, boolean>;
}

export interface Proposal {
  id: string;
  status: string;
  adType: string;
  campaign: string;
  sku: string;
  asin: string;
  kind: string;
  /** The posting App's name and its action, on an App inbox item only. */
  app: string;
  action: string;
  change: string;
  currentValue: number | string | null;
  proposedValue: number | string | null;
  valueChange: number | string | null;
  valueUnit: string;
  valuesReason: string;
  currency: string;
  added: string;
  planLink: string;
  shipFrom: string;
  prepOwner: string;
  reason: string;
  gate: string;
  day: string;
  dataDate: string;
  spend: number | null;
  decidedBy: string;
  decidedAt: string;
  note: string;
  cause: string;
  /** A skipped or unknown row's cause from the last approve, shown muted. */
  notice?: string;
  /** The removal snapshot a person reviews in the drawer before approving (S82-T56). */
  review?: RemovalReview | null;
}

interface ReviewedRemoval { reviewed: unknown; validateOnly: boolean }

interface RemovalReview extends ReviewedRemoval {
  /** Sent back unchanged on approve, so the source App checks the numbers its person saw. */
  reviewed: unknown;
  canSubmit: boolean;
  fate: string;
  units: number | null;
  sellable: number | null;
  unitCost: number | null;
  currency: string;
  arithmetic: Record<string, unknown> | null;
  shipTo: Record<string, unknown> | null;
}

interface Held { adType: string; campaign: string; sku: string; asin: string; reason: string }

interface Page { total: number; open: number; offset: number; cursor: string | null }
interface TodayScreen { dataDate: string; items: Proposal[]; appItems: Proposal[]; held: Held[]; canEdit: boolean;
  pages: { items: Page; apps: Page; held: Page }; withheldCount: number }

interface HistoryPage { items: Proposal[]; cursor: string | null; total: number | null; withheldCount: number }

interface ResultMetrics { profit: number | null; acos: number | null }
interface ResultWindow {
  days: number;
  availableOn: string;
  waiting: boolean;
  reason: string;
  before: ResultMetrics | null;
  after: ResultMetrics | null;
}
interface ChangeResults {
  windows: ResultWindow[];
  undo: { available: boolean; reason: string; item: Proposal | null };
  budgetSpend: { cost: number | null; basis: string; reason: string } | null;
}

type Load<T> = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T };

const AD_TAGS: Record<string, string> = { sp: "SP", sb: "SB", sd: "SD" };
/** The `kind` of an App inbox item. */
const APP_KIND = "app";
const HISTORY_PAGE = 50;
const HISTORY_FILTERS = [
  ["", "All"], ["proposed", "Open"], ["sent", "Sent"], ["approved", "Approved"], ["refused", "Refused"],
  ["dismissed", "Dismissed"],
] as const;

const text = (value: unknown) => (typeof value === "string" ? value : "");
const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null);
const scalar = (value: unknown): number | string | null => num(value) ?? (text(value) || null);
const addressText = (value: unknown) => typeof value === "string" ? value
  : value && typeof value === "object" && !Array.isArray(value)
    ? Object.values(value).map(text).filter(Boolean).join(", ") : "";

export interface OperatorColumnSpec {
  key: string;
  label: string;
  width: number;
  /** QI33 must retain these optional fields behind Fields on the initial view. */
  defaultHidden?: boolean;
  kind?: "product" | "value" | "change" | "decision" | "date" | "link" | "status";
}

// R6 keeps the references' content order inside the shared Grid's product-first contract.
export const OPERATOR_TODAY_COLUMNS = [
  { key: "product", label: "Product", width: 168, kind: "product" },
  { key: "current_value", label: "Current value", width: 84, kind: "value" },
  { key: "proposed_value", label: "Proposed value", width: 84, kind: "value" },
  { key: "value_change", label: "Change", width: 88, kind: "change" },
  { key: "decision", label: "Decision", width: 144, kind: "decision" },
  { key: "first_seen", label: "Added", width: 80, kind: "date" },
  { key: "reason", label: "Reason", width: 184 },
  { key: "campaign", label: "Campaign", width: 160, defaultHidden: true },
  { key: "gate", label: "Gate", width: 160, defaultHidden: true },
  { key: "spend", label: "Spend", width: 112, kind: "value", defaultHidden: true },
] as const satisfies readonly OperatorColumnSpec[];

export const OPERATOR_APP_COLUMNS = [
  ...OPERATOR_TODAY_COLUMNS.slice(0, 7),
  { key: "action", label: "Action", width: 224, defaultHidden: true },
  { key: "plan_link", label: "Plan", width: 160, kind: "link", defaultHidden: true },
  { key: "ship_from", label: "Ship from", width: 240, defaultHidden: true },
  { key: "prep_owner", label: "Prep owner", width: 112, defaultHidden: true },
  { key: "app", label: "App", width: 160, defaultHidden: true },
] as const satisfies readonly OperatorColumnSpec[];

export const OPERATOR_HISTORY_COLUMNS = [
  { key: "product", label: "Product", width: 180, kind: "product" },
  { key: "day", label: "Date", width: 96, kind: "date" },
  { key: "campaign", label: "Campaign or App", width: 160 },
  { key: "current_value", label: "Old value", width: 112, kind: "value" },
  { key: "proposed_value", label: "New value", width: 112, kind: "value" },
  { key: "value_change", label: "Change", width: 112, kind: "change" },
  { key: "source", label: "Source", width: 160 },
  { key: "decision", label: "Decision", width: 112, kind: "status" },
  { key: "outcome", label: "Outcome", width: 200 },
] as const satisfies readonly OperatorColumnSpec[];

export const OPERATOR_CHANGE_LOG_COLUMNS = [
  { key: "product", label: "Product", width: 168, kind: "product" },
  { key: "at", label: "Date", width: 132, kind: "date" },
  { key: "operation", label: "Change type", width: 80 },
  { key: "old_value", label: "Old value", width: 88, kind: "value" },
  { key: "new_value", label: "New value", width: 88, kind: "value" },
  { key: "value_change", label: "Change", width: 96, kind: "change" },
  // QI33 shows the recorded approver below Source while Changed by is hidden.
  { key: "source", label: "Source", width: 216 },
  { key: "approver", label: "Changed by", width: 160, defaultHidden: true },
  { key: "campaign", label: "Campaign", width: 160, defaultHidden: true },
  { key: "account", label: "Account", width: 160, defaultHidden: true },
  { key: "status", label: "Outcome", width: 176, kind: "status", defaultHidden: true },
  { key: "currency", label: "Currency", width: 112, defaultHidden: true },
] as const satisfies readonly OperatorColumnSpec[];

const defaultHiddenColumns = (columns: readonly OperatorColumnSpec[]) =>
  columns.filter(column => column.defaultHidden).map(column => column.key);
const gridWidth = (columns: readonly OperatorColumnSpec[], hidden: readonly string[], markers = 0) =>
  columns.reduce((width, column) => width + (hidden.includes(column.key) ? 0 : column.width), markers * 32);

function ColumnHeaders({ columns, sized = false }: { columns: readonly OperatorColumnSpec[]; sized?: boolean }) {
  return <>{columns.map(column => <th key={column.key} scope="col" data-field={column.key}
    style={sized ? { width: column.width } : undefined}
    className={column.kind === "value" || column.kind === "change" ? "is-num" : undefined}>
    {column.label}</th>)}</>;
}

async function readJson(response: Response, fallback: string): Promise<unknown> {
  const body: unknown = await response.json().catch(() => null);
  if (response.ok) return body;
  const error = (body as { detail?: { error?: { message?: unknown } } } | null)?.detail?.error;
  throw new Error(text(error?.message) || fallback);
}

function parseProposal(raw: unknown): Proposal | null {
  const row = (raw ?? {}) as Record<string, unknown>;
  const id = text(row.id);
  if (!id) return null;
  return {
    id, status: text(row.status) || "proposed", adType: text(row.ad_type), campaign: text(row.campaign)
      || text(row.campaign_id), sku: text(row.sku), asin: text(row.asin), kind: text(row.kind),
    app: text(row.app), action: text(row.action), change: text(row.change), reason: text(row.reason), gate: text(row.gate), day: text(row.day),
    currentValue: scalar(row.current_value), proposedValue: scalar(row.proposed_value), valueChange: scalar(row.value_change),
    valueUnit: text(row.value_unit), valuesReason: text(row.values_reason), currency: text(row.currency),
    added: text(row.first_seen) || text(row.firstSeen), planLink: text(row.plan_link), shipFrom: addressText(row.ship_from),
    prepOwner: text(row.prep_owner),
    dataDate: text(row.data_date), spend: num(row.spend), decidedBy: text(row.decided_by),
    decidedAt: text(row.decided_at), note: text(row.note), cause: text(row.cause), review: parseReview(row.review),
  };
}

function parseReview(raw: unknown): RemovalReview | null {
  if (!raw || typeof raw !== "object") return null;
  const row = raw as Record<string, unknown>;
  if (row.reviewed === undefined || row.reviewed === null || row.reviewed === "") return null;
  const record = (value: unknown) => (value && typeof value === "object" && !Array.isArray(value)
    ? value as Record<string, unknown> : null);
  return { reviewed: row.reviewed, validateOnly: row.validateOnly !== false,
    canSubmit: row.canSubmit === true,
    fate: text(row.fate), units: num(row.units), sellable: num(row.sellable),
    unitCost: num(row.unitCost), currency: text(row.currency), arithmetic: record(row.arithmetic),
    shipTo: record(row.shipTo) };
}

/** The drawer lines for a removal: fate, quantities, the cost arithmetic and the typed ship-to. */
function reviewFacts(review: RemovalReview): [string, string][] {
  const amount = (value: unknown) => {
    const figure = num(value);
    return figure === null ? "" : `${money(figure)}${review.currency ? " " + review.currency : ""}`;
  };
  const sums = review.arithmetic ?? {};
  const units = num(review.units);
  const sellable = num(review.sellable);
  const shipTo = Object.values(review.shipTo ?? {}).map(text).filter(Boolean).join(", ");
  return [
    ["Fate", review.fate], ["Units", units === null ? "" : units.toLocaleString()],
    ["Sellable units", sellable === null ? "" : sellable.toLocaleString()],
    ["Unit cost", amount(review.unitCost)], ["Recoverable value", amount(sums.recoverableValue)],
    ["Removal fee", amount(sums.removalFee)], ["Freight", amount(sums.freight)],
    ["Return cost", amount(sums.returnCost)], ["Rule", text(sums.rule)],
    ["Ship to", review.fate === "Return" ? shipTo || "No ship to address" : shipTo],
  ];
}

const proposals = (raw: unknown) => (Array.isArray(raw) ? raw : [])
  .map(parseProposal).filter((row): row is Proposal => row !== null);

function parseToday(raw: unknown): TodayScreen {
  const body = (raw ?? {}) as Record<string, unknown>;
  const pages = (body.pages ?? {}) as Record<string, unknown>;
  const page = (key: string): Page => {
    const row = (pages[key] ?? {}) as Record<string, unknown>;
    return { total: num(row.total) ?? 0, open: num(row.open) ?? 0, offset: num(row.offset) ?? 0,
      cursor: text(row.cursor) || null };
  };
  return {
    dataDate: text(body.dataDate),
    items: proposals(body.items),
    appItems: proposals(body.appItems),
    held: (Array.isArray(body.held) ? body.held : []).map((item) => {
      const row = (item ?? {}) as Record<string, unknown>;
      return { adType: text(row.ad_type), campaign: text(row.campaign) || text(row.campaign_id), sku: text(row.sku),
        asin: text(row.asin), reason: text(row.reason) };
    }).filter((row) => row.reason),
    canEdit: body.canEdit === true,
    withheldCount: num(body.withheldCount) ?? 0,
    pages: { items: page("items"), apps: page("apps"), held: page("held") },
  };
}

function parseHistory(raw: unknown): HistoryPage {
  const body = (raw ?? {}) as Record<string, unknown>;
  return { items: proposals(body.items), cursor: text(body.cursor) || null, total: num(body.total),
    withheldCount: num(body.withheldCount) ?? 0 };
}

function WithheldItems({ count }: { count: number }) {
  return count > 0 ? <p className="ao-undo-notice" role="status" data-surface="operator-source-wall">
    {count} items need access you do not have
  </p> : null;
}

function parseResults(raw: unknown, proposalId: string): ChangeResults {
  const body = (raw ?? {}) as Record<string, unknown>;
  const rawWindows = body.windows;
  if (body.proposal_id !== proposalId || !Array.isArray(rawWindows)) throw new Error("Results are unavailable.");
  const metrics = (raw: unknown): ResultMetrics | null => {
    if (!raw || typeof raw !== "object") return null;
    const row = raw as Record<string, unknown>;
    return { profit: num(row.ad_profit_after_cogs), acos: num(row.acos) };
  };
  const windows = [7, 14].map((days) => {
    const row = rawWindows.find((value: Record<string, unknown> | null) => value?.days === days);
    if (!row || !text(row.available_on) || !["waiting", "ready", "partial"].includes(row.state)) {
      throw new Error("Results are unavailable.");
    }
    return { days, availableOn: text(row.available_on), waiting: row.state === "waiting", reason: text(row.reason),
      before: metrics(row.before), after: metrics(row.after) };
  });
  const undo = (body.undo ?? {}) as Record<string, unknown>;
  const spend = body.budget_spend as Record<string, unknown> | null | undefined;
  return { windows, undo: { available: undo.available === true, reason: text(undo.reason), item: parseProposal(undo.item) },
    budgetSpend: spend ? { cost: num(spend.ad_cost), basis: text(spend.basis), reason: text(spend.reason) } : null };
}

/** "October 21" from an ISO day. The day is a calendar date, so it is read in UTC. */
function dayWords(iso: string, month: "long" | "short" = "long") {
  const date = new Date(iso.length === 10 ? iso + "T00:00:00Z" : iso);
  return Number.isNaN(date.getTime()) ? iso
    : date.toLocaleDateString(undefined, { month, day: "numeric", timeZone: "UTC" });
}

const money = (value: number | null) => (value === null ? "Not held"
  : value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));

const recordedValue = (value: unknown) => value == null ? "Not recorded"
  : typeof value === "number" ? money(value) : String(value);

export function operatorValueText(value: number | string | null, unit: string, currency: string,
  reason = "Value not recorded", signed = false): string {
  if (value === null) return reason || "Value not recorded";
  if (typeof value === "string") return value;
  const amount = (signed && value > 0 ? "+" : "") + (unit === "currency" ? money(value) : value.toLocaleString());
  return unit === "currency" ? `${amount} ${currency || "(Currency not recorded)"}`
    : `${amount} ${unit || "(Unit not recorded)"}`;
}

const proposalValue = (row: Proposal, field: "currentValue" | "proposedValue" | "valueChange") =>
  operatorValueText(row[field], row.valueUnit, row.currency, row.valuesReason, field === "valueChange");

function ValueCells({ row }: { row: Proposal }) {
  return <>
    <td className="ao-c-value is-num" data-field="current_value">{proposalValue(row, "currentValue")}</td>
    <td className="ao-c-value is-num" data-field="proposed_value">{proposalValue(row, "proposedValue")}</td>
    <td className={`ao-c-value ao-c-delta is-num${typeof row.valueChange === "number"
      ? row.valueChange > 0 ? " is-up" : row.valueChange < 0 ? " is-down" : "" : ""}`}
      data-field="value_change">{proposalValue(row, "valueChange")}</td>
  </>;
}

function ProductCell({ row, onOpen }: { row: Proposal; onOpen: (row: Proposal) => void }) {
  return <td className="ao-c-product" data-field="product">
    <span className="ao-product-picture" role="img" aria-label="Product image not supplied" />
    <span className="ao-product-copy"><button type="button" className="ao-open" onClick={() => onOpen(row)}
      title={row.sku || row.asin || "Product not recorded"}>{row.sku || row.asin || "Product not recorded"}</button>
      <small>{row.asin || row.sku || "No SKU or ASIN"}</small></span>
  </td>;
}

function PlanLink({ value }: { value: string }) {
  let safe = false;
  try { safe = new URL(value).protocol === "https:"; } catch { /* Missing links stay plain. */ }
  return safe ? <a className="ao-link" href={value} target="_blank" rel="noopener noreferrer">View plan</a>
    : <span>{value ? "Plan link unavailable" : "Plan link not supplied"}</span>;
}

const isOpen = (row: Proposal) => row.status === "proposed";

/** The plain decision word for a proposal's status. */
export function decisionLabel(status: string): string {
  if (status === "proposed") return "Open";
  if (status === "dismissed") return "Dismissed";
  if (status === "stale") return "No longer open";
  return "Approved";
}

/** The outcome of a decided proposal: its words and whether it is a refusal. */
export function outcomeOf(row: Pick<Proposal, "status" | "cause" | "note" | "kind">):
  { label: string; refused: boolean } | null {
  if (row.status === "sent") return { label: "Sent", refused: false };
  if (row.status === "refused") return { label: row.cause || "Refused", refused: true };
  if (row.status === "approved") return { label: row.kind === APP_KIND ? "Approved" : "Sending", refused: false };
  if (row.status === "dismissed") return { label: "Dismissed", refused: false };
  if (row.status === "stale") return { label: row.cause || "No longer open in its App", refused: false };
  return null;
}

function AdTag({ adType }: { adType: string }) {
  const tag = AD_TAGS[adType] ?? adType.toUpperCase();
  return tag ? <span className="ao-tag">{tag}</span> : null;
}

function Outcome({ row }: { row: Proposal }) {
  const outcome = outcomeOf(row);
  return <>
    {outcome && <span className={outcome.refused ? "ao-result is-refused"
      : row.status === "stale" ? "ao-result is-notice" : `ao-result is-${row.status}`}>
      {outcome.label}</span>}
    {row.status === "dismissed" && row.note && <span className="ao-result is-notice">{row.note}</span>}
    {row.status === "proposed" && row.cause && <span className="ao-result is-notice">{row.cause}</span>}
    {row.notice && <span className="ao-result is-notice">{row.notice}</span>}
  </>;
}

function Skeleton() {
  return <div className="ao-skeleton-rows" aria-busy="true" aria-label="Loading">
    <div className="ao-skeleton" /><div className="ao-skeleton" /><div className="ao-skeleton" />
  </div>;
}

interface SearchProps { search: string; onSearch: (value: string) => void }
type TodayGroup = "items" | "apps" | "held";
const emptyFilters = (): FilterTree => ({ conj: "and", nodes: [] });
export const operatorFields = (columns: readonly (readonly [string, string])[]): Field[] =>
  columns.map(([key, label]) => ({ key, label, source: "overlay",
    type: ["current_value", "proposed_value", "value_change", "spend"].includes(key) ? "currency" : "text" }));
const TODAY_FIELDS = OPERATOR_TODAY_COLUMNS.filter(column => column.key !== "product" && column.key !== "decision")
  .map(column => [column.key, column.label] as const);
const HISTORY_FIELDS = OPERATOR_HISTORY_COLUMNS.filter(column => column.key !== "product")
  .map(column => [column.key, column.label] as const);

function FieldControls({ fields, hidden, onHidden }: {
  fields: Field[]; hidden: string[]; onHidden: (keys: string[]) => void;
}) {
  return <Popover label="Fields" icon={<Columns size={16} aria-hidden="true" />} active={hidden.length > 0} wide>
    {() => fields.length === 0 ? <div className="cg-pop-body cg-builder-empty">No fields to show</div>
      : <FieldsHidePanel fields={fields} hidden={new Set(hidden)}
      onToggle={(key) => onHidden(hidden.includes(key) ? hidden.filter(field => field !== key) : [...hidden, key])}
      onShowAll={() => onHidden([])} onHideAll={() => onHidden(fields.map(field => field.key))} />}
  </Popover>;
}

/** Presentation controls never receive a record writer. Sorting applies to the current cursor page. */
function GridControls({ fields, hidden, onHidden, sorts, onSorts, filters, onFilters, search, onSearch }: SearchProps & {
  fields: Field[]; hidden: string[]; onHidden: (keys: string[]) => void;
  sorts: SortSpec; onSorts: (sorts: SortSpec) => void; filters: FilterTree; onFilters: (filters: FilterTree) => void;
}) {
  return <>
    <FieldControls fields={fields} hidden={hidden} onHidden={onHidden} />
    <Popover label="Sort" icon={<SortAscending size={16} aria-hidden="true" />} active={sorts.length > 0} tone="sort" wide>
      {() => <div role="group" aria-label="Sort current page"><SortBuilder fields={fields}
        fieldByKey={new Map(fields.map(field => [field.key, field]))} sorts={sorts} onSorts={onSorts}
        filters={filters} onFilters={onFilters} grouped={false} /></div>}
    </Popover>
    <label className="ao-grid-search">
      <span className="ao-field-label">Search</span>
      <input type="search" className="ao-input" aria-label="Search proposals" value={search}
        onChange={(event) => onSearch(event.target.value)} />
    </label>
  </>;
}

export function sortProposals(rows: Proposal[], sorts: SortSpec, filters: FilterTree, fields: Field[], today = false) {
  const rawRows: Row[] = rows.map((row, index) => ({ pid: index + 1, campaign: row.campaign || row.app,
    sku: row.sku, reason: row.reason, gate: row.gate, spend: row.spend, first_seen: row.added, day: row.day,
    current_value: row.currentValue, proposed_value: row.proposedValue, value_change: row.valueChange,
    action: row.action || row.change, app: row.app, plan_link: row.planLink, ship_from: row.shipFrom,
    prep_owner: row.prepOwner, source: row.decidedBy, decision: decisionLabel(row.status), outcome: outcomeOf(row)?.label,
    status: today ? isOpen(row) ? "Open" : "Decided" : HISTORY_FILTERS.find(([value]) => value === row.status)?.[1] ?? row.status }));
  return runPipeline({ rawRows, fields, sorts, filters: filters.nodes, filterConj: filters.conj,
    search: "", groupBy: null, collapsed: new Set() }).visibleRows.flatMap(row =>
      row.kind === "data" ? [rows[row.record.pid - 1]] : []);
}

/** Only a root AND status equality can use History's existing server status parameter. */
export function operatorHistoryStatus(filters: FilterTree): string {
  if (filters.conj !== "and") return "";
  const statuses = filters.nodes.filter(node => "op" in node && node.colId === "status" && node.op === "eq");
  const rule = statuses.length === 1 ? statuses[0] : null;
  return rule && "value" in rule ? HISTORY_FILTERS.find(([value, label]) =>
    value && (value === rule.value || label === rule.value))?.[0] ?? "" : "";
}

/** Arrow keys move through cells. Enter opens details and Space changes only row selection. */
function useGridSelection() {
  const [selected, setSelected] = useState("");
  const select = (event: MouseEvent<HTMLTableElement> | FocusEvent<HTMLTableElement>) => {
    const target = event.target as HTMLElement;
    const row = target.closest<HTMLTableRowElement>("tr[data-row-id]");
    if (row) setSelected(row.dataset.rowId || "");
    if (event.type === "click" && !target.closest("button, input, select, summary, a")) {
      const cell = target.closest<HTMLTableCellElement>("td");
      if (cell) { cell.tabIndex = -1; cell.focus(); }
    }
  };
  const onKeyDown = (event: KeyboardEvent<HTMLTableElement>) => {
    const target = event.target as HTMLElement;
    if (target.closest("button, input, select, summary, a, details")) return;
    const rows = Array.from(event.currentTarget.tBodies[0]?.rows ?? []);
    if (!rows.length) return;
    const current = target.closest<HTMLTableCellElement>("td");
    const rowIndex = Math.max(0, rows.findIndex((row) => row === current?.parentElement));
    const row = rows[rowIndex];
    const visibleCells = (row: HTMLTableRowElement) => Array.from(row.cells).filter((cell) => cell.getClientRects().length > 0);
    const column = Math.max(0, visibleCells(row).findIndex((cell) => cell === current));
    let nextRow = rowIndex;
    let nextCol = column;
    if (event.key === "ArrowDown") nextRow = Math.min(rows.length - 1, rowIndex + (current ? 1 : 0));
    else if (event.key === "ArrowUp") nextRow = Math.max(0, rowIndex - 1);
    else if (event.key === "ArrowRight") nextCol++;
    else if (event.key === "ArrowLeft") nextCol--;
    else if (event.key === "Home") { nextCol = 0; if (event.ctrlKey || event.metaKey) nextRow = 0; }
    else if (event.key === "End") {
      if (event.ctrlKey || event.metaKey) nextRow = rows.length - 1;
      nextCol = visibleCells(rows[nextRow]).length - 1;
    } else if (event.key === "Enter") {
      row.querySelector<HTMLButtonElement>(".ao-open")?.click(); event.preventDefault(); return;
    } else if (event.key === " ") {
      const tick = row.querySelector<HTMLInputElement>(".ao-c-tick input:not(:disabled)");
      if (tick) tick.click();
      else setSelected((value) => value === row.dataset.rowId ? "" : row.dataset.rowId || "");
      event.preventDefault(); return;
    } else return;
    event.preventDefault();
    const cells = visibleCells(rows[nextRow]);
    const cell = cells[Math.max(0, Math.min(cells.length - 1, nextCol))];
    if (!cell) return;
    cell.tabIndex = -1;
    cell.focus();
    cell.scrollIntoView({ block: "nearest", inline: "nearest" });
    const viewport = event.currentTarget.closest<HTMLDivElement>(".ao-grid-viewport");
    if (!viewport) return;
    const style = getComputedStyle(cell);
    if (style.position === "sticky" && (style.left !== "auto" || style.right !== "auto")) return;

    // Native scrolling ignores cells frozen over the scrollport. Reserve their measured bounds.
    const viewportRect = viewport.getBoundingClientRect();
    const viewportLeft = viewportRect.left + viewport.clientLeft;
    let left = Math.max(0, viewportLeft);
    let right = Math.min(document.documentElement.clientWidth, viewportLeft + viewport.clientWidth);
    for (const peer of cells) {
      const pinned = getComputedStyle(peer);
      if (pinned.position !== "sticky") continue;
      const bounds = peer.getBoundingClientRect();
      if (bounds.right <= left || bounds.left >= right) continue;
      if (pinned.left !== "auto" && peer.cellIndex < cell.cellIndex) left = Math.max(left, bounds.right);
      if (pinned.right !== "auto" && peer.cellIndex > cell.cellIndex) right = Math.min(right, bounds.left);
    }
    const available = right - left;
    if (available <= 0) return;
    const bounds = cell.getBoundingClientRect();
    const start = bounds.left - left;
    const end = bounds.right - right;
    // An oversized cell keeps its visible portion, or aligns the nearest edge, without oscillating.
    const delta = bounds.width <= available
      ? start < 0 ? start : end > 0 ? end : 0
      : start > 0 ? start : end < 0 ? end : 0;
    viewport.scrollLeft = Math.max(0, Math.min(viewport.scrollWidth - viewport.clientWidth, viewport.scrollLeft + delta));
  };
  return { selected, table: { role: "grid", tabIndex: 0, "aria-describedby": "ao-grid-help",
    onKeyDown, onClick: select, onFocusCapture: select } };
}

function Failed({ message, onRetry }: { message: string; onRetry: () => void }) {
  return <p className="ao-error" role="alert">{message}{" "}
    <button type="button" className="ao-link" onClick={onRetry}>Retry</button></p>;
}

function Drawer({ row, onClose, onReviewed, editable, previousReview }: {
  row: Proposal; onClose: () => void; onReviewed?: (id: string, reviewed: ReviewedRemoval) => void; editable: boolean;
  previousReview?: ReviewedRemoval;
}) {
  const panel = useRef<HTMLElement | null>(null);
  const close = useRef<HTMLButtonElement | null>(null);
  const [validateOnly, setValidateOnly] = useState(previousReview
    && JSON.stringify(previousReview.reviewed) === JSON.stringify(row.review?.reviewed)
    ? previousReview.validateOnly : row.review?.validateOnly !== false);
  useEscapeClose(true, onClose, { container: () => panel.current });
  useEffect(() => { close.current?.focus(); }, [row.id]);
  // The snapshot shown here is the one an approve sends back, so a changed removal is refused, never sent.
  const reviewed = row.review?.reviewed;
  useEffect(() => {
    if (reviewed !== undefined && row.status === "proposed" && editable)
      onReviewed?.(row.id, { reviewed, validateOnly });
  }, [row.id, row.status, reviewed, validateOnly, editable, onReviewed]);
  const outcome = outcomeOf(row);
  const facts: [string, string][] = [
    ...(row.review ? reviewFacts(row.review) : []),
    ["App", row.app], ["Campaign", row.campaign], ["Ad type", AD_TAGS[row.adType] ?? row.adType], ["SKU", row.sku],
    ["ASIN", row.asin], ["Action", row.action || row.change], ["Current value", proposalValue(row, "currentValue")],
    ["Proposed value", proposalValue(row, "proposedValue")], ["Change", row.change], ["Reason", row.reason], ["Gate", row.gate],
    ["Added", row.added ? dayWords(row.added) : ""], ["Ship from", row.shipFrom], ["Prep owner", row.prepOwner],
    ["Data date", row.dataDate ? dayWords(row.dataDate) : ""], ["Decision", decisionLabel(row.status)],
    ["Decided by", row.decidedBy], ["Note", row.note], ["Cause", row.cause],
  ];
  return <aside ref={panel} className="ao-drawer" role="dialog" aria-label={row.review ? "Removal review" : "Proposal"}>
    <div className="ao-drawer-head">
      <h2 className="ao-drawer-title">{row.review ? "Removal review" : row.kind === APP_KIND ? "App proposal" : "Ad proposal"}</h2>
      <button ref={close} type="button" className="ao-button is-quiet" onClick={onClose}>Close</button>
    </div>
    {row.review?.canSubmit && row.status === "proposed" && editable && <label className="ao-field">
      <span className="ao-field-label">Removal mode</span>
      <select className="ao-select" aria-label="Removal mode" value={String(validateOnly)}
        onChange={event => setValidateOnly(event.target.value === "true")}>
        <option value="true">Validate file</option><option value="false">Submit removal</option>
      </select>
    </label>}
    <dl className="ao-facts">
      {facts.filter(([, value]) => value).map(([label, value]) => <div key={label} className="ao-fact">
        <dt>{label}</dt><dd className={row.review && ["Units", "Sellable units", "Unit cost", "Recoverable value",
          "Removal fee", "Freight", "Return cost"].includes(label) ? "is-num" : undefined}>{value}</dd>
      </div>)}
      {row.kind === APP_KIND && <div className="ao-fact"><dt>Plan</dt><dd><PlanLink value={row.planLink} /></dd></div>}
      {row.kind !== APP_KIND && <div className="ao-fact"><dt>Spend</dt><dd className="is-num">
        {operatorValueText(row.spend, "currency", row.currency, "Spend not recorded")}</dd></div>}
      {outcome && <div className="ao-fact"><dt>Outcome</dt>
        <dd className={outcome.refused ? "is-refused" : undefined}>{outcome.label}</dd></div>}
    </dl>
  </aside>;
}

interface TodayProps extends SearchProps {
  state: Load<TodayScreen>;
  busy: boolean;
  onPage: (section: "items" | "apps" | "held", offset: number) => void;
  editable: boolean;
  excluded: ReadonlySet<string>;
  settled: ReadonlySet<string>;
  sending: boolean;
  decideError: string;
  dismissing: Dismissing | null;
  onToggle: (id: string) => void;
  onToggleAll: (open: Proposal[], include: boolean) => void;
  onApprove: (batch: Proposal[]) => void;
  onDismissStart: (id: string | null) => void;
  onDismissReason: (reason: string) => void;
  onDismissCancel: () => void;
  onDismiss: (ids: string[], reason: string) => void;
  onOpen: (row: Proposal) => void;
  onRetry: () => void;
}

/** An open reason field: one row's (id) or the ticked batch's (id null). */
interface Dismissing { id: string | null; reason: string }

function ReasonForm({ label, submitLabel, ready, value, busy, inline, onChange, onCancel, onSubmit }: {
  label: string; submitLabel: string; ready: boolean; value: string; busy: boolean; inline: boolean;
  onChange: (value: string) => void; onCancel: () => void; onSubmit: () => void;
}) {
  return <form className={inline ? "ao-reason-form is-inline" : "ao-reason-form"}
    onSubmit={(event) => { event.preventDefault(); if (value.trim() && ready && !busy) onSubmit(); }}>
    <input className="ao-input" value={value} onChange={(event) => onChange(event.target.value)} autoFocus
      placeholder="Reason" aria-label={label} disabled={busy} />
    <span className="ao-reason-actions">
      <button type="submit" className="ao-button" disabled={busy || !ready || !value.trim()}>{submitLabel}</button>
      <button type="button" className="ao-button is-quiet" disabled={busy} onClick={onCancel}>Cancel</button>
    </span>
  </form>;
}

type RowProps = Pick<TodayProps, "editable" | "excluded" | "settled" | "sending" | "dismissing" | "onToggle"
  | "onToggleAll" | "onApprove" | "onDismissStart" | "onDismissReason" | "onDismissCancel" | "onDismiss" | "onOpen">;

/** The select all tick for one group's open rows. */
function TickAll({ open, excluded, sending, label, onToggleAll }: {
  open: Proposal[]; excluded: ReadonlySet<string>; sending: boolean; label: string;
  onToggleAll: (open: Proposal[], include: boolean) => void;
}) {
  const ticked = open.filter((row) => !excluded.has(row.id)).length;
  const allIn = open.length > 0 && ticked === open.length;
  return <label className="ao-tick-all">
    <input type="checkbox" className="ao-check" checked={allIn} disabled={sending || open.length === 0}
      ref={(node) => { if (node) node.indeterminate = ticked > 0 && !allIn; }}
      onChange={() => onToggleAll(open, !allIn)} aria-label={label} />
    <span className="ao-tick-all-label">Select all</span>
  </label>;
}

/** One row's result in place, then its own Dismiss while it is open. */
function ResultCell({ row, live, props }: { row: Proposal; live: boolean; props: RowProps }) {
  const { editable, sending, dismissing, onApprove, onDismissStart, onDismissReason, onDismissCancel, onDismiss } = props;
  const what = row.change || row.action;
  return <td className="ao-c-result" data-field="decision" aria-live="polite">
    {live && <span className="ao-status" data-status={row.status}>Open</span>}
    <Outcome row={row} />
    {editable && live && <button type="button" className="ao-button" disabled={sending}
      aria-label={`Approve ${what}`} onClick={() => onApprove([row])}>Approve</button>}
    {editable && live && (dismissing?.id === row.id
      ? <ReasonForm label={`Reason to dismiss ${what}`} submitLabel="Dismiss" ready
        value={dismissing.reason}
        busy={sending} inline={false} onChange={onDismissReason} onCancel={onDismissCancel}
        onSubmit={() => onDismiss([row.id], dismissing.reason)} />
      : <button type="button" className="ao-dismiss-open" disabled={sending}
        aria-label={`Dismiss ${what}`} onClick={() => onDismissStart(row.id)}>Dismiss</button>)}
  </td>;
}

function rowClass(live: boolean, leaving: boolean) {
  return leaving ? "ao-row is-settled" : live ? "ao-row" : "ao-row is-decided";
}

function AdTable({ items, props, offset, hidden }: { items: Proposal[]; props: RowProps; offset: number; hidden: string[] }) {
  const { editable, excluded, settled, sending, onToggle, onToggleAll, onOpen } = props;
  const grid = useGridSelection();
  const open = items.filter(isOpen);
  return <table {...grid.table} aria-label="Ad changes grid" className={editable ? "ao-table ao-today" : "ao-table ao-today is-readonly"}
    style={{ width: gridWidth(OPERATOR_TODAY_COLUMNS, hidden, editable ? 2 : 1) }}>
    <thead>
      <tr>
        <th scope="col" aria-label="Row">#</th>
        {editable && <th scope="col" className="ao-c-tick">
          <TickAll open={open} excluded={excluded} sending={sending} label="Select all ad changes"
            onToggleAll={onToggleAll} />
        </th>}
        <ColumnHeaders columns={OPERATOR_TODAY_COLUMNS} sized />
      </tr>
    </thead>
    <tbody>
      {items.map((row, index) => {
        const live = isOpen(row);
        const leaving = settled.has(row.id);
        return <tr key={row.id} data-row-id={row.id} aria-selected={grid.selected === row.id}
          data-included={editable && live && !excluded.has(row.id) || undefined} className={rowClass(live, leaving)}
          aria-busy={sending && live && !excluded.has(row.id) ? true : undefined}>
          <td className="ao-grid-marker">{offset + index + 1}</td>
          {editable && <td className="ao-c-tick">
            {(live || leaving) && <input type="checkbox" className="ao-check" checked={live && !excluded.has(row.id)}
              disabled={!live || sending} tabIndex={live ? undefined : -1} aria-hidden={live ? undefined : true}
              onChange={() => onToggle(row.id)}
              aria-label={`Include ${row.change} for ${row.sku || row.campaign}`} />}
          </td>}
          <ProductCell row={row} onOpen={onOpen} />
          <ValueCells row={row} />
          <ResultCell row={row} live={live} props={props} />
          <td data-field="first_seen">{row.added ? dayWords(row.added, "short") : "Added date not recorded"}</td>
          <td className="ao-c-reason" data-field="reason" title={row.reason}>{row.reason || "Reason not recorded"}</td>
          <td className="ao-c-campaign" data-field="campaign">
            <button type="button" className="ao-open" title={row.campaign} onClick={() => onOpen(row)}>{row.campaign}</button>
            <AdTag adType={row.adType} />
          </td>
          <td className="ao-c-gate" data-field="gate" title={row.gate}>{row.gate}</td>
          <td className="is-num" data-field="spend">{operatorValueText(row.spend, "currency", row.currency, "Spend not recorded")}</td>
        </tr>;
      })}
    </tbody>
  </table>;
}

/** Items the other Apps posted: App, SKU, action and reason. A stale row shows why and takes no tick. */
function AppTable({ items, props, offset, hidden }: { items: Proposal[]; props: RowProps; offset: number; hidden: string[] }) {
  const { editable, excluded, settled, sending, onToggle, onToggleAll, onOpen } = props;
  const grid = useGridSelection();
  const open = items.filter(isOpen);
  return <table {...grid.table} aria-label="App items grid" className={editable ? "ao-table ao-today ao-apps" : "ao-table ao-today ao-apps is-readonly"}
    style={{ width: gridWidth(OPERATOR_APP_COLUMNS, hidden, editable ? 2 : 1) }}>
    <thead>
      <tr>
        <th scope="col" aria-label="Row">#</th>
        {editable && <th scope="col" className="ao-c-tick">
          <TickAll open={open} excluded={excluded} sending={sending} label="Select all App items"
            onToggleAll={onToggleAll} />
        </th>}
        <ColumnHeaders columns={OPERATOR_APP_COLUMNS} sized />
      </tr>
    </thead>
    <tbody>
      {items.map((row, index) => {
        const live = isOpen(row);
        const leaving = settled.has(row.id);
        return <tr key={row.id} data-row-id={row.id} aria-selected={grid.selected === row.id}
          data-included={editable && live && !excluded.has(row.id) || undefined} className={rowClass(live, leaving)}
          aria-busy={sending && live && !excluded.has(row.id) ? true : undefined}>
          <td className="ao-grid-marker">{offset + index + 1}</td>
          {editable && <td className="ao-c-tick">
            {(live || leaving) && <input type="checkbox" className="ao-check" checked={live && !excluded.has(row.id)}
              disabled={!live || sending} tabIndex={live ? undefined : -1} aria-hidden={live ? undefined : true}
              onChange={() => onToggle(row.id)}
              aria-label={`Include ${row.action} for ${row.sku || row.app}`} />}
          </td>}
          <ProductCell row={row} onOpen={onOpen} />
          <ValueCells row={row} />
          <ResultCell row={row} live={live} props={props} />
          <td data-field="first_seen">{row.added ? dayWords(row.added, "short") : "Added date not recorded"}</td>
          <td className="ao-c-reason" data-field="reason" title={row.reason}>{row.reason || "Reason not recorded"}</td>
          <td className="ao-c-action" data-field="action">{row.action}</td>
          <td className="ao-c-plan" data-field="plan_link"><PlanLink value={row.planLink} /></td>
          <td className="ao-c-address" data-field="ship_from">{row.shipFrom || "Ship from not supplied"}</td>
          <td data-field="prep_owner">{row.prepOwner || "Prep owner not supplied"}</td>
          <td className="ao-c-campaign" data-field="app">
            <button type="button" className="ao-open" title={row.app} onClick={() => onOpen(row)}>{row.app}</button>
          </td>
        </tr>;
      })}
    </tbody>
  </table>;
}

function HeldTable({ items, offset }: { items: Held[]; offset: number }) {
  const grid = useGridSelection();
  return <table {...grid.table} className="ao-table ao-held-grid" aria-label="Held grid">
    <thead><tr><th scope="col" aria-label="Row">#</th><th scope="col">Campaign</th>
      <th scope="col" data-field="sku">SKU</th><th scope="col" data-field="reason">Reason</th></tr></thead>
    <tbody>{items.map((row, index) => {
      const id = `${row.adType}:${row.campaign}:${row.sku || row.asin}:${index}`;
      return <tr key={id} data-row-id={id} aria-selected={grid.selected === id} className="ao-row">
        <td className="ao-grid-marker">{offset + index + 1}</td><td title={row.campaign}>{row.campaign}</td>
        <td data-field="sku" title={row.sku || row.asin}>{row.sku || row.asin}</td>
        <td data-field="reason" title={row.reason}>{row.reason}</td>
      </tr>;
    })}</tbody>
  </table>;
}

function Pager({ label, page, count, busy, onPage }: {
  label: string; page: Page; count: number; busy: boolean; onPage: (offset: number) => void;
}) {
  return <nav className="ao-bar ao-grid-footer" aria-label={label} aria-busy={busy}>
    <button type="button" className="ao-button is-quiet" disabled={busy || page.offset === 0}
      onClick={() => { if (!busy && page.offset > 0) onPage(Math.max(0, page.offset - HISTORY_PAGE)); }}>Previous</button>
    <span>{page.offset + (count ? 1 : 0)} to {page.offset + count} of {page.total}</span>
    <button type="button" className="ao-button is-quiet" disabled={busy || !page.cursor}
      onClick={() => { if (!busy && page.cursor) onPage(Number(page.cursor)); }}>Next</button>
  </nav>;
}

function TodayPanel(props: TodayProps) {
  const { state, editable, excluded, sending, decideError, dismissing, onApprove, onDismissStart,
    onDismissReason, onDismissCancel, onDismiss, onRetry } = props;
  const [group, setGroup] = useState<TodayGroup>("items");
  const [hiddenByGroup, setHiddenByGroup] = useState<Record<TodayGroup, string[]>>(() => ({
    items: defaultHiddenColumns(OPERATOR_TODAY_COLUMNS), apps: defaultHiddenColumns(OPERATOR_APP_COLUMNS), held: [],
  }));
  const hidden = hiddenByGroup[group];
  const setHidden = (keys: string[]) => setHiddenByGroup(current => ({ ...current, [group]: keys }));
  const [sorts, setSorts] = useState<SortSpec>([]);
  const [filters, setFilters] = useState<FilterTree>(emptyFilters);
  if (state.phase === "loading") return <Skeleton />;
  if (state.phase === "error") return <Failed message={state.message} onRetry={onRetry} />;
  const { items, appItems, held, dataDate, pages } = state.value;
  const fields = operatorFields(group === "apps" ? OPERATOR_APP_COLUMNS
    .filter(column => column.key !== "product" && column.key !== "decision").map(column => [column.key, column.label] as const)
    : group === "held" ? [["sku", "SKU"], ["reason", "Reason"], ["campaign", "Campaign"]] : TODAY_FIELDS);
  const statusField: Field = { key: "status", label: "Status", type: "select", source: "overlay", options: ["Open", "Decided"] };
  const filterFields = [...fields, statusField];
  const rows = sortProposals(group === "items" ? items : group === "apps" ? appItems : [], sorts, filters, filterFields, true);
  const heldRows = runPipeline({ rawRows: held.map((row, index) => ({ ...row, pid: index + 1 })), fields,
    sorts, filters: [], search: "", groupBy: null, collapsed: new Set() }).visibleRows.flatMap(row =>
      row.kind === "data" ? [held[row.record.pid - 1]] : []);
  const open = rows.filter(isOpen);
  const batch = open.filter((row) => !excluded.has(row.id));
  const count = group === "items" ? items.length : group === "apps" ? appItems.length : held.length;
  const visibleCount = group === "held" ? heldRows.length : rows.length;
  const pageLabels = { items: "Ad change pages", apps: "App item pages", held: "Held pages" };
  return <div className="ao-view ao-grid-shell" data-surface="operator-today-grid" data-hidden={hidden.join(" ")}
    aria-busy={props.busy}>
    <WithheldItems count={state.value.withheldCount} />
    <div className="ao-grid-toolbar">
      <span className="ao-grid-view"><ModeIcon mode="grid" />Grid view</span>
      <Popover label="Group" icon={<SquaresFour size={16} aria-hidden="true" />} active tone="group">
        {() => <div role="group" aria-label="Today group"><GroupBuilder
          fields={operatorFields([["items", `Ad changes (${pages.items.total})`],
            ["apps", `From your Apps (${pages.apps.total})`], ["held", `Held (${pages.held.total})`]])}
          groupBy={group} allowUngrouped={false} readOnly={sending}
          onGroupBy={key => { if (key === "items" || key === "apps" || key === "held") {
            setGroup(key); onDismissCancel();
          } }} /></div>}
      </Popover>
      <GridControls fields={fields} hidden={hidden} onHidden={setHidden} sorts={sorts} onSorts={setSorts}
        filters={filters} onFilters={setFilters} search={props.search} onSearch={props.onSearch} />
      {group !== "held" && <Popover label="Filter" icon={<Funnel size={16} aria-hidden="true" />} active={filters.nodes.length > 0} tone="filter" wide>
        {() => <div role="group" aria-label="Filter current page"><FilterBuilderPanel fields={filterFields}
          filters={filters} onChange={next => { setFilters(next); onDismissCancel(); }} /></div>}
      </Popover>}
    </div>
    <div className="ao-bar ao-grid-decisions">
      {dataDate && <span className="ao-date">Ads data for {dayWords(dataDate)}</span>}
      {editable && open.length > 0 && <div className="ao-actions">
        {dismissing && dismissing.id === null
          ? <ReasonForm label={`Reason to dismiss ${batch.length}`} submitLabel={`Dismiss ${batch.length}`}
            ready={batch.length > 0} value={dismissing.reason}
            busy={sending} inline onChange={onDismissReason} onCancel={onDismissCancel}
            onSubmit={() => onDismiss(batch.map((row) => row.id), dismissing.reason)} />
          : <button type="button" className="ao-button ao-dismiss-many" disabled={sending || batch.length === 0}
            onClick={() => onDismissStart(null)}>{`Dismiss ${batch.length}`}</button>}
        <button type="button" className="ao-button is-primary" disabled={sending || batch.length === 0}
          onClick={() => onApprove(batch)}>{sending ? "Sending" : `Approve ${batch.length}`}</button>
      </div>}
    </div>
    {decideError && <p className="ao-error" role="alert">{decideError}</p>}
    <div className="ao-grid-viewport" key={group}>
      {group === "items" ? <AdTable items={rows} props={props} offset={pages.items.offset} hidden={hidden} />
        : group === "apps" ? <AppTable items={rows} props={props} offset={pages.apps.offset} hidden={hidden} />
          : <HeldTable items={heldRows} offset={pages.held.offset} />}
      {visibleCount === 0 && <p className="ao-empty" role="status">{group === "held" ? "No held items"
        : filters.nodes.length === 0 ? "Nothing to change today" : "No matches on this page"}</p>}
    </div>
    <Pager label={pageLabels[group]} page={pages[group]} count={count} busy={props.busy || sending}
      onPage={(offset) => props.onPage(group, offset)} />
  </div>;
}

interface HistoryProps extends SearchProps {
  state: Load<HistoryPage>;
  filter: string;
  loadingMore: boolean;
  moreError: string;
  onFilter: (status: string) => void;
  offset: number;
  onPage: (offset: number) => void;
  onOpen: (row: Proposal) => void;
  onRetry: () => void;
  editable: boolean;
  undoing: boolean;
  resultUrl: (id: string) => string;
  onUndo: (id: string) => Promise<void>;
  onToday: () => void;
}

function SentResults({ row, editable, undoing, resultUrl, onUndo, onToday }: {
  row: Proposal;
} & Pick<HistoryProps, "editable" | "undoing" | "resultUrl" | "onUndo" | "onToday">) {
  const [state, setState] = useState<Load<ChangeResults>>({ phase: "loading" });
  const [attempt, setAttempt] = useState(0);
  const [undoError, setUndoError] = useState("");
  const endpoint = resultUrl(row.id);
  useEffect(() => {
    const controller = new AbortController();
    setState({ phase: "loading" });
    void fetch(endpoint, { credentials: CREDENTIALS, signal: controller.signal })
      .then((response) => readJson(response, "Results could not be loaded."))
      .then((body) => { if (!controller.signal.aborted) setState({ phase: "ready", value: parseResults(body, row.id) }); })
      .catch((reason: unknown) => {
        if (!controller.signal.aborted) setState({ phase: "error", message: reason instanceof Error
          ? reason.message : "Results could not be loaded." });
      });
    return () => controller.abort();
  }, [endpoint, row.id, attempt]);
  const undo = async () => {
    setUndoError("");
    try { await onUndo(row.id); }
    catch (reason) { setUndoError(reason instanceof Error ? reason.message : "Undo could not be added."); }
  };
  if (state.phase === "loading") return <td colSpan={10} className="ao-result-loading" aria-busy="true">Loading results</td>;
  if (state.phase === "error") return <td colSpan={10}>
    <Failed message={state.message} onRetry={() => setAttempt((n) => n + 1)} /></td>;
  const report = state.value;
  const profit = (value: number | null | undefined) => value == null ? "Unavailable" : money(value);
  const acos = (value: number | null | undefined) => value == null ? "Unavailable" : `${money(value)}%`;
  return <>
    {report.windows.map((window) => window.waiting
      ? <td key={window.days} colSpan={4} data-result-window={window.days} className="ao-result-wait">
        Result arrives {dayWords(window.availableOn)}
      </td>
      : <Fragment key={window.days}>
        <td className="is-num" data-result-window={window.days} data-metric="profit-before"
          aria-label={`${window.days} day profit after ads and COGS before: ${profit(window.before?.profit)}. ${window.reason}`}>
          {profit(window.before?.profit)}</td>
        <td className="is-num" data-result-window={window.days} data-metric="profit-after"
          aria-label={`${window.days} day profit after ads and COGS after: ${profit(window.after?.profit)}. ${window.reason}`}>
          {profit(window.after?.profit)}</td>
        <td className="is-num" data-result-window={window.days} data-metric="acos-before"
          aria-label={`${window.days} day ACoS before: ${acos(window.before?.acos)}. ${window.reason}`}>
          {acos(window.before?.acos)}</td>
        <td className="is-num" data-result-window={window.days} data-metric="acos-after"
          aria-label={`${window.days} day ACoS after: ${acos(window.after?.acos)}. ${window.reason}`}>
          {acos(window.after?.acos)}</td>
      </Fragment>)}
    <td className="ao-budget-spend is-num">
      {report.budgetSpend ? <Popover label={profit(report.budgetSpend.cost)} icon={null}>
        {() => report.budgetSpend && <div className="ao-grid-options ao-budget-detail">
          <strong>Spend under changed budget</strong>
          <p>{report.budgetSpend.basis}</p>
          <p>Daily totals include send and Undo days. Past spend stays.</p>
          {report.budgetSpend.reason && <p>{report.budgetSpend.reason}</p>}
        </div>}
      </Popover> : <span className="ao-result-note">Not applicable</span>}
    </td>
    <td className="ao-grid-undo">
      {editable && report.undo.available && !report.undo.item && <button type="button" className="ao-button ao-undo"
        disabled={undoing} aria-label={`Undo ${row.change}`} title="Add an Undo proposal to Today"
        onClick={() => void undo()}>{undoing ? "Adding Undo" : "Undo"}</button>}
      {report.undo.item && <span className="ao-result-note" role="status">
        {report.undo.item.status === "proposed" ? "Undo is in Today" : `Undo: ${outcomeOf(report.undo.item)?.label || report.undo.item.status}`}
        {editable && report.undo.item.status === "proposed" && <button type="button" className="ao-link" onClick={onToday}>View in Today</button>}
      </span>}
      {!report.undo.available && report.undo.reason && <span className="ao-result-note" title={report.undo.reason}>{report.undo.reason}</span>}
      {undoError && <p className="ao-error" role="alert">{undoError}</p>}
    </td>
  </>;
}

function HistoryPanel({ state, filter, loadingMore, moreError, onFilter, offset, onPage, onOpen, onRetry,
  editable, undoing, resultUrl, onUndo, onToday, search, onSearch }: HistoryProps) {
  const [hidden, setHidden] = useState<string[]>([]);
  const [sorts, setSorts] = useState<SortSpec>([]);
  const [filters, setFilters] = useState<FilterTree>(() => ({ conj: "and", nodes: filter
    ? [createFilterRule({ colId: "status", op: "eq", value: HISTORY_FILTERS.find(([value]) => value === filter)?.[1] ?? filter })] : [] }));
  const fields = operatorFields(HISTORY_FIELDS);
  const filterFields: Field[] = [...fields, { key: "status", label: "Status", type: "select", source: "overlay",
    options: HISTORY_FILTERS.filter(([value]) => value).map(([, label]) => label) }];
  const grid = useGridSelection();
  const rows = state.phase === "ready" ? sortProposals(state.value.items, sorts, filters, filterFields) : [];
  return <div className="ao-view ao-grid-shell" data-surface="operator-history-grid" data-hidden={hidden.join(" ")}
    aria-busy={loadingMore}>
    {state.phase === "ready" && <WithheldItems count={state.value.withheldCount} />}
    <div className="ao-grid-toolbar">
      <span className="ao-grid-view"><ModeIcon mode="grid" />Grid view</span>
      <GridControls fields={fields} hidden={hidden} onHidden={setHidden}
        sorts={sorts} onSorts={setSorts} filters={filters} onFilters={setFilters} search={search} onSearch={onSearch} />
      <Popover label={filter ? `Filter: ${HISTORY_FILTERS.find(([value]) => value === filter)?.[1]}` : "Filter"}
        icon={<Funnel size={16} aria-hidden="true" />} active={filters.nodes.length > 0} tone="filter" wide>
        {() => <div role="group" aria-label="History status"><FilterBuilderPanel fields={filterFields}
          filters={filters} onChange={next => { setFilters(next); onFilter(operatorHistoryStatus(next)); }} /></div>}
      </Popover>
    </div>
    {state.phase === "loading" && <Skeleton />}
    {state.phase === "error" && <Failed message={state.message} onRetry={onRetry} />}
    {state.phase === "ready" && <div className="ao-grid-viewport">
      <table {...grid.table} aria-label="History grid" className="ao-table ao-history">
      <thead>
        <tr><th scope="col" aria-label="Row">#</th><ColumnHeaders columns={OPERATOR_HISTORY_COLUMNS} />
          {filter === "sent" && <>
            {[7, 14].map((days) => <Fragment key={days}>
              <th scope="col" className="is-num ao-metric-head" title={`${days} day profit after ads and COGS before`}
                aria-label={`${days} day profit after ads and COGS before`}>
                {days}d profit<small>Before</small></th>
              <th scope="col" className="is-num ao-metric-head" title={`${days} day profit after ads and COGS after`}
                aria-label={`${days} day profit after ads and COGS after`}>
                {days}d profit<small>After</small></th>
              <th scope="col" className="is-num ao-metric-head">{days}d ACoS<small>Before</small></th>
              <th scope="col" className="is-num ao-metric-head">{days}d ACoS<small>After</small></th>
            </Fragment>)}
            <th scope="col" className="is-num ao-spend-head" title="Spend under changed budget">Budget spend</th>
            <th scope="col" className="ao-undo-head">Undo</th>
          </>}
        </tr>
      </thead>
      <tbody>
        {rows.map((row, index) => <tr key={row.id} data-row-id={row.id} aria-selected={grid.selected === row.id}
          className={filter === "sent" && row.status === "sent" && row.kind !== APP_KIND ? "ao-row ao-change-results" : "ao-row"}
          data-surface={filter === "sent" && row.status === "sent" && row.kind !== APP_KIND ? "ads-change-result" : undefined}>
          <td className="ao-grid-marker">{offset + index + 1}</td>
          <ProductCell row={row} onOpen={onOpen} />
          <td className="ao-c-day is-num" data-field="day">{dayWords(row.day, "short")}</td>
          <td className="ao-c-campaign" data-field="campaign">
            <button type="button" className="ao-open" title={row.campaign || row.app} onClick={() => onOpen(row)}>{row.campaign || row.app}</button>
            <AdTag adType={row.adType} />
          </td>
          <ValueCells row={row} />
          <td className="ao-c-source" data-field="source">{row.decidedBy || "Decision source not recorded"}</td>
          <td className="ao-c-decision" data-field="decision">
            <span className="ao-status" data-status={row.status}>
              {decisionLabel(row.status)}</span>
          </td>
          <td className="ao-c-outcome" data-field="outcome"><Outcome row={row} /></td>
          {filter === "sent" && (row.status === "sent" && row.kind !== APP_KIND
            ? <SentResults row={row} editable={editable} undoing={undoing} resultUrl={resultUrl}
              onUndo={onUndo} onToday={onToday} />
            : <td colSpan={10} className="ao-result-note">Not applicable</td>)}
        </tr>)}
      </tbody>
      </table>
      {rows.length === 0 && <p className="ao-empty" role="status">No proposals yet</p>}
    </div>}
    {moreError && state.phase === "ready" && <Failed message={moreError} onRetry={onRetry} />}
    <Pager label="History pages" page={{ offset, total: state.phase === "ready" ? state.value.total ?? 0 : 0,
      open: 0, cursor: state.phase === "ready" ? state.value.cursor : null }}
      count={state.phase === "ready" ? state.value.items.length : 0} busy={loadingMore} onPage={onPage} />
  </div>;
}

interface ScheduleCampaign { campaign_id: string; campaign: string; ad_type: string; connection_id: string; profile_id: string }
interface ScheduleCell {
  weekday: number; day: string; hour: number; dates: string[]; reason: string | null;
  spend: number | null; orders: number | null; sales: number | null; acos: number | null;
}
export interface ScheduleReport {
  campaign_id: string; ad_type: string; connection_id: string; profile_id: string; start: string; end: string;
  state: string; reason: string | null; timezone: string | null; currency: string | null;
  attribution_window: string; source_table: string; grid: ScheduleCell[];
  validation: { ok: boolean; detail: string; days: { date: string; ok: boolean; hourly_spend: number | null;
    daily_spend: number | null; reasons: string[] }[] };
}
export interface ScheduleHeatmapProps {
  label: string; unit: string; period: string;
  series: { id: string; label: string; points: { x: string; value: number | null }[] }[];
}
/** Integrate binds the public viz/kit/charts Heatmap. */
export const OperatorScheduleKitContext = createContext<{ Heatmap: ComponentType<ScheduleHeatmapProps> } | null>(null);
const SCHEDULE_DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const SCHEDULE_METRICS = [["spend", "Spend"], ["orders", "Orders"], ["acos", "ACoS"]] as const;
type ScheduleMetric = typeof SCHEDULE_METRICS[number][0];
const scheduleKey = (row: ScheduleCampaign) => JSON.stringify([row.ad_type, row.connection_id, row.profile_id, row.campaign_id]);
const scheduleValue = (value: number | null, metric: string) => value === null ? "Unavailable"
  : value.toLocaleString(undefined, { maximumFractionDigits: metric === "orders" ? 0 : 2 }) + (metric === "acos" ? "%" : "");
const object = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value)
  ? value as Record<string, unknown> : {};
const finiteMetric = (value: unknown) => value === null || typeof value === "number" && Number.isFinite(value);

export function parseScheduleReport(value: unknown, campaign: ScheduleCampaign, start: string, end: string): ScheduleReport {
  const body = object(value), validation = object(body.validation);
  const dates: string[] = [];
  for (const day = new Date(`${start}T00:00:00Z`); day.toISOString().slice(0, 10) <= end; day.setUTCDate(day.getUTCDate() + 1)) {
    dates.push(day.toISOString().slice(0, 10));
  }
  if (body.campaign_id !== campaign.campaign_id || body.ad_type !== "sp" || campaign.ad_type !== "sp"
    || body.connection_id !== campaign.connection_id || body.profile_id !== campaign.profile_id
    || body.start !== start || body.end !== end || body.attribution_window !== "14d"
    || body.source_table !== "amzn_ads_sp_hourly" || typeof validation.ok !== "boolean"
    || !["ready", "partial", "empty", "unavailable", "unsupported"].includes(text(body.state))
    || !Array.isArray(body.grid) || body.grid.length !== 168 || !Array.isArray(validation.days)
    || validation.days.length !== dates.length || !validation.days.every((raw, index) => {
      const row = object(raw);
      return row.date === dates[index] && typeof row.ok === "boolean" && finiteMetric(row.hourly_spend)
        && finiteMetric(row.daily_spend) && Array.isArray(row.reasons) && row.reasons.every(v => typeof v === "string");
    }) || !body.grid.every((raw, index) => {
      const row = object(raw), weekday = Math.floor(index / 24);
      const selectedDates = dates.filter(date => (new Date(`${date}T00:00:00Z`).getUTCDay() + 6) % 7 === weekday);
      return row.weekday === weekday && row.day === SCHEDULE_DAYS[weekday] && row.hour === index % 24
        && JSON.stringify(row.dates) === JSON.stringify(selectedDates)
        && (row.reason === null || typeof row.reason === "string")
        && ["spend", "orders", "sales", "acos"].every(key => finiteMetric(row[key]));
    })) throw new Error("Schedule data is unavailable.");
  return body as unknown as ScheduleReport;
}

function useScheduleRead(endpoint: string | null, attempt: number, surface = "Schedule"): Load<unknown> {
  const tenant = currentTenant(), key = JSON.stringify([tenant, endpoint, attempt]);
  const [state, setState] = useState<{ key: string; value: Load<unknown> } | null>(null);
  useEffect(() => {
    if (!endpoint) return;
    let active = true;
    const controller = new AbortController();
    const timer = window.setTimeout(() => controller.abort(), 20000);
    const clear = () => { active = false; controller.abort(); setState(null); };
    const events = ["aios:tenant-changed", "aios:signed-out", UNAUTHORIZED_EVENT];
    events.forEach(event => window.addEventListener(event, clear));
    setState({ key, value: { phase: "loading" } });
    void fetch(endpoint, { method: "GET", credentials: CREDENTIALS, cache: "no-store", signal: controller.signal })
      .then(async response => {
        if (!response.ok) throw new Error([401, 403, 404].includes(response.status)
          ? `No permission to view this ${surface}` : `${surface} could not be loaded`);
        const value: unknown = await response.json();
        if (active && tenant === currentTenant()) setState({ key, value: { phase: "ready", value } });
      }).catch((error: unknown) => {
        if (active && tenant === currentTenant()) setState({ key, value: { phase: "error",
          message: error instanceof Error ? error.message : `${surface} could not be loaded` } });
      }).finally(() => window.clearTimeout(timer));
    return () => { active = false; controller.abort(); window.clearTimeout(timer);
      events.forEach(event => window.removeEventListener(event, clear)); };
  }, [endpoint, attempt, tenant, key, surface]);
  return state?.key === key ? state.value : { phase: "loading" };
}

export function ScheduleFigures({ report, metric, Heatmap }: { report: ScheduleReport; metric: ScheduleMetric;
  Heatmap?: ComponentType<ScheduleHeatmapProps> }) {
  const ref = useRef<HTMLTableElement>(null);
  const label = SCHEDULE_METRICS.find(([key]) => key === metric)![1];
  const series = SCHEDULE_DAYS.map((day, weekday) => ({ id: String(weekday), label: day,
    points: report.grid.filter(cell => cell.weekday === weekday).map(cell => ({
      x: `${String(cell.hour).padStart(2, "0")}:00`, value: cell[metric] })) }));
  const navigate = (event: KeyboardEvent<HTMLTableElement>) => {
    const cells = Array.from(ref.current?.querySelectorAll<HTMLTableCellElement>("tbody td") ?? []);
    const index = cells.indexOf(event.target as HTMLTableCellElement);
    const jump = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: 24, ArrowUp: -24 }[event.key];
    if (jump === undefined && event.key !== "Home" && event.key !== "End") return;
    event.preventDefault();
    const next = cells[event.key === "Home" ? 0 : event.key === "End" ? cells.length - 1
      : Math.max(0, Math.min(cells.length - 1, index < 0 ? 0 : index + jump!))];
    next?.focus(); next?.scrollIntoView({ block: "nearest", inline: "nearest" });
  };
  return <div className="ao-schedule-figures">
    <p className="ao-schedule-context">{report.start} to {report.end} · {report.timezone || "Timezone unavailable"}
      {report.currency ? ` · ${report.currency}` : ""} · 14d attribution</p>
    {report.reason && <p role="status">{report.reason}</p>}
    {report.validation.ok && Heatmap ? <Heatmap label={`${label} by weekday and hour`} series={series}
      unit={metric === "acos" ? "percent" : metric === "spend" ? report.currency || "money" : "count"}
      period={`${report.start} to ${report.end}`} />
      : <p role="status">{!report.validation.ok ? "Daily totals need review" : "Charts unavailable"}</p>}
    <section className="ao-grid-shell ao-schedule-grid" data-surface="operator-schedule-grid">
      <div className="ao-grid-toolbar"><span className="ao-grid-view"><ModeIcon mode="grid" />Grid view</span>
        <span>{label}</span></div>
      <div className="ao-grid-viewport"><table ref={ref} role="grid" tabIndex={0} onKeyDown={navigate}
        className="ao-table" aria-label={`${label} by weekday and hour`}>
        <thead><tr><th scope="col">Weekday</th>{Array.from({ length: 24 }, (_, hour) =>
          <th key={hour} scope="col" className="is-num">{String(hour).padStart(2, "0")}:00</th>)}</tr></thead>
        <tbody>{SCHEDULE_DAYS.map((day, weekday) => <tr key={day} className="ao-row"><th scope="row">{day}</th>
          {report.grid.filter(cell => cell.weekday === weekday).map(cell => <td key={cell.hour} tabIndex={-1}
            className="is-num" data-weekday={weekday} data-hour={cell.hour} data-metric={metric}
            title={cell.reason || cell.dates.join(", ")}>{scheduleValue(cell[metric], metric)}</td>)}</tr>)}</tbody>
      </table></div><div className="ao-grid-footer">Profile time · Missing cells stay unavailable</div>
    </section>
    <details data-surface="operator-schedule-validation"><summary>Daily validation</summary>
      {report.validation.days.map(day => <p key={day.date} data-date={day.date} data-ok={day.ok}>
        {day.date}: {scheduleValue(day.hourly_spend, "spend")} hourly / {scheduleValue(day.daily_spend, "spend")} daily.
        {day.ok ? " Within 2%." : ` ${day.reasons.join(" ")}`}</p>)}
    </details>
  </div>;
}

function ScheduleRecords({ title, records, runs, editable, busy, onApprove, onSwitch }: {
  title: string; records: Record<string, unknown>[]; runs?: boolean; editable: boolean; busy: boolean;
  onApprove: (id: string) => void; onSwitch: (id: string, enabled: boolean) => void;
}) {
  const grid = useGridSelection();
  const display = (value: unknown) => typeof value === "number" && Number.isFinite(value)
    ? value.toLocaleString(undefined, { maximumFractionDigits: 2 }) : text(value) || "Unknown";
  return <section className="ao-grid-shell ao-schedule-records" data-surface={runs ? "operator-schedule-runs" : "operator-schedule-records"}>
    <div className="ao-grid-toolbar"><span>{title}</span><span>{records.length} on this page</span></div>
    <div className="ao-grid-viewport"><table {...grid.table} className="ao-table" aria-label={title}>
      <thead><tr><th scope="col">Campaign</th><th scope="col">Connection</th><th scope="col">Timing</th>
        <th scope="col">Change</th><th scope="col">Approval</th><th scope="col">Status</th></tr></thead>
      <tbody>{records.map(row => {
        const id = text(row.id), rules = (Array.isArray(row.rules) ? row.rules : [row.rule]).map(object);
        const weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
        const timing = rules.map(rule => `${weekdays[Number(rule.weekday)]} ${String(rule.hour).padStart(2, "0")}:00`).join(", ");
        const change = rules[0]?.action === "set_bid" ? `Bid ${display(rules[0]?.value)}` : "Pause ads";
        return <tr key={id} data-row-id={id} aria-selected={grid.selected === id} className="ao-row" data-status={runs ? text(row.status) : row.enabled ? "on" : "off"}>
          <td title={text(row.campaign_id)}>{text(row.campaign_id)}</td>
          <td title={`${text(row.connection_id)} / ${text(row.profile_id)}`}>{text(row.connection_id)} / {text(row.profile_id)}</td>
          <td title={`${timing} ${text(row.timezone)}`}>{timing} {text(row.timezone)}</td>
          <td title={runs ? `${display(row.previous_value)} to ${display(row.new_value)} · ${text(row.source)}` : change}>
            {runs ? `${display(row.previous_value)} to ${display(row.new_value)}` : change}</td>
          <td title={`${text(row.approved_by)} ${text(row.approved_at)}`}>{text(row.approved_by) || "Needs approval"}</td>
          <td title={runs ? `${text(row.cause)} ${text(row.outcome_at) || text(row.claimed_at)}` : undefined}>
            {runs ? <span>{text(row.status)} · {text(row.outcome_at) || text(row.claimed_at)}{row.cause ? ` · ${text(row.cause)}` : ""}</span>
              : <><span>{row.enabled ? "On" : "Off"}</span>{editable && (!row.approved_by
                ? <button type="button" className="ao-button" disabled={busy} aria-label={`Approve schedule ${id}`}
                  onClick={() => onApprove(id)}>Approve once</button>
                : <button type="button" className="ao-button" disabled={busy} aria-label={`Switch schedule ${id} ${row.enabled ? "off" : "on"}`}
                  onClick={() => onSwitch(id, !row.enabled)}>{row.enabled ? "Turn off" : "Turn on"}</button>)}</>}
          </td>
        </tr>;
      })}</tbody>
    </table></div>
    {!records.length && <p className="ao-empty" role="status">{runs ? "No schedule runs yet" : "No schedules yet"}</p>}
  </section>;
}

function ScheduleManager({ appId, campaign, canEdit }: { appId: string; campaign?: ScheduleCampaign; canEdit?: boolean }) {
  const [attempt, setAttempt] = useState(0), [busy, setBusy] = useState(false), [message, setMessage] = useState("");
  const [schedulePages, setSchedulePages] = useState<(string | null)[]>([null]);
  const [runPages, setRunPages] = useState<(string | null)[]>([null]);
  const [targetPages, setTargetPages] = useState<(string | null)[]>([null]);
  const [action, setAction] = useState("set_bid"), [bid, setBid] = useState(""), [entity, setEntity] = useState("");
  const [weekdays, setWeekdays] = useState<number[]>([]), [hours, setHours] = useState<number[]>([]);
  const alive = useRef(true), pending = useRef(false), tenant = currentTenant();
  useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
  const endpoint = (path: string, extra: Record<string, string> = {}) => `${API_V1}/app-kinds/amazon_operator/${path}?`
    + new URLSearchParams({ app: appId, ...extra });
  const schedules = useScheduleRead(endpoint("schedules", { ...(schedulePages.at(-1) ? { cursor: schedulePages.at(-1)! } : {}) }), attempt);
  const runs = useScheduleRead(endpoint("schedule-runs", { ...(runPages.at(-1) ? { cursor: runPages.at(-1)! } : {}) }), attempt);
  const targets = useScheduleRead(campaign ? endpoint("schedule-targets", { ...campaign, action,
    ...(targetPages.at(-1) ? { cursor: targetPages.at(-1)! } : {}) }) : null, attempt);
  const body = schedules.phase === "ready" ? object(schedules.value) : {};
  const runBody = runs.phase === "ready" ? object(runs.value) : {};
  const targetBody = targets.phase === "ready" ? object(targets.value) : {};
  const rows = (value: unknown) => (Array.isArray(value) ? value : []).map(object);
  const editable = canEdit === true && body.canEdit === true;
  const choices = rows(targetBody.items), selected = choices.find(row => JSON.stringify(row) === entity);
  const mutate = async (path: string, method: string, payload?: unknown) => {
    if (!editable || pending.current || tenant !== currentTenant()) return;
    pending.current = true; setBusy(true); setMessage("");
    const controller = new AbortController(), timer = window.setTimeout(() => controller.abort(), 20000);
    try {
      const response = await fetch(endpoint(path), { method, credentials: CREDENTIALS, signal: controller.signal,
        headers: { "Content-Type": "application/json" }, ...(payload === undefined ? {} : { body: JSON.stringify(payload) }) });
      if (!response.ok) throw new Error("The schedule could not be saved. Check its campaign and try again.");
      if (alive.current && tenant === currentTenant()) { setAttempt(value => value + 1); setMessage("Saved"); }
    } catch (error) {
      if (alive.current && tenant === currentTenant()) setMessage(error instanceof Error ? error.message : "Schedule unavailable");
    } finally { window.clearTimeout(timer); pending.current = false; if (alive.current) setBusy(false); }
  };
  const pageButtons = (label: string, page: Record<string, unknown>, stack: (string | null)[], set: (value: (string | null)[]) => void) =>
    <nav className="ao-bar ao-grid-footer" aria-label={label}>
      <button type="button" className="ao-button" disabled={busy || stack.length === 1} onClick={() => set(stack.slice(0, -1))}>Previous</button>
      <button type="button" className="ao-button" disabled={busy || !text(page.cursor)} onClick={() => set([...stack, text(page.cursor)])}>Next</button>
    </nav>;
  return <section className="ao-schedule-manager" data-surface="operator-schedule-manager">
    {schedules.phase === "loading" ? <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading schedules" />
      : schedules.phase === "error" ? <Failed message={schedules.message} onRetry={() => setAttempt(v => v + 1)} /> : <>
        <div className="ao-bar"><h3>Schedules</h3>
          <label className="ao-schedule-switch"><input type="checkbox" role="switch" aria-label="App schedules" checked={body.enabled === true}
            disabled={!editable || busy} onChange={event => void mutate("schedule-switch", "PUT", { enabled: event.target.checked })} />
            App schedules {body.enabled === true ? "on" : "off"}</label></div>
        {!editable && <p role="status">View only</p>}
        {editable && campaign && <form className="ao-schedule-form" data-surface="operator-schedule-create" onSubmit={event => {
          event.preventDefault();
          if (!selected || !weekdays.length || !hours.length) return;
          const rules = weekdays.flatMap(weekday => hours.map(hour => ({ weekday, hour, action,
            value: action === "set_bid" ? Number(bid) : "paused", ad_group_id: selected.ad_group_id,
            ...(action === "set_bid" ? { target_id: selected.target_id } : { ad_ids: [selected.ad_id] }) })));
          void mutate("schedules", "POST", { ...campaign, rules });
        }}>
          <div className="ao-bar">
            <label className="ao-field">Change<select className="ao-select" aria-label="Schedule action" value={action} disabled={busy}
              onChange={event => { setAction(event.target.value); setEntity(""); setTargetPages([null]); }}>
              <option value="set_bid">Set bid</option><option value="pause_ads">Pause ads</option></select></label>
            <label className="ao-field">Target<select className="ao-select" aria-label="Schedule target" value={entity} disabled={busy || targets.phase !== "ready"}
              onChange={event => setEntity(event.target.value)}><option value="">Choose target</option>
              {choices.map(row => <option key={JSON.stringify(row)} value={JSON.stringify(row)}>
                {text(row.ad_group_id)} / {text(row.target_id) || text(row.ad_id)}</option>)}</select></label>
            {action === "set_bid" && <label className="ao-field">Bid<input className="ao-select" aria-label="Schedule bid" type="number" min="0.01" step="0.01"
              required value={bid} disabled={busy} onChange={event => setBid(event.target.value)} /></label>}
          </div>
          {targets.phase === "error" && <Failed message={targets.message} onRetry={() => setAttempt(v => v + 1)} />}
          {targets.phase === "ready" && pageButtons("Schedule target pages", targetBody, targetPages, value => { setTargetPages(value); setEntity(""); })}
          <fieldset disabled={busy}><legend>Weekdays</legend><div className="ao-bar">
            {["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"].map((label, value) =>
              <label key={label}><input type="checkbox" checked={weekdays.includes(value)} onChange={event =>
                setWeekdays(values => event.target.checked ? [...values, value] : values.filter(day => day !== value))} />{label}</label>)}
          </div></fieldset>
          <fieldset disabled={busy}><legend>Hours in Ads profile time</legend><div className="ao-schedule-hours">
            {Array.from({ length: 24 }, (_, hour) => <label key={hour}><input type="checkbox" aria-label={`Hour ${hour}`} checked={hours.includes(hour)}
              onChange={event => setHours(values => event.target.checked ? [...values, hour] : values.filter(value => value !== hour))} />
              {String(hour).padStart(2, "0")}:00</label>)}
          </div></fieldset>
          <button type="submit" className="ao-button" disabled={busy || !selected || !weekdays.length || !hours.length || (action === "set_bid" && !(Number(bid) > 0))}>
            Create schedule</button>
        </form>}
        <p role="status" aria-live="polite">{message}</p>
        <ScheduleRecords title="Saved schedules" records={rows(body.items)} editable={editable} busy={busy}
          onApprove={id => void mutate(`schedules/${id}/approve`, "POST")}
          onSwitch={(id, enabled) => void mutate(`schedules/${id}/enabled`, "PUT", { enabled })} />
        {pageButtons("Saved schedule pages", body, schedulePages, setSchedulePages)}
      </>}
    {runs.phase === "loading" ? <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading schedule runs" />
      : runs.phase === "error" ? <Failed message={runs.message} onRetry={() => setAttempt(v => v + 1)} /> : <>
        <ScheduleRecords title="Schedule runs" records={rows(runBody.items)} runs editable={false} busy={busy} onApprove={() => {}} onSwitch={() => {}} />
        {pageButtons("Schedule run pages", runBody, runPages, setRunPages)}
      </>}
  </section>;
}

export function SchedulePanel({ appId, end: fixedEnd, canEdit }: { appId: string; end?: string; canEdit?: boolean }) {
  const kit = useContext(OperatorScheduleKitContext);
  const [days, setDays] = useState(7), [attempt, setAttempt] = useState(0);
  const [defaultEnd] = useState(() => new Date(Date.now() - 86400000).toISOString().slice(0, 10));
  const end = fixedEnd ?? defaultEnd;
  const first = new Date(`${end}T00:00:00Z`); first.setUTCDate(first.getUTCDate() - days + 1);
  const start = first.toISOString().slice(0, 10);
  const [cursors, setCursors] = useState<(string | null)[]>([null]);
  const [chosen, setChosen] = useState("");
  const [metric, setMetric] = useState<ScheduleMetric>("spend");
  const endpoint = (path: string, extra: Record<string, string> = {}) => `${API_V1}/app-kinds/amazon_operator/${path}?`
    + new URLSearchParams({ app: appId, start, end, ...extra });
  const campaigns = useScheduleRead(endpoint("overview", { limit: "50", sort: "campaign",
    ...(cursors.at(-1) ? { cursor: cursors.at(-1)! } : {}) }), attempt);
  const page = campaigns.phase === "ready" ? object(object(campaigns.value).campaigns) : {};
  const rows = (Array.isArray(page.items) ? page.items : []).map(object).filter(row => row.ad_type === "sp"
    && [row.campaign_id, row.connection_id, row.profile_id].every(value => typeof value === "string" && !!value)) as unknown as ScheduleCampaign[];
  const campaign = rows.find(row => scheduleKey(row) === chosen) ?? rows[0];
  const load = useScheduleRead(campaign ? endpoint("schedule-grid", { campaign_id: campaign.campaign_id,
    ad_type: campaign.ad_type, connection_id: campaign.connection_id, profile_id: campaign.profile_id }) : null, attempt);
  let report: ScheduleReport | null = null, invalid = false;
  if (load.phase === "ready" && campaign) {
    try { report = parseScheduleReport(load.value, campaign, start, end); } catch { invalid = true; }
  }
  const retry = () => setAttempt(value => value + 1);
  return <section className="ao-schedule" data-surface="operator-schedule">
    <div className="ao-bar ao-schedule-controls">
      <label className="ao-field"><span>Period</span><select className="ao-select" aria-label="Schedule period" value={days}
        onChange={event => { setDays(Number(event.target.value)); setCursors([null]); setChosen(""); }}>
        {[7, 14, 30, 90].map(value => <option key={value} value={value}>Last {value} days</option>)}
      </select></label>
      <label className="ao-field ao-schedule-campaign"><span>Campaign</span><select className="ao-select" aria-label="Schedule campaign"
        value={campaign ? scheduleKey(campaign) : ""} disabled={!rows.length}
        onChange={event => setChosen(event.target.value)}>
        {!rows.length && <option value="">No Sponsored Products campaigns on this page</option>}
        {rows.map(row => <option key={scheduleKey(row)} value={scheduleKey(row)}>
          {row.campaign || row.campaign_id} ({row.connection_id}, {row.profile_id})</option>)}
      </select></label>
      <label className="ao-field"><span>Metric</span><select className="ao-select" aria-label="Schedule metric" value={metric}
        onChange={event => setMetric(event.target.value as ScheduleMetric)}>
        {SCHEDULE_METRICS.map(([key, label]) => <option key={key} value={key}>{label}</option>)}
      </select></label>
    </div>
    {campaigns.phase === "loading" ? <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading campaigns" />
      : campaigns.phase === "error" ? <Failed message={campaigns.message} onRetry={retry} />
      : <>
        <nav className="ao-bar" aria-label="Schedule campaign pages">
          <button type="button" className="ao-button" disabled={cursors.length === 1}
            onClick={() => { setCursors(stack => stack.slice(0, -1)); setChosen(""); }}>Previous</button>
          <span>{num(page.total)?.toLocaleString() ?? "Unavailable"} campaigns</span>
          <button type="button" className="ao-button" disabled={!text(page.cursor)}
            onClick={() => { setCursors(stack => [...stack, text(page.cursor)]); setChosen(""); }}>Next</button>
        </nav>
        <ScheduleManager key={campaign ? scheduleKey(campaign) : appId} appId={appId} campaign={campaign} canEdit={canEdit} />
        {!campaign ? <p role="status">Hourly data is available for Sponsored Products only.</p>
          : load.phase === "loading" ? <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading Schedule" />
            : load.phase === "error" ? <Failed message={load.message} onRetry={retry} />
              : invalid ? <Failed message="Schedule data is unavailable." onRetry={retry} />
                : report && <ScheduleFigures report={report} metric={metric} Heatmap={kit?.Heatmap} />}
      </>}
  </section>;
}

const changeEndpoint = (appId: string, path: string, params: Record<string, string> = {}) =>
  `${API_V1}/app-kinds/amazon_operator/${path}?${new URLSearchParams({ app: appId, ...params })}`;
const changeScope = (row: Record<string, unknown>): Record<string, string> => Object.fromEntries(
  ["connection_id", "profile_id", "ad_type", "campaign_id", "currency"].map(key => [key, text(row[key])]));
const changeKey = (row: Record<string, unknown>) => JSON.stringify(changeScope(row));

function ChangePageButtons({ label, pages, cursor, onPage, total, countNoun = "records" }: {
  label: string; pages: string[]; cursor: string; onPage: (pages: string[]) => void; total?: number | null; countNoun?: string;
}) {
  return <nav className="ao-bar ao-grid-footer" aria-label={label}>
    <button type="button" className="ao-button" disabled={pages.length === 1}
      onClick={() => onPage(pages.slice(0, -1))}>Previous</button>
    <span>{total == null ? `Page ${pages.length}` : `${total.toLocaleString()} ${countNoun}`}</span>
    <button type="button" className="ao-button" disabled={!cursor}
      onClick={() => onPage([...pages, cursor])}>Next</button>
  </nav>;
}

function useChangeCampaigns(appId: string, all: boolean) {
  const [pages, setPages] = useState([""]), [chosen, setChosen] = useState("");
  const [attempt, setAttempt] = useState(0);
  const load = useScheduleRead(changeEndpoint(appId, "pacing-campaigns", { cursor: pages.at(-1)!, limit: "50" }), attempt, "campaign list");
  const body = load.phase === "ready" ? object(load.value) : {};
  const rows = (Array.isArray(body.items) ? body.items : []).map(object);
  const campaign = rows.find(row => changeKey(row) === chosen) ?? (all ? undefined : rows[0]);
  const controls = <>
    <label className="ao-field ao-change-campaign">Campaign<select className="ao-select" aria-label="Change campaign"
      value={campaign ? changeKey(campaign) : ""} disabled={!rows.length}
      onChange={event => setChosen(event.target.value)}>
      {all && <option value="">All campaigns</option>}
      {!all && !rows.length && <option value="">No campaigns</option>}
      {rows.map(row => <option key={changeKey(row)} value={changeKey(row)}>
        {text(row.campaign) || text(row.campaign_id)} ({text(row.ad_type)}, {text(row.connection_id)}, {text(row.profile_id)}, {text(row.currency) || "Currency not recorded"})
      </option>)}
    </select></label>
    {load.phase === "error" && <Failed message={load.message} onRetry={() => setAttempt(v => v + 1)} />}
    {load.phase === "loading" && <span className="lp-spin" role="status" aria-label="Loading campaign filters" />}
    <ChangePageButtons label="Change campaign pages" pages={pages} cursor={text(body.cursor)} total={num(body.total)} countNoun="campaigns"
      onPage={value => { setPages(value); setChosen(""); }} />
  </>;
  return { campaign, controls, load };
}

const changeType = (operation: unknown) => ({ set_bid: "Bid", set_daily_budget: "Daily budget", pause_ads: "Pause",
  enable_ads: "Enable", add_negative_keyword: "Negative exact" }[text(operation)] || "Change");

export function ChangeLogPanel({ appId }: { appId: string }) {
  const { campaign, controls } = useChangeCampaigns(appId, true);
  const [hidden, setHidden] = useState(() => defaultHiddenColumns(OPERATOR_CHANGE_LOG_COLUMNS));
  const [source, setSource] = useState(""), [pages, setPages] = useState([""]), [attempt, setAttempt] = useState(0);
  const scope = campaign ? changeScope(campaign) : {};
  const identity = JSON.stringify([source, scope]);
  const [pageIdentity, setPageIdentity] = useState(identity);
  // A filter change never sends the preceding filter's cursor.
  const currentPages = pageIdentity === identity ? pages : [""];
  useEffect(() => { setPages([""]); setPageIdentity(identity); }, [identity]);
  const load = useScheduleRead(changeEndpoint(appId, "change-log", { ...scope, source, limit: "50", cursor: currentPages.at(-1)! }), attempt, "change log");
  const body = load.phase === "ready" ? object(load.value) : {};
  const rows = (Array.isArray(body.items) ? body.items : []).map(object);
  const grid = useGridSelection();
  return <section className="ao-grid-shell ao-change-log" data-surface="operator-change-log" data-hidden={hidden.join(" ")}>
    <div className="ao-grid-toolbar">
      <span className="ao-grid-view"><ModeIcon mode="grid" size={16} />Grid view</span>
      <FieldControls fields={operatorFields(OPERATOR_CHANGE_LOG_COLUMNS.filter(column => column.key !== "product")
        .map(column => [column.key, column.label] as const))} hidden={hidden} onHidden={setHidden} />
      <label className="ao-field">Source<select className="ao-select" aria-label="Change source" value={source}
        onChange={event => setSource(event.target.value)}><option value="">All sources</option>
        {["Inbox", "Undo", "Schedule", "Wasted spend"].map(value => <option key={value}>{value}</option>)}
      </select></label>{controls}
    </div>
    {load.phase === "loading" ? <Skeleton /> : load.phase === "error"
      ? <Failed message={load.message} onRetry={() => setAttempt(v => v + 1)} /> : <>
      <div className="ao-grid-viewport"><table {...grid.table} className="ao-table ao-change-table" aria-label="Ad change log"
        style={{ width: gridWidth(OPERATOR_CHANGE_LOG_COLUMNS, hidden) }}>
        <thead><tr><ColumnHeaders columns={OPERATOR_CHANGE_LOG_COLUMNS} sized /></tr></thead>
        <tbody>{rows.map(row => <tr key={text(row.id)} data-row-id={text(row.id)} aria-selected={grid.selected === text(row.id)}>
          <td className="ao-c-product" data-field="product">
            <span className="ao-product-picture" role="img" aria-label="Product image not supplied" />
            <span className="ao-product-copy">{text(row.sku) || text(row.asin) || "Product not recorded"}
              <small>{text(row.asin) || text(row.sku) || "No SKU or ASIN"}</small></span>
          </td>
          <td data-field="at">{text(row.at) ? <time dateTime={text(row.at)}>{new Date(text(row.at)).toLocaleString(undefined, { timeZone: "UTC" })} UTC</time> : "Not recorded"}</td>
          <td data-field="operation">{changeType(row.operation)}</td>
          <td className="ao-c-value is-num" data-field="old_value">{operatorValueText(scalar(row.old_value), text(row.value_unit), text(row.currency), text(row.values_reason))}</td>
          <td className="ao-c-value is-num" data-field="new_value">{operatorValueText(scalar(row.new_value), text(row.value_unit), text(row.currency), text(row.values_reason))}</td>
          <td className={`ao-c-value ao-c-delta is-num${typeof row.value_change === "number"
            ? row.value_change > 0 ? " is-up" : row.value_change < 0 ? " is-down" : "" : ""}`} data-field="value_change">
            {operatorValueText(scalar(row.value_change), text(row.value_unit), text(row.currency), text(row.values_reason), true)}</td>
          <td data-field="source">{text(row.source) || "Source not recorded"}
            <small>{text(row.approver) || "Decision source not recorded"}</small>
            {text(row.evidence_table) && <small>{text(row.evidence_table)}</small>}</td>
          <td data-field="approver">{text(row.approver) || "Decision source not recorded"}</td>
          <td data-field="campaign">{text(row.campaign) || "Not recorded"}<small>{AD_TAGS[text(row.ad_type)] || "Ad type not recorded"}</small></td>
          <td data-field="account">{row.binding_recorded === true ? <>{text(row.connection_id)}<small>{text(row.profile_id)}</small></> : "Not recorded"}</td>
          <td data-field="status"><span className="ao-status" data-status={text(row.status)}>{row.status === "sent" ? "Sent" : row.status === "refused" ? "Refused" : "Unknown"}</span>
            {text(row.cause) && <small>{text(row.cause)}</small>}</td><td data-field="currency">{text(row.currency) || "Not recorded"}</td>
        </tr>)}</tbody>
      </table>{!rows.length && <p className="ao-empty" role="status">No changes recorded</p>}</div>
      <ChangePageButtons label="Change log pages" pages={currentPages} cursor={text(body.cursor)} total={num(body.total)} onPage={setPages} />
    </>}
  </section>;
}

interface PacingDay { date: string; budget: number | null; spend: number | null }
interface PacingReport { month: string; timezone: string; currency: string; days: PacingDay[];
  recordedSpend: number | null; monthlySpend: number | null; monthlyBudget: number | null; budgetDays: number; spendDays: number }
function parsePacing(raw: unknown, campaign: Record<string, unknown>, month: string): PacingReport {
  const row = object(raw), validation = object(row.validation);
  if (validation.ok !== true || !text(row.timezone) || !text(row.currency) || !text(row.month)
    || (month && row.month !== month) || !Array.isArray(row.days)
    || Object.entries(changeScope(campaign)).some(([key, value]) => row[key] !== value)) {
    throw new Error(text(validation.reason) || "Budget pacing could not be validated.");
  }
  return { month: text(row.month), timezone: text(row.timezone), currency: text(row.currency),
    days: row.days.map(value => { const day = object(value); return { date: text(day.date), budget: num(day.budget), spend: num(day.spend) }; }),
    recordedSpend: num(row.recorded_spend), monthlySpend: num(row.monthly_spend), monthlyBudget: num(row.monthly_budget),
    budgetDays: num(row.budget_days) ?? 0, spendDays: num(row.spend_days) ?? 0 };
}

function PacingCalendar({ report }: { report: PacingReport }) {
  const first = new Date(`${report.month}-01T00:00:00Z`);
  const pad = (first.getUTCDay() + 6) % 7;
  const label = first.toLocaleDateString(undefined, { month: "long", year: "numeric", timeZone: "UTC" });
  return <>
    <div className="ao-bar ao-pacing-heading"><h3>{label}</h3><span>{report.timezone} · {report.currency}</span></div>
    <div className="ao-pacing-summary">
      {[["Monthly budget", report.monthlyBudget], ["Monthly spend", report.monthlySpend], ["Recorded spend", report.recordedSpend]].map(([label, value]) =>
        <div className="ao-pacing-kpi" key={String(label)}><span>{label}</span><strong>{typeof value === "number" ? money(value) : "Unavailable"}</strong></div>)}
    </div>
    <p className="ao-pacing-basis" role="status">{report.budgetDays} of {report.days.length} budgets recorded · {report.spendDays} of {report.days.length} spend days · Recorded spend ties to the selected Ads report</p>
    <div className="ao-pacing-viewport"><div className="ao-pacing-calendar" role="table" aria-label={`${label} budget pacing`}>
      <div className="ao-pacing-week" role="row">{["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"].map(day =>
        <div key={day} role="columnheader">{day}</div>)}</div>
      {Array.from({ length: Math.ceil((pad + report.days.length) / 7) }, (_, week) =>
        <div className="ao-pacing-week" role="row" key={week}>{Array.from({ length: 7 }, (_, weekday) => {
          const day = report.days[week * 7 + weekday - pad];
          return day ? <div role="cell" className="ao-pacing-day" data-date={day.date} key={weekday}>
            <time dateTime={day.date}>{Number(day.date.slice(-2))}</time>
            <span className="ao-pacing-budget">Budget <strong>{recordedValue(day.budget)}</strong></span>
            <span className="ao-pacing-spend">Spend <strong>{day.spend == null ? "Unavailable" : money(day.spend)}</strong></span>
          </div> : <div role="cell" className="ao-pacing-day is-empty" key={weekday} />;
        })}</div>)}
    </div></div>
  </>;
}

export function BudgetPacingPanel({ appId }: { appId: string }) {
  const { campaign, controls, load: campaigns } = useChangeCampaigns(appId, false);
  const [month, setMonth] = useState(""), [monthPages, setMonthPages] = useState([""]), [attempt, setAttempt] = useState(0);
  const scope = campaign ? changeScope(campaign) : null;
  const identity = JSON.stringify(scope);
  const [selectedIdentity, setSelectedIdentity] = useState(identity);
  const selectedMonth = identity === selectedIdentity ? month : "";
  const pages = identity === selectedIdentity ? monthPages : [""];
  useEffect(() => { setMonth(""); setMonthPages([""]); setSelectedIdentity(identity); }, [identity]);
  const months = useScheduleRead(scope ? changeEndpoint(appId, "pacing-months", { ...scope, cursor: pages.at(-1)!, limit: "12" }) : null, attempt, "month list");
  const monthBody = months.phase === "ready" ? object(months.value) : {};
  const available = Array.isArray(monthBody.items) ? monthBody.items.map(text) : [];
  const load = useScheduleRead(scope ? changeEndpoint(appId, "budget-pacing", { ...scope, ...(selectedMonth ? { month: selectedMonth } : {}) }) : null, attempt, "budget pacing");
  let report: PacingReport | null = null, error = "";
  if (load.phase === "ready" && campaign) {
    try { report = parsePacing(load.value, campaign, selectedMonth); } catch (cause) { error = cause instanceof Error ? cause.message : "Budget pacing is unavailable."; }
  }
  const shownMonth = selectedMonth || report?.month || text(monthBody.current_month);
  return <section className="ao-budget-pacing" data-surface="operator-budget-pacing">
    <div className="ao-grid-toolbar">{controls}
      <label className="ao-field">Month<select className="ao-select" aria-label="Pacing month" value={shownMonth}
        disabled={months.phase !== "ready"} onChange={event => setMonth(event.target.value)}>
        {[...new Set([shownMonth, ...available])].filter(Boolean).map(value => <option key={value}>{value}</option>)}
      </select></label>
      <ChangePageButtons label="Pacing month pages" pages={pages} cursor={text(monthBody.cursor)}
        onPage={value => { setMonthPages(value); setMonth(""); }} />
    </div>
    {months.phase === "error" && <Failed message={months.message} onRetry={() => setAttempt(v => v + 1)} />}
    {campaigns.phase === "ready" && !campaign ? <p role="status">No campaign history is available</p>
      : load.phase === "loading" ? <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading budget pacing" />
        : load.phase === "error" || error ? <Failed message={error || (load.phase === "error" ? load.message : "Budget pacing is unavailable.")}
          onRetry={() => setAttempt(v => v + 1)} /> : report && <PacingCalendar report={report} />}
  </section>;
}

function OperatorBody({ application, canEdit }: {
  application: OperatorApplication; canEdit?: boolean;
}) {
  const dashboardAdapter = useContext(OperatorDashboardContext);
  const appId = application.id;
  const url = useCallback((path: string, params: Record<string, string> = {}) => {
    const query = new URLSearchParams({ app: appId, ...params });
    return `${API_V1}/app-kinds/amazon_operator${path}?${query.toString()}`;
  }, [appId]);
  const [tab, setTab] = useState<OperatorTab>("today");
  const [today, setToday] = useState<Load<TodayScreen>>({ phase: "loading" });
  const [todayAttempt, setTodayAttempt] = useState(0);
  const [todayBusy, setTodayBusy] = useState(false);
  const [todayError, setTodayError] = useState("");
  const [offsets, setOffsets] = useState({ items: 0, apps: 0, held: 0 });
  const [historyOffset, setHistoryOffset] = useState(0);
  const [search, setSearch] = useState("");
  const [query, setQuery] = useState("");
  const [history, setHistory] = useState<Load<HistoryPage>>({ phase: "loading" });
  const [historyAttempt, setHistoryAttempt] = useState(0);
  const [filter, setFilter] = useState("");
  const [loadingMore, setLoadingMore] = useState(false);
  const [moreError, setMoreError] = useState("");
  const [excluded, setExcluded] = useState<Set<string>>(() => new Set());
  const [settled, setSettled] = useState<Set<string>>(() => new Set());
  const [sending, setSending] = useState(false);
  const [decideError, setDecideError] = useState("");
  const reviewedRemovals = useRef(new Map<string, ReviewedRemoval>());
  const noteReviewed = useCallback((id: string, value: ReviewedRemoval) => { reviewedRemovals.current.set(id, value); }, []);
  const [dismissing, setDismissing] = useState<Dismissing | null>(null);
  const [undoing, setUndoing] = useState(false);
  const undoPending = useRef(false);
  const [undoNotice, setUndoNotice] = useState("");
  const [opened, setOpened] = useState<{ row: Proposal; from: "today" | "history" } | null>(null);
  const todayTab = useRef<HTMLButtonElement | null>(null);
  const sharedTabStrip = useRef<HTMLDivElement | null>(null);
  const focusTodayPending = useRef(false);
  const opener = useRef<HTMLElement | null>(null);
  const alive = useRef(true);
  useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);

  useEffect(() => {
    if (tab !== "today" || !focusTodayPending.current) return;
    focusTodayPending.current = false;
    // Shared tabs expose semantics, so focus the selected tab after Today commits.
    sharedTabStrip.current?.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]')?.focus();
  }, [tab, todayAttempt]);

  useEffect(() => {
    if (search === query) return;
    const timer = window.setTimeout(() => {
      setQuery(search); setOffsets({ items: 0, apps: 0, held: 0 }); setHistoryOffset(0);
    }, 250);
    return () => window.clearTimeout(timer);
  }, [search, query]);

  useEffect(() => {
    if (sending || dismissing || tab !== "today") return;
    const timer = window.setInterval(() => setTodayAttempt((n) => n + 1), 30000);
    return () => window.clearInterval(timer);
  }, [sending, dismissing, tab]);

  useEffect(() => { setSettled(new Set()); setExcluded(new Set()); }, [offsets, query]);

  useEffect(() => {
    const controller = new AbortController();
    setTodayBusy(true);
    setTodayError("");
    void fetch(url("/today", { cursor: String(offsets.items), app_cursor: String(offsets.apps),
      held_cursor: String(offsets.held), limit: String(HISTORY_PAGE), q: query }), { credentials: CREDENTIALS, signal: controller.signal })
      .then((response) => readJson(response, "Today's proposals could not be loaded."))
      .then((body) => { if (!controller.signal.aborted) setToday({ phase: "ready", value: parseToday(body) }); })
      .catch((reason: unknown) => {
        if (!controller.signal.aborted) {
          const message = reason instanceof Error ? reason.message : "Today's proposals could not be loaded.";
          setTodayError(message);
          setToday((current) => current.phase === "ready" ? current : { phase: "error", message });
        }
      }).finally(() => { if (!controller.signal.aborted) setTodayBusy(false); });
    return () => controller.abort();
  }, [url, todayAttempt, offsets, query]);

  useEffect(() => {
    const controller = new AbortController();
    setLoadingMore(true);
    setMoreError("");
    const params: Record<string, string> = { limit: String(HISTORY_PAGE), cursor: String(historyOffset), q: query };
    if (filter) params.status = filter;
    void fetch(url("/history", params), { credentials: CREDENTIALS, signal: controller.signal })
      .then((response) => readJson(response, "History could not be loaded."))
      .then((body) => { if (!controller.signal.aborted) setHistory({ phase: "ready", value: parseHistory(body) }); })
      .catch((reason: unknown) => {
        if (!controller.signal.aborted) {
          const message = reason instanceof Error ? reason.message : "History could not be loaded.";
          setMoreError(message);
          setHistory((current) => current.phase === "ready" ? current : { phase: "error", message });
        }
      }).finally(() => { if (!controller.signal.aborted) setLoadingMore(false); });
    return () => controller.abort();
  }, [url, filter, historyAttempt, historyOffset, query]);

  const screen = today.phase === "ready" ? today.value : null;
  const editable = canEdit === true && screen?.canEdit === true;
  const openCount = useMemo(() => (screen
    ? screen.pages.items.open + screen.pages.apps.open : null), [screen]);
  const historyCount = history.phase === "ready"
    ? history.value.total ?? history.value.items.length : null;

  const toggle = (id: string) => setExcluded((current) => {
    const next = new Set(current);
    if (next.has(id)) next.delete(id); else next.add(id);
    return next;
  });
  const toggleAll = (open: Proposal[], include: boolean) => setExcluded((current) => {
    const next = new Set(current);
    for (const row of open) { if (include) next.delete(row.id); else next.add(row.id); }
    return next;
  });

  /** Approve or dismiss ids as one decision. Each row then shows its own result in place. */
  const decide = async (decision: "approve" | "dismiss", ids: string[], note = "") => {
    if (!ids.length) return;
    const fallback = decision === "approve" ? "The batch was not sent." : "The dismissal was not saved.";
    setSending(true);
    setDecideError("");
    try {
      const response = await fetch(url(`/${decision}`), {
        method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
        body: JSON.stringify(decision === "approve"
          ? { item_ids: ids, reviews: Object.fromEntries(ids.filter((id) => reviewedRemovals.current.has(id))
            .map((id) => [id, reviewedRemovals.current.get(id)])) }
          : { item_ids: ids, reason: note.trim() }),
      });
      const body = await readJson(response, fallback) as { rows?: unknown; withheldCount?: unknown } | null;
      if ((num(body?.withheldCount) ?? 0) > 0) {
        setTodayAttempt((count) => count + 1);
        setHistoryAttempt((count) => count + 1);
        setOpened(null);
        throw new Error(`${num(body?.withheldCount)} items need access you do not have`);
      }
      const rows = new Map<string, Record<string, unknown>>();
      for (const item of Array.isArray(body?.rows) ? body.rows : []) {
        const row = (item ?? {}) as Record<string, unknown>;
        if (text(row.id)) rows.set(text(row.id), row);
      }
      if (!alive.current) return;
      // Each row keeps its place and shows its own result, so nothing in the table moves.
      const settle = (item: Proposal): Proposal => {
        const row = rows.get(item.id);
        if (!row) return item;
        const status = text(row.status);
        if (status === "sent" || status === "refused" || status === "approved") {
          return { ...item, status, cause: text(row.cause) };
        }
        if (status === "dismissed") return { ...item, status, note: note.trim() };
        return { ...item, status: text(row.current) || item.status, notice: text(row.cause) || undefined };
      };
      setToday((current) => {
        if (current.phase !== "ready") return current;
        const items = current.value.items.map(settle);
        const appItems = current.value.appItems.map(settle);
        const pages = current.value.pages;
        return { phase: "ready", value: { ...current.value, items, appItems, pages: {
          ...pages,
          items: { ...pages.items, open: Math.max(0, pages.items.open
            - current.value.items.filter(isOpen).length + items.filter(isOpen).length) },
          apps: { ...pages.apps, open: Math.max(0, pages.apps.open
            - current.value.appItems.filter(isOpen).length + appItems.filter(isOpen).length) },
        } } };
      });
      setSettled((current) => new Set([...current, ...ids]));
      setDismissing(null);
      setHistoryAttempt((count) => count + 1);
    } catch (reason) {
      if (alive.current) setDecideError(reason instanceof Error ? reason.message : fallback);
    } finally {
      if (alive.current) setSending(false);
    }
  };

  const showToday = () => {
    focusTodayPending.current = true;
    setSearch(""); setQuery(""); setOffsets({ items: 0, apps: 0, held: 0 });
    setSettled(new Set()); setExcluded(new Set()); setDismissing(null); setOpened(null);
    setToday({ phase: "loading" }); setTodayAttempt((count) => count + 1); setTab("today");
    todayTab.current?.focus();
  };

  const proposeUndo = async (proposalId: string) => {
    if (!editable || sending || undoPending.current) return;
    undoPending.current = true;
    setUndoing(true);
    try {
      const response = await fetch(url("/undo"), {
        method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ proposal_id: proposalId }),
      });
      const body = await readJson(response, "Undo could not be added.");
      const item = parseProposal(body);
      if (!item || item.status !== "proposed") throw new Error("Undo is no longer open. Refresh History.");
      if (!alive.current) return;
      setUndoNotice("Undo added to Today");
      setHistoryAttempt((count) => count + 1);
      showToday();
    } finally {
      undoPending.current = false;
      if (alive.current) setUndoing(false);
    }
  };

  const openRow = (row: Proposal, from: "today" | "history") => {
    opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
    setOpened({ row, from });
  };
  const closeRow = useCallback(() => {
    setOpened(null);
    opener.current?.focus();
  }, []);

  // A Today drawer reads the live row, so a result that lands while it is open shows there too.
  const openedRow = !opened ? null : opened.from === "today"
    ? [...(screen?.items ?? []), ...(screen?.appItems ?? [])].find((row) => row.id === opened.row.id) ?? opened.row
    : opened.row;
  const tabs: [typeof tab, string, number | null][] = [["today", "Today", openCount], ["dashboard", "Dashboard", null], ["wasted", "Wasted spend", null], ["schedule", "Schedule", null], ["history", "History", historyCount], ["changes", "Change log", null], ["pacing", "Budget pacing", null]];
  const AppTabs = dashboardAdapter?.AppTabs;
  const changeTab = (key: OperatorTab) => { setTab(key); setOpened(null); };
  const tabKeys = (event: KeyboardEvent<HTMLDivElement>) => {
    const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
    if (!step && event.key !== "Home" && event.key !== "End") return;
    event.preventDefault();
    const index = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1
      : (tabs.findIndex(([key]) => key === tab) + step + tabs.length) % tabs.length;
    changeTab(tabs[index][0]);
    event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="tab"]')[index]?.focus();
  };
  return <div className="ao-app">
    <p id="ao-grid-help" className="ao-grid-help">Arrow keys move between cells. Enter opens proposal details.
      Space selects a row. Tab reaches row actions. Escape closes a menu or details.</p>
    <div className="ao-scroll">
      {AppTabs ? <div ref={sharedTabStrip}><AppTabs tabs={tabs} value={tab} onChange={changeTab} /></div>
        : <div className="ao-tabs" role="tablist" aria-label="Amazon operator" onKeyDown={tabKeys}>
        {tabs.map(([key, label, count]) => <button key={key} ref={key === "today" ? todayTab : undefined}
          type="button" role="tab" aria-selected={tab === key} tabIndex={tab === key ? 0 : -1}
          id={`ao-tab-${appId}-${key}`} aria-controls={`ao-panel-${appId}`}
          className={tab === key ? "ao-tab is-active" : "ao-tab"} onClick={() => changeTab(key)}>
          {label}{count !== null && <span className="ao-count">{count}</span>}
        </button>)}
      </div>}
      <div className="ao-body" role="tabpanel" id={`ao-panel-${appId}`} aria-label={tabs.find(([key]) => key === tab)?.[1]}>
        {undoNotice && tab === "today" && <p className="ao-undo-notice" role="status">{undoNotice}</p>}
        {todayError && tab === "today" && today.phase === "ready" && <Failed message={todayError} onRetry={() => setTodayAttempt((n) => n + 1)} />}
        {tab === "dashboard" ? <AdsOverview key={appId} appId={appId} /> : tab === "today"
          ? <TodayPanel state={today} busy={todayBusy} search={search} onSearch={setSearch} onPage={(section, offset) => {
            setOffsets((current) => ({ ...current, [section]: offset })); setDismissing(null);
          }} editable={editable} excluded={excluded} settled={settled} sending={sending || todayBusy}
            decideError={decideError} dismissing={dismissing} onToggle={toggle} onToggleAll={toggleAll}
            onApprove={(batch) => void decide("approve", batch.map((row) => row.id))}
            onDismissStart={(id) => setDismissing({ id, reason: "" })}
            onDismissReason={(reason) => setDismissing((current) => current && { ...current, reason })}
            onDismissCancel={() => setDismissing(null)}
            onDismiss={(ids, reason) => void decide("dismiss", ids, reason)}
            onOpen={(row) => openRow(row, "today")}
            onRetry={() => setTodayAttempt((count) => count + 1)} />
          : tab === "wasted" ? <WastedSpend key={appId} appId={appId} editable={editable} useGridSelection={useGridSelection}
            onDecided={() => { setTodayAttempt((value) => value + 1); setHistoryAttempt((value) => value + 1); }} />
          : tab === "schedule" ? <SchedulePanel key={appId} appId={appId} canEdit={editable} />
          : tab === "changes" ? <ChangeLogPanel key={appId} appId={appId} />
          : tab === "pacing" ? <BudgetPacingPanel key={appId} appId={appId} />
          : <HistoryPanel state={history} filter={filter} loadingMore={loadingMore} moreError={moreError}
            search={search} onSearch={setSearch}
            editable={editable} undoing={undoing || sending} resultUrl={(id) => url("/results", { proposal_id: id })}
            onUndo={proposeUndo} onToday={showToday}
            offset={historyOffset} onFilter={(status) => { setFilter(status); setHistoryOffset(0); }}
            onPage={setHistoryOffset} onOpen={(row) => openRow(row, "history")}
            onRetry={() => setHistoryAttempt((count) => count + 1)} />}
      </div>
    </div>
    {openedRow && <Drawer key={openedRow.id} row={openedRow} onClose={closeRow} onReviewed={noteReviewed} editable={editable}
      previousReview={reviewedRemovals.current.get(openedRow.id)} />}
  </div>;
}

export default function AmazonOperatorView({ application, canEdit }: {
  application: OperatorApplication; canEdit?: boolean;
}) {
  return <OperatorDashboardContext.Provider value={operatorDashboardAdapter}>
    <OperatorBody key={application.id} application={application} canEdit={canEdit} />
  </OperatorDashboardContext.Provider>;
}