File size: 123,051 Bytes
602dda9
8229039
52c6936
8229039
52c6936
2e7e617
52c6936
 
 
dec006b
e174d2c
19aed6d
103a492
19aed6d
 
2e7e617
 
 
 
103a492
2e7e617
602dda9
2e7e617
1d4419b
8cbc29f
1d4419b
 
19aed6d
4a26bdc
103a492
19aed6d
 
2e7e617
52c6936
8cbc29f
 
 
 
 
 
 
 
 
 
19aed6d
 
 
19b91ce
 
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52c6936
8229039
 
 
 
 
 
 
 
 
 
 
 
 
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19b91ce
de19b91
19b91ce
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103a492
 
 
 
 
19aed6d
52c6936
 
74f72af
103a492
82cdb59
8133df9
8cbc29f
19aed6d
 
 
 
 
 
 
 
 
 
 
52c6936
2e7e617
52c6936
 
2e7e617
52c6936
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103a492
 
 
19aed6d
 
4a26bdc
 
 
 
 
 
8229039
 
 
 
e174d2c
 
 
 
 
8229039
 
103a492
82cdb59
 
103a492
8cbc29f
 
8133df9
 
 
19aed6d
602dda9
8229039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103a492
 
 
 
 
 
8229039
 
 
 
 
 
 
19aed6d
8229039
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8229039
 
 
19aed6d
 
 
 
 
 
 
8229039
f530297
8229039
52c6936
19aed6d
8cbc29f
4a26bdc
8cbc29f
8229039
 
103a492
19aed6d
f530297
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
82cdb59
 
19aed6d
 
 
 
 
 
 
 
dec006b
7e977bc
dec006b
 
 
 
7e977bc
 
dec006b
 
19aed6d
 
52c6936
 
 
 
 
 
f530297
 
 
 
 
 
52c6936
 
 
 
f530297
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8229039
 
 
 
dec006b
8229039
 
 
 
 
 
 
 
2e7e617
8229039
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
103a492
 
 
19b91ce
19aed6d
 
 
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
8229039
 
 
 
 
 
 
19aed6d
 
52c6936
19aed6d
4a26bdc
8229039
19aed6d
 
 
 
 
 
 
4a26bdc
103a492
19aed6d
 
 
 
 
52c6936
19aed6d
 
 
52c6936
19aed6d
52c6936
19aed6d
 
 
 
 
103a492
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
19aed6d
 
 
 
 
 
 
 
 
 
8cbc29f
19aed6d
 
 
 
 
 
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
 
 
103a492
8229039
 
 
 
 
 
 
103a492
8229039
 
 
 
 
 
 
 
 
 
 
 
103a492
8229039
 
 
 
 
 
 
52c6936
 
 
 
 
 
 
 
 
 
103a492
52c6936
 
 
 
 
 
 
103a492
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
52c6936
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
 
 
 
 
 
 
52c6936
 
 
 
e174d2c
 
 
 
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
 
 
 
 
 
 
 
 
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
 
 
 
 
2e7e617
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8229039
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103a492
52c6936
 
 
 
 
 
 
e174d2c
2e7e617
 
e174d2c
 
 
 
 
 
 
52c6936
 
 
103a492
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
2e7e617
52c6936
 
2e7e617
 
 
 
 
 
 
 
 
52c6936
 
 
 
 
2e7e617
 
 
52c6936
 
2e7e617
52c6936
 
 
 
2e7e617
52c6936
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
dec006b
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
de19b91
 
 
 
 
 
52c6936
 
 
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
52c6936
 
 
 
 
2e7e617
52c6936
 
2e7e617
602dda9
 
2e7e617
8cbc29f
52c6936
 
 
 
 
 
 
 
 
 
 
 
19aed6d
7e977bc
2e7e617
 
 
 
52c6936
 
 
 
19aed6d
 
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
52c6936
 
 
8cbc29f
 
 
52c6936
 
 
 
 
 
 
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
e174d2c
8229039
 
 
e174d2c
 
 
 
 
 
 
 
602dda9
e174d2c
602dda9
e174d2c
 
 
 
 
 
 
 
 
602dda9
e174d2c
602dda9
e174d2c
 
 
 
2e7e617
52c6936
2e7e617
 
 
52c6936
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
 
52c6936
 
 
 
 
 
 
2e7e617
 
 
 
 
8cbc29f
2e7e617
 
 
 
 
 
 
8cbc29f
2e7e617
 
8cbc29f
2e7e617
8cbc29f
 
2e7e617
 
 
 
 
 
8229039
 
 
 
 
 
 
 
 
52c6936
8229039
52c6936
 
8229039
 
 
 
8cbc29f
 
 
 
8229039
 
 
 
 
8cbc29f
 
 
 
52c6936
 
 
 
 
 
 
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
52c6936
8229039
 
 
 
 
 
 
 
 
 
 
52c6936
 
 
 
 
8cbc29f
 
 
 
602dda9
 
8cbc29f
52c6936
19aed6d
8229039
 
 
 
 
 
 
 
19aed6d
8229039
 
 
 
 
19aed6d
 
 
 
 
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
602dda9
2e7e617
 
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
8229039
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
8229039
 
 
 
 
 
 
f530297
 
 
 
 
 
 
8229039
f530297
8229039
 
 
f530297
 
8229039
 
 
 
 
 
 
 
f530297
8229039
 
 
19aed6d
 
 
 
8cbc29f
19aed6d
 
52c6936
 
 
19aed6d
52c6936
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52c6936
 
 
 
 
 
 
 
 
 
 
e174d2c
 
 
 
 
 
 
 
 
 
 
 
 
 
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a26bdc
 
 
8cbc29f
4a26bdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
19aed6d
8229039
 
 
 
 
 
 
 
 
19aed6d
8229039
 
 
 
 
 
 
 
 
 
 
103a492
8229039
103a492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
 
103a492
8229039
 
 
 
19aed6d
52c6936
19aed6d
 
103a492
 
 
 
 
52c6936
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
19aed6d
 
2e7e617
 
 
 
 
 
19aed6d
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
8229039
 
 
 
 
e174d2c
8229039
 
e174d2c
 
8229039
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
8229039
82cdb59
 
 
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
19aed6d
f530297
19aed6d
f530297
8229039
19aed6d
f530297
19aed6d
 
 
1d4419b
f530297
 
19aed6d
8229039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e977bc
 
 
 
8229039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
8229039
f530297
8229039
f530297
8229039
 
 
f530297
8229039
 
f530297
8229039
f530297
8229039
1d4419b
f530297
 
8229039
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
dec006b
 
2e7e617
 
dec006b
2e7e617
8229039
 
 
2e7e617
8229039
f530297
 
 
 
 
 
 
 
8229039
 
 
f530297
 
 
 
8229039
f530297
8229039
 
f530297
8229039
f530297
 
2e7e617
 
 
 
 
 
 
 
8cbc29f
2e7e617
 
 
 
 
 
8229039
7e977bc
 
8229039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
8229039
19aed6d
 
2e7e617
dec006b
 
 
 
7e977bc
 
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
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
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { ReactElement } from "react";
import { createPortal } from "react-dom";
import { FolderMark } from "./icons";
import {
  formatSeconds, haversineKm, parseRouteAnswer, previewSeconds,
  routeCaveats, routeSaving, routeTimeLabel, routeTimeTone,
} from "./mapProjection";
import type { GeoStop, RouteAnswer } from "./mapProjection";
import { AnchoredOverlay, BodyPortal } from "./OverlaySurface";
import { normalizedRouteMapLinks, routePrintStops, routeReversePrintLabels } from "./routeLinks";
import type { NormalizedRouteMapLink } from "./routeLinks";
import { routingPreferenceKey } from "./routePrefs";
import { submitRouteStopMove } from "./routeStopMove";
import { boundedGoogleMapsUrl } from "./routeZoneTypes";
import {
  locatedRouteMovePlan,
  mergeLocatedOrderAtAnchors,
  routeLocationPartition,
  routeApplicationPath,
  routeStopIdentity,
  RoutingStopLabelErrors,
} from "./routeZoneApi";
// W51-T28 / R6 + C8 — the wave-51 base kit's ONE confirm dialog. Consumed, never re-implemented.
import { TruncatedName } from "../home/TruncatedName";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { useEscapeClose } from "../ui/useEscapeClose";
import type {
  MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
  RouteDeliveryRecipient, RouteDeliveryDto, RouteDeliveryRequest,
} from "./routeZoneTypes";
import "../styles/wave42/route-nav.css";
import "./route-nav.css";
import "../styles/wave46/route-print.css";
import "../styles/sdlc78/routing.css";

/** Google's own Maps mark from `public/brand/`, relative to the document as vite `base: "./"` makes
 *  every asset. No `import.meta` here: gates compile this file to CommonJS, where it is an error. */
export const GOOGLE_MAPS_MARK_SRC = "./brand/google-maps.svg";

/** The decorative 16 px Maps mark. The text beside it carries the name. */
export function GoogleMapsMark({ className = "cg-gmaps-mark" }: { className?: string }) {
  return <img className={className} src={GOOGLE_MAPS_MARK_SRC} alt="" aria-hidden="true" width={16} height={16} draggable={false} />;
}

type Result = Promise<string | null>;

type RouteAction = "rename" | "duplicate" | "star" | "share" | "delete";

/* ═════════════════════════════ W46-T19 / INSTRUCTION 9 / R9 / C2 ═════════════════════════════
 *
 * The drive time at the top of the Route, the saving a reorder would win, and the number that
 * moves while a stop is being dragged.
 *
 * ⛔⛔ THE DEBOUNCE IS A COURTESY LIMIT, NOT A NICETY. The door behind `ROUTE_DOOR` calls a free,
 * unauthenticated public routing service, twice per request (the order as it stands, then the
 * order it would choose), behind a process-wide 1100 ms throttle. One settled figure therefore
 * costs at least 2.2 s of that service's time. A drag emits dozens of events a second, so the
 * only safe wiring is the one C2 names: arithmetic during the drag, ONE request on drop, and
 * every earlier request cancelled the moment a new drag starts, or a slow answer lands on an
 * order nobody is looking at any more.
 */
/* ═════════════════════════════ W46-T20 / INSTRUCTION 10 / R6 / C6 ════════════════════════
 *
 * "ADD an export button for routes regardless to give to the sales team", plus R6's addition:
 * "i also want the google map link clickable in that PDF."
 *
 * The export is the browser's own Save as PDF behind a print stylesheet, which is the pattern
 * the catalog export already proves here. Set on `<html>` for the duration of one print and
 * taken off again however the dialog ends; `styles/wave46/route-print.css` carries the
 * isolation keyed off it.
 *
 * ⛔ A NAME OF ITS OWN, NEVER `cg-cat-printing`. The catalog's print block un-hides exactly
 * `.cg-cat-print-portal` and hides every other child of `<body>`, so borrowing its class would
 * print a blank sheet with nothing anywhere reporting a fault.
 */
const ROUTE_PRINTING_CLASS = "cg-w46-route-printing";
/** The honest backstop when neither `afterprint` nor the print media query reports an end. */
const PRINT_RELEASE_MS = 120_000;

const ROUTE_DOOR = "/api/v1/geo/route";
/**
 * OWNER 2026-08-31 item 2 - the six defaults a new Route is stamped with, offered back as an
 * edit. ⛔ THIS LIST IS A MIRROR OF `route_system.py::_ROUTE_COLORS` AND MUST STAY ONE. The
 * server is the authority: `_color` falls back to `_ROUTE_COLORS[ordinal % len]` for anything
 * `_COLOR_RE` refuses, so a swatch offered here that the server does not recognise would save
 * as a different colour than the one the person pressed. The free picker beside them is why the
 * list does not need to grow: it is a shortcut, not the vocabulary.
 */
const ROUTE_SWATCHES = ["#6E4AC7", "#1F4E78", "#C85A54", "#2F8F83", "#B57716", "#A14B8B"];

/** The rail's own top level, as a map key. A bare string keeps `foldersByParent` and
 *  `routesByFolder` one type instead of `Map<string | null, ...>`, and no folder id can collide
 *  with it: `route_system.py` mints folder ids, and none of them is empty. */
const ROOT_LEVEL = "";
/* ⛔ TWO DRAG TYPES, ONE PER ROW KIND, and that is the same discrimination `ViewSidebar` makes
   with `FOLD_DRAG_TYPE` against a view's own channel. Sharing one channel would let a folder
   dropped on a Route reorder the Routes, and the handler that fired first would decide which. */
const ROUTE_DRAG = "application/x-aios-route";
const ROUTE_FOLDER_DRAG = "application/x-aios-route-folder";

/** Owner item 3 - the ONE mark every Route row wears. Deliberately the SAME waypoint path
 *  `viewModes.tsx::IconRouteZone` draws, at the same 1.5 stroke: the toolbar button that opens
 *  this rail and the rows inside it are one family, and a second route glyph would read as two. */
function IconRoute() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"
      className="cg-view-route-mark">
      <path d="M4 2.4a2 2 0 0 1 2 2c0 1.5-2 3.7-2 3.7S2 5.9 2 4.4a2 2 0 0 1 2-2Z" stroke="currentColor"
        strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M12 2.4a2 2 0 0 1 2 2c0 1.5-2 3.7-2 3.7s-2-2.2-2-3.7a2 2 0 0 1 2-2Z" stroke="currentColor"
        strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M4.2 9.4c2.1 2.7 5.5 2.7 7.6 0" stroke="currentColor" strokeWidth="1.5"
        strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}
const SETTLE_DEBOUNCE_MS = 400;
/** ⛔ BOTH HALVES OF THE FIGURE MUST ASK THE SAME QUESTION, or the number jumps on drop by the
 *  size of a closing edge and the reorder gets blamed for it. That is why the round-trip answer
 *  travels as ONE value into `previewSeconds` during the drag and into the request body on drop.
 *
 *  ⭐⭐ OWNER 2026-08-31: *"wtf I don't see the button to make it either 1 single trip or round
 *  trip. The algorithm was there its not being displayed anymore"*. They are right, and the
 *  record says so in code: `MapView.tsx` holds `roundTrip` state whose only writer, `setRoundTrip`,
 *  sits in the retired `void []` compatibility list, so the value was pinned at false with no
 *  control anywhere. The solver (`mapProjection.ts::planRoute`, `twoOptOrder`, `tourLength`) and
 *  the server door (`routes_geo.py`, which reads `roundTrip` off the body) were both live the
 *  whole time. So this is a control being re-attached to an algorithm, not a feature being built.
 *  It is a PROP rather than local state because the map's drawn plan and this panel's timer must
 *  answer the same question; two copies is how they come to disagree. */
const ROUTE_MODE = "driving";

/**
 * The order a drag would leave behind: `moved` taken out and put back where `over` sits now.
 *
 * ⛔ PURE, AND DELIBERATELY OUTSIDE THE COMPONENT. It is the only thing the drag path computes,
 * so keeping it here makes "the drag calls no network" a property of a function that has no
 * closure to hide one in.
 */
function orderAfterMove(pids: number[], moved: number, over: number): number[] {
  const from = pids.indexOf(moved);
  const to = pids.indexOf(over);
  if (from < 0 || to < 0 || from === to) return pids;
  const next = [...pids];
  next.splice(to, 0, next.splice(from, 1)[0]);
  return next;
}

function mayRouteAction(route: MapRouteDto, action: RouteAction): boolean {
  return route.capabilities?.[action] === true;
}

export interface RoutingCustomerDetail {
  pid: number;
  name: string;
  fields: { key: string; label: string; value: string }[];
}

function routingFieldUrl(value: string): string | null {
  try {
    const url = new URL(value);
    return /^https?:\/\//i.test(value.trim()) && (url.protocol === "http:" || url.protocol === "https:")
      ? url.href : null;
  } catch {
    return null;
  }
}

export function RouteCustomerPane({ detail, onBack }: {
  detail: RoutingCustomerDetail | null;
  onBack: () => void;
}) {
  const pane = useRef<HTMLElement>(null);
  const opener = useRef<HTMLElement | SVGElement | null>(null);
  const previousPid = useRef<number | null>(null);
  const [closingPid, setClosingPid] = useState<number | null>(null);
  const closing = detail != null && closingPid === detail.pid;
  const close = () => {
    if (!detail) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) onBack();
    else setClosingPid(detail.pid);
  };
  useEscapeClose(detail != null, close, { container: () => pane.current });
  useLayoutEffect(() => {
    if (detail) {
      const active = document.activeElement;
      if ((active instanceof HTMLElement || active instanceof SVGElement) && !pane.current?.contains(active))
        opener.current = active;
      pane.current?.querySelector<HTMLButtonElement>(".cg-routing-detail-back")?.focus({ preventScroll: true });
    } else if (previousPid.current !== null && opener.current?.isConnected) {
      opener.current.focus({ preventScroll: true });
    }
    previousPid.current = detail?.pid ?? null;
    setClosingPid(null);
  }, [detail?.pid]);
  if (!detail) return null;
  return <BodyPortal><article ref={pane} className={"cg-routing-detail" + (closing ? " is-closing" : "")}
      key={detail.pid} data-detail-pid={detail.pid} aria-label="Customer detail"
      onAnimationEnd={(event) => {
        if (event.target === event.currentTarget && closing) onBack();
      }}>
      <header>
        <button type="button" className="cg-routing-detail-back" onClick={close}>Back</button>
        <h2>{detail.name}</h2>
      </header>
      <dl className="cg-routing-detail-fields" role="region" aria-label="Customer fields" tabIndex={0}>
        {detail.fields.map((field) => {
          const href = routingFieldUrl(field.value);
          return <div className="cg-routing-detail-field" key={field.key} data-field-key={field.key}>
            <dt>{field.label}</dt><dd>{href
              ? <a className="cg-detail-action" href={href} target="_blank" rel="noopener noreferrer">{field.value}</a>
              : field.value}</dd>
          </div>;
        })}</dl>
    </article></BodyPortal>;
}

export function RouteNav(props: Parameters<typeof RouteNavContent>[0]) {
  return <RouteNavContent key={JSON.stringify([props.storageKey, props.applicationId ?? ""])} {...props} />;
}

function RouteNavContent({ routes, folders, selectedIds, activeRouteId, sources, storageKey,
  createdRoute, onCreatedDismiss, onToggle, onActiveRouteChange, onOpenRecord, onCreate,
  onMoveToOrder, onUpdate, onDuplicate, onDelete, onShare, onRouteMove, onRouteReorder, stopLabels = {},
  stopCoords = {},
  onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
  onDeleteDelivery, deliveryRecipients, deliveryRecipientError, onReloadDeliveryRecipients, zones = [],
  roundTrip = false, onRoundTripChange, routeStartPid = null, routeEndPid = null, onRouteStartChange, onRouteEndChange, onStopAdded,
  routesLoadError = false, onRetryRoutes,
  applicationName = "", applicationId, routesLoaded = true }: {
  routes: MapRouteDto[];
  folders: MapRouteFolderDto[];
  selectedIds: ReadonlySet<string>;
  activeRouteId: string | null;
  sources: MapRouteSource[];
  storageKey: string;
  createdRoute: MapRouteDto | null;
  onCreatedDismiss: () => void;
  onToggle: (route: MapRouteDto) => void;
  onActiveRouteChange: (routeId: string | null) => void;
  onOpenRecord: (pid: number) => void;
  /** Row-derived identity for every stop the host can name. Keyed by pid; both fields may be
   *  empty, and `routeStopIdentity` owns what is shown when they are.
   *  ⚠ OPTIONAL because this component also mounts in a render harness with no host grid behind
   *  it; MapView always supplies it. The default is `{}`, which routes every stop through
   *  `routeStopIdentity`'s final arm rather than rendering a blank. */
  stopLabels?: Record<number, { name: string; address: string }>;
  /** W46-T19 — where each stop IS, keyed by pid, in the coordinates the host already geocoded.
   *  The drive time, the drag preview and the reorder offer all need a position rather than a
   *  name, and `stopLabels` deliberately carries neither.
   *  ⚠ OPTIONAL for the same reason `stopLabels` is: this component mounts in a render harness
   *  with no host grid behind it. An absent or partial map is stated on screen, never rounded
   *  down to a confident zero. */
  stopCoords?: Record<number, { lat: number; lon: number }>;
  onCreate: (name: string, source: MapRouteSource) => Result;
  onMoveToOrder: (route: MapRouteDto, customerPid: number, order: number) => Result;
  onUpdate: (route: MapRouteDto, patch: MapRouteUpdate) => Result;
  onDuplicate: (route: MapRouteDto) => Result;
  onDelete: (route: MapRouteDto) => Promise<string | null>;
  onShare: (route: MapRouteDto) => Result;
  onRouteMove: (route: MapRouteDto, folderId: string | null) => Result;
  onRouteReorder: (order: string[]) => Result;
  onFolderCreate: (name: string, parent: string | null) => Result;
  onFolderUpdate: (folder: MapRouteFolderDto, patch: { name?: string; parent?: string | null }) => Result;
  onFolderDelete: (folder: MapRouteFolderDto) => Result;
  onFolderReorder: (order: string[]) => Result;
  onCreateStart: () => void;
  mapLinks: NormalizedRouteMapLink[];
  mapLinkRefusal: string | null;
  deliveries: RouteDeliveryDto[] | null;
  deliveryRecipients: RouteDeliveryRecipient[] | null;
  deliveryRecipientError: string | null;
  onReloadDeliveryRecipients: () => void;
  onSchedule: (route: MapRouteDto, request: RouteDeliveryRequest) => Result;
  onDeleteDelivery: (route: MapRouteDto, delivery: RouteDeliveryDto) => Result;
  /** D-599 / W46-T22 - the Zones this database has, so a Route can be put in one. The host
   *  already holds them to draw the map, so this is a pass-through and never a second fetch.
   *  ⚠ OPTIONAL with a `[]` default for the same reason `stopLabels` is: this component also
   *  mounts in a render harness with no host behind it. An empty list renders the selector
   *  disabled with a sentence, never a silently empty dropdown. */
  zones?: MapZoneDto[];
  /** Owner 2026-08-31 - one way, or back to where the driver started. Owned by the host so the
   *  map's drawn plan and this panel's drive time cannot answer different questions. */
  roundTrip?: boolean;
  onRoundTripChange?: (value: boolean) => void;
  /** Planner endpoints are owned by MapView, so the rail cannot disagree with the drawn route. */
  routeStartPid?: number | null;
  routeEndPid?: number | null;
  onRouteStartChange?: (pid: number | null) => void;
  onRouteEndChange?: (pid: number | null) => void;
  /** The Route the membership door answered with, so the host's read model gains the new stop
   *  without a second fetch. Mirrors what `moveNamedRouteStop` already does on a reorder. */
  onStopAdded?: (route: MapRouteDto, applicationId?: string) => void;
  /** Present only when this trusted route surface was launched by a saved Application. */
  applicationName?: string;
  applicationId?: string;
  /** False until the first saved-Route read answers, so an empty list is not read as "none". */
  routesLoaded?: boolean;
  /** True when the last saved-Route read failed; the listed routes are the last good read. */
  routesLoadError?: boolean;
  onRetryRoutes?: () => void;
}) {
  const stopLabelErrors = useContext(RoutingStopLabelErrors);
  /* ⭐⭐ OWNER 2026-08-31 item 3 - THE ROUTES RAIL IS THE VIEWS RAIL, NOT A COUSIN OF IT.
     Owner: *"I need the routes LIST navigation and the routes itself to have the exact same
     interface just like how we have it with view, where you can just click it and drag it AND
     its fucking compact. Make it the exact same layout. The only difference is the icon."* and,
     in the grill: *"exactly like how Views rail is, with the +create for folder and find at the
     top. Exactly the same. instead of number it should all just be the same Route icon."*

     ⛔ SO THE BREADCRUMB PATH IS GONE, AND THAT IS THE STRUCTURAL HALF OF THE ASK. A folder used
     to be a place you NAVIGATED INTO (`levelAt` + `folderPath` + an `Up` button), which is a
     different interaction from the Views rail's disclosure groups however similar the rows look.
     Folders now open and shut in place, and the stored key holds the SHUT set rather than the
     current level - so a person who never touches a folder sees every Route, which is the
     behaviour a rail whose whole job is "pick one" should have.

     ⚠ THE ROW CLASSES ARE THE VIEWS RAIL'S OWN (`.cg-view-row`, `.cg-view-main`, `.cg-view-text`,
     `.cg-view-name`, `.cg-view-more`, `.cg-fold*`, `.cg-create-new`, `.cg-find-view`), reused
     rather than copied. Copying them into a `cg-w44-route-*` twin is how the two lists drift
     apart again the first time either is polished, and "exact same layout" is a promise that
     only a shared contract can keep. */
  const routingAlive = useRef(true);
  useEffect(() => {
    routingAlive.current = true;
    return () => { routingAlive.current = false; };
  }, []);
  const routePathKey = routingPreferenceKey(`aios-routes-shut-${storageKey}`, applicationId);
  const [shutFolders, setShutFolders] = useState<ReadonlySet<string>>(() => {
    if (typeof window === "undefined") return new Set<string>();
    try {
      const raw = window.localStorage.getItem(routePathKey);
      const parsed = raw ? JSON.parse(raw) : null;
      return new Set<string>(Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : []);
    } catch { return new Set<string>(); }
  });
  /** Owner item 3 - "find at the top". Local, never persisted: a search is a way of LOOKING at
   *  the rail, not a property of it, which is the rule `ViewSidebar`'s own box already follows. */
  const [routeQuery, setRouteQuery] = useState("");
  /* ═════════════════ W50-T10 / INSTRUCTION 9 — THE FOUR MENUS PORTAL NOW ═════════════════
   *
   * Owner: *"Clicking the '...' on each route (Duplicate/Star/Share/Delete) expands the whole
   * thing, and it cannot be closed."* All four menus in this rail were in-flow `<div>`s toggled
   * only by their own button: no outside-click dismiss, no Escape, no focus restore, and each one
   * pushed the rows below it down as it opened. `AnchoredOverlay` owns all four behaviours
   * already, so every one of them is now a portalled overlay instead.
   *
   * ⛔ THE ANCHOR RIDES IN THE STATE, AND IT IS READ FROM `event.currentTarget` IN THE HANDLER
   * BODY — never inside the updater. React sets `currentTarget = null` the moment the handler
   * returns, and a functional updater is re-invoked when React drains the queue, by which time it
   * reads null and the overlay degrades to a zero-rect at the viewport origin. `ViewSidebar.tsx`
   * carries the full account: that one line was the difference between its rail working and the
   * whole app going white, reproduced on the shipped build by `_qa_live_rail.py` on 2026-08-04.
   *
   * ⚠ NO CSS CAME WITH THIS. `body > .cg-overlay` already sits at `--cg-z-overlay` (110), which
   * outranks `--cg-z-mapchrome` (65) that the route popover stacks at, so a portalled menu is
   * above it by construction. Minting a z token here would be a second answer to a solved
   * question.
   */
  const [createMenu, setCreateMenu] = useState<{ anchor: HTMLElement } | null>(null);
  /** The row being carried, and the row it would land ABOVE. Same two marks the Views rail uses. */
  const [rowDrag, setRowDrag] = useState<string | null>(null);
  const [rowOver, setRowOver] = useState<string | null>(null);
  const [creating, setCreating] = useState(false);
  const [creatingFolder, setCreatingFolder] = useState(false);
  const [name, setName] = useState("");
  const [folderName, setFolderName] = useState("");
  const [sourceId, setSourceId] = useState<MapRouteSource["id"]>("selection");
  const [error, setError] = useState<string | null>(null);
  const [orderErrors, setOrderErrors] = useState<Record<number, string>>({});
  /** Owner 2026-08-31 - the add-record door's own two pieces of state. */
  const [addStop, setAddStop] = useState<{ anchor: HTMLElement } | null>(null);
  const [addStopQuery, setAddStopQuery] = useState("");
  const [titleDraft, setTitleDraft] = useState<string | null>(null);
  const [editMapsUrl, setEditMapsUrl] = useState("");
  /** D-599 - the Route's Zone, as a draft, saved by the same Save button as the Maps URL. */
  const [editZoneId, setEditZoneId] = useState("");
  /** OWNER 2026-08-31 item 2 - the Route's colour, as a draft, on the same Save button.
   *  Seeded from the record so the swatch a person sees selected is the colour the map draws. */
  const [editColor, setEditColor] = useState(ROUTE_SWATCHES[0]);
  const [deliveryRecipient, setDeliveryRecipient] = useState("");
  const [deleteConfirm, setDeleteConfirm] = useState(false);
  const [menu, setMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
  /* ⭐⭐ W51-T28 / R6 — THE PENDING DELETE IS HOISTED TO THE COMPONENT, AND THAT IS THE WHOLE
     TRICK. Both row menus close themselves (`setMenu(null)`) in the same handler that used to
     raise `window.confirm`, and each menu is a conditional subtree
     (`{menu && menu.id === item.id && (<AnchoredOverlay …>`). A dialog rendered inside that
     subtree unmounts in the same commit and the person sees nothing at all. So the menu records
     WHAT was asked for, and the dialog is mounted from the component's own returned JSX, outside
     every menu conditional and outside `renderLevel`.
     ⚠ ONE state serves both deletes because it is DISCRIMINATED. Two booleans would let a folder
     delete and a route delete be pending at once, which is two dialogs on one screen. */
  const [pendingDelete, setPendingDelete] = useState<
    | { kind: "folder"; folder: MapRouteFolderDto }
    | { kind: "route"; item: MapRouteDto }
    | null
  >(null);
  const [renameId, setRenameId] = useState<string | null>(null);
  /** W54-T21 - raised by the rename's Escape claim so the blur it causes does not save. */
  const renameEscaping = useRef(false);
  const [busy, setBusy] = useState(false);
  const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10);
  const [deliveryNotice, setDeliveryNotice] = useState<string | null>(null);
  const [deliveryError, setDeliveryError] = useState<string | null>(null);
  const [deliveryBusy, setDeliveryBusy] = useState(false);
  const [mapCopyNotice, setMapCopyNotice] = useState<string | null>(null);
  const [mapCopyError, setMapCopyError] = useState<string | null>(null);
  const route = activeRouteId ? routes.find((item) => item.id === activeRouteId) : null;
  const rail = useRef<HTMLElement>(null);
  // ⚠ The Routes list unmounts while a Route is open, so its scroll is kept here for Back.
  const listScroll = useRef(0);
  const previousRouteId = useRef<string | null>(null);
  useLayoutEffect(() => {
    if (!applicationName) return;
    const list = rail.current?.querySelector<HTMLElement>(".cg-route-index-scroll");
    if (!route && previousRouteId.current !== null && list) list.scrollTop = listScroll.current;
    previousRouteId.current = route?.id ?? null;
  }, [applicationName, route?.id]);
  const source = sources.find((item) => item.id === sourceId) || sources[0];
  const mapsUrl = boundedGoogleMapsUrl(route?.mapsUrl);
  /**
   * W46-T22 / INSTRUCTION 19 — a stop can be taken OFF a Route from the Route itself.
   *
   * ⛔ THE WHOLE STOP LIST IS NEVER SUBMITTED. `visibleStopIds` is permission filtered on the
   * server, so PATCHing it back as this Route's `stops` would silently drop every stop outside
   * the reader's customer book. The membership door removes exactly one pid and re-densifies the
   * rest, which is why it exists.
   * ⛔ R14 (2026-09-03) MADE THIS ONE OF MEMBERSHIP'S TWO REMAINING DOORS. The map used to
   * offer a third: clicking a pin with the Routes panel open raised an add-or-remove prompt
   * on the same endpoint. That shortcut is retired, because it stole the plain click from
   * opening the record. Membership is now this per-stop control and the `Add record` picker
   * below, both of them visible, and both of them still calling `/stops/membership`.
   *
   * ⚠ THE HOST OWNS `namedRoutes` AND THIS COMPONENT HAS NO CALLBACK INTO IT, so a confirmed
   * removal is held here until the host refetches. The set self-heals rather than going stale:
   * it is keyed to one Route id, and any pid the host no longer reports is pruned, so a stop
   * re-added through the `Add record` picker reappears instead of staying invisible.
   */
  const [removedStops, setRemovedStops] = useState<{ routeId: string; pids: number[] }>(
    { routeId: "", pids: [] }
  );
  const activeStopIds = route?.visibleStopIds;
  const activeStopRouteId = route?.id || "";
  useEffect(() => {
    const present = new Set(activeStopIds || []);
    setRemovedStops((current) => {
      if (current.routeId !== activeStopRouteId) return { routeId: activeStopRouteId, pids: [] };
      const pids = current.pids.filter((pid) => present.has(pid));
      return pids.length === current.pids.length ? current : { routeId: activeStopRouteId, pids };
    });
  }, [activeStopIds, activeStopRouteId]);
  const stopIds = useMemo(
    () => (activeStopIds || []).filter(
      (pid) => !(removedStops.routeId === activeStopRouteId && removedStops.pids.includes(pid))
    ),
    [activeStopIds, activeStopRouteId, removedStops]
  );
  /**
   * ⭐ OWNER 2026-08-31 - the records the add-record dropdown may offer: everything in the book
   * this panel already holds, minus what is already a stop.
   *
   * Every match remains reachable through the picker.
   */
  const stopSet = useMemo(() => new Set(stopIds), [stopIds]);
  const addStopMatches = useMemo(() => {
    const needle = addStopQuery.trim().toLowerCase();
    const out: { pid: number; label: string }[] = [];
    for (const [key, value] of Object.entries(stopLabels)) {
      const pid = Number(key);
      if (!Number.isSafeInteger(pid) || stopSet.has(pid)) continue;
      const label = routeStopIdentity(value, pid);
      if (needle && !label.toLowerCase().includes(needle)) continue;
      out.push({ pid, label });
    }
    // ⛔ A NAMELESS RECORD SORTS LAST, AND THIS IS A MEASUREMENT, NOT A PREFERENCE. Tenant #0's
    // customer book carries 57 records whose name in Odoo is literally "?" (counted on the
    // deployed staging build). Plain `localeCompare` puts "?" before every letter, so all 57
    // filled the first fifty rows and the menu opened on nothing anybody could pick. A label
    // with no letter or digit in it is a placeholder rather than a name, so it goes to the end;
    // it is still offered, still searchable, and no record is hidden.
    const named = (label: string) => /[\p{L}\p{N}]/u.test(label);
    out.sort((a, b) => (Number(named(b.label)) - Number(named(a.label)))
      || a.label.localeCompare(b.label));
    return out;
  }, [addStopQuery, stopLabels, stopSet]);
  const addableStops = addStopMatches;
  const recipientNames = useMemo(
    () => new Set((deliveryRecipients || []).map((person) => person.username)),
    [deliveryRecipients]
  );
  const knownFolders = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]);
  const deliveryTimezone = useMemo(() => {
    try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; }
    catch { return "UTC"; }
  }, []);

  /** Child folders of one parent, in their stored order. `ROOT_LEVEL` is the rail's own top. */
  const foldersByParent = useMemo(() => {
    const map = new Map<string, MapRouteFolderDto[]>();
    for (const folder of folders) {
      const parent = folder.parent && knownFolders.has(folder.parent) ? folder.parent : ROOT_LEVEL;
      const bucket = map.get(parent);
      if (bucket) bucket.push(folder); else map.set(parent, [folder]);
    }
    for (const bucket of map.values()) bucket.sort((a, b) => (a.order || 0) - (b.order || 0));
    return map;
  }, [folders, knownFolders]);

  /** Routes filed in one folder, in their stored rail order. A Route whose folder this reader
   *  cannot see falls to the top level rather than disappearing. */
  const routesByFolder = useMemo(() => {
    const map = new Map<string, MapRouteDto[]>();
    for (const item of routes) {
      const parent = item.folderId && knownFolders.has(item.folderId) ? item.folderId : ROOT_LEVEL;
      const bucket = map.get(parent);
      if (bucket) bucket.push(item); else map.set(parent, [item]);
    }
    for (const bucket of map.values()) bucket.sort((a, b) => (a.navOrder || 0) - (b.navOrder || 0));
    return map;
  }, [routes, knownFolders]);

  /** ⚠ A FOLDER SURVIVES THE FIND BOX WHEN A DESCENDANT MATCHES, never only when its own name
   *  does. Hiding a folder whose contents match is how a search convinces somebody a Route has
   *  been deleted. `ViewSidebar` holds the same rule for its groups. */
  const query = routeQuery.trim().toLowerCase();
  const folderMatches = useMemo(() => {
    const hit = new Set<string>();
    if (!query) return hit;
    const walk = (parent: string): boolean => {
      let found = (routesByFolder.get(parent) || []).some(
        (item) => item.name.toLowerCase().includes(query)
      );
      for (const child of foldersByParent.get(parent) || []) {
        const inside = walk(child.id);
        if (inside || child.name.toLowerCase().includes(query)) { hit.add(child.id); found = true; }
      }
      return found;
    };
    walk(ROOT_LEVEL);
    return hit;
  }, [foldersByParent, query, routesByFolder]);

  const toggleFolder = (folderId: string) => {
    setMenu(null);
    setShutFolders((current) => {
      const next = new Set(current);
      if (next.has(folderId)) next.delete(folderId); else next.add(folderId);
      try { window.localStorage.setItem(routePathKey, JSON.stringify([...next])); }
      catch { /* The rail still opens and shuts when storage is unavailable. */ }
      return next;
    });
  };
  useEffect(() => {
    setTitleDraft(null);
    setEditMapsUrl(route?.mapsUrl || "");
    setEditZoneId(route?.zoneId || "");
    setEditColor((route?.color || ROUTE_SWATCHES[0]).toUpperCase());
    setOrderErrors({});
    setDeleteConfirm(false);
    setError(null);
    setDeliveryNotice(null);
    setDeliveryError(null);
    setMapCopyNotice(null);
    setMapCopyError(null);
  }, [route?.id, route?.mapsUrl, route?.name, route?.zoneId]);
  useEffect(() => { setDeliveryRecipient(""); }, [route?.id]);

  const copyMapLinks = () => {
    setMapCopyNotice(null);
    setMapCopyError(null);
    const clipboard = typeof navigator === "undefined" ? null : navigator.clipboard;
    if (!shownMapLinks.length || !clipboard?.writeText) {
      setMapCopyError("Maps links could not be copied in this browser.");
      return;
    }
    void clipboard.writeText(shownMapLinks.map((link) => link.url).join("\n"))
      .then(() => setMapCopyNotice(
        `${shownMapLinks.length.toLocaleString()} Maps link${shownMapLinks.length === 1 ? "" : "s"} copied.`
      ))
      .catch(() => setMapCopyError("Maps links could not be copied. Open each link instead."));
  };

  const scheduleDelivery = (target: MapRouteDto) => {
    const recipient = deliveryRecipient;
    if (!recipient || !recipientNames.has(recipient)) {
      setDeliveryError("Choose an active delivery recipient.");
      return;
    }
    setDeliveryBusy(true);
    setDeliveryError(null);
    setDeliveryNotice(null);
    void onSchedule(target, {
      recipient,
      timezone: deliveryTimezone,
      mapsPerLink: deliveryMapsPerLink,
    }).then((message) => {
      if (message) setDeliveryError(message);
      else setDeliveryNotice(`${target.name} will be delivered to ${recipient} daily at 08:00.`);
    }).finally(() => setDeliveryBusy(false));
  };

  const removeDelivery = (target: MapRouteDto, delivery: RouteDeliveryDto) => {
    setDeliveryBusy(true);
    setDeliveryError(null);
    setDeliveryNotice(null);
    void onDeleteDelivery(target, delivery).then((message) => {
      if (message) setDeliveryError(message);
      else setDeliveryNotice(`${delivery.name} was removed.`);
    }).finally(() => setDeliveryBusy(false));
  };

  const finish = (operation: Result) => {
    setBusy(true);
    void operation.then(setError).finally(() => setBusy(false));
  };
  const commitStopMove = (target: MapRouteDto, pid: number, raw: string) => {
    holdTimerCard(true);
    setBusy(true);
    setOrderErrors((current) => {
      const next = { ...current };
      delete next[pid];
      return next;
    });
    void submitRouteStopMove(target, pid, raw, onMoveToOrder).then((result) => {
      if (result.error) {
        const message = result.error;
        setOrderErrors((current) => ({ ...current, [pid]: message }));
        setTimerHold(null);
        return;
      }
      setOrderErrors((current) => {
        const next = { ...current };
        delete next[pid];
        return next;
      });
    }).finally(() => setBusy(false));
  };
  /**
   * Put ONE record onto this Route, through the same membership door the x uses.
   *
   * ⛔ NO OPTIMISTIC ROW. The server answers with the whole Route and `onMoveToOrder`'s host
   * already replaces the record from that answer; painting a stop locally first would show a
   * position the server has not agreed to, and a refusal would then have to un-paint it.
   */
  const commitStopAdd = (target: MapRouteDto, pid: number) => {
    setBusy(true);
    setError(null);
    void (async () => {
      try {
        const res = await fetch(
          routeApplicationPath(`/api/v1/customers/routes/${encodeURIComponent(target.id)}/stops/membership`, applicationId),
          {
            method: "POST", credentials: "same-origin",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ customerPid: pid, present: true }),
          }
        );
        const payload = await res.json().catch(() => null);
        if (!routingAlive.current) return;
        if (!res.ok) {
          setError(payload?.error?.message || payload?.detail?.message
            || "That record could not be added to this Route.");
          return;
        }
        // The removal ledger is what hides a stop this session took OFF the Route. Adding the
        // same record back has to clear its entry, or the row the server just returned would be
        // filtered straight back out and the button would look broken.
        setRemovedStops((current) => current.routeId === target.id
          ? { routeId: target.id, pids: current.pids.filter((item) => item !== pid) }
          : current);
        const routeUpdate = payload?.route as MapRouteDto | undefined;
        if (routeUpdate) onStopAdded?.(routeUpdate, applicationId);
      } catch {
        setError("That record could not be added to this Route.");
      } finally {
        setBusy(false);
      }
    })();
  };
  const commitStopRemove = (target: MapRouteDto, pid: number) => {
    setBusy(true);
    setOrderErrors((current) => {
      const next = { ...current };
      delete next[pid];
      return next;
    });
    void (async () => {
      try {
        const res = await fetch(
          routeApplicationPath(`/api/v1/customers/routes/${encodeURIComponent(target.id)}/stops/membership`, applicationId),
          {
            method: "POST", credentials: "same-origin",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ customerPid: pid, present: false }),
          }
        );
        const payload = await res.json().catch(() => null);
        if (!routingAlive.current) return;
        if (!res.ok) {
          const message = payload?.error?.message || payload?.detail?.message
            || "This stop could not be removed.";
          setOrderErrors((current) => ({ ...current, [pid]: message }));
          return;
        }
        setRemovedStops((current) => current.routeId === target.id
          ? (current.pids.includes(pid) ? current : { routeId: target.id, pids: [...current.pids, pid] })
          : { routeId: target.id, pids: [pid] });
      } catch {
        setOrderErrors((current) => ({ ...current, [pid]: "This stop could not be removed." }));
      } finally {
        setBusy(false);
      }
    })();
  };

  /* ── W46-T19: the drive time, the saving, and the number that moves during a drag ─────────
     The whole feature is state and arithmetic here, and exactly one request, so that the two
     numbers on screen can never come from two different questions. */
  const [routeAnswer, setRouteAnswer] = useState<RouteAnswer | null>(null);
  const [timerError, setTimerError] = useState<string | null>(null);
  const [timerBusy, setTimerBusy] = useState(false);
  const [applyBusy, setApplyBusy] = useState(false);
  const [dragPid, setDragPid] = useState<number | null>(null);
  const [dragOrder, setDragOrder] = useState<number[] | null>(null);
  const [dragSeconds, setDragSeconds] = useState<number | null>(null);
  /* S78-T08: the timer card keeps its pre-move height from a stop's pickup until the new drive
     time settles, so the stop list below it never jumps on drop or on Alt + Up / Alt + Down. */
  const timerCardRef = useRef<HTMLElement | null>(null);
  const [timerHold, setTimerHold] = useState<
    { height: number; from: RouteAnswer | null; committed: boolean } | null>(null);
  const holdTimerCard = (committed: boolean) => {
    const height = timerCardRef.current?.getBoundingClientRect().height ?? 0;
    setTimerHold((current) => current ? { ...current, committed: current.committed || committed }
      : height > 0 ? { height, from: routeAnswer, committed } : null);
  };
  /** W46-T20 — true only while one print is in flight. The printed sheet is mounted on
   *  `document.body` for exactly that long, so it costs nothing the rest of the time and can
   *  never be a second copy of the Route sitting invisibly in the panel. */
  const [printing, setPrinting] = useState(false);
  /** A reverse label is prepared before mounting the print portal, never requested from a
   * browser/provider during print.  The server may answer unavailable; that remains printable. */
  const [preparingPrint, setPreparingPrint] = useState(false);
  const [reversePrintLabels, setReversePrintLabels] = useState<Record<number, string>>({});
  /** ⚠ A LATCH, BECAUSE `window.print()` MUST HAPPEN ONCE. React's development strict mode
   *  invokes an effect twice; without this the dialog opens, closes, and opens again. */
  const printLatch = useRef(false);
  /** The in-flight print's own release, held so an unmount can take the printing class back
   *  off `<html>` without the effect needing a teardown of its own (see below). */
  const releasePrint = useRef<(() => void) | null>(null);
  useEffect(() => () => { releasePrint.current?.(); }, []);

  /**
   * W46-T20 — open the print dialog once the printed sheet is in the document, and give the
   * app back to the person however the dialog ends.
   *
   * THREE WAYS OUT, because none of them is reliable alone: `afterprint` (which does not fire
   * on a cancelled dialog in every engine), the `print` media query going false (Safari's
   * route), and a timeout (the honest backstop). `finish` is idempotent, so whichever arrives
   * first wins. Leaving the class on would hide the entire app behind a print rule.
   *
   * ⛔⛔ THIS EFFECT DELIBERATELY RETURNS NO TEARDOWN, AND THAT IS THE WHOLE FIX. A cleanup
   * that cancelled the queued frame would run IMMEDIATELY under development strict mode, which
   * mounts, tears down and mounts again: the frame would be cancelled before it ever fired and
   * the Export button would silently do nothing in dev while working in production, which is
   * the worst shape a defect can take. The latch above makes the second invocation a no-op
   * instead, `finish` is the only teardown there is, and `releasePrint` above hands an unmount
   * the same exit so the printing class can never be left behind.
   */
  useEffect(() => {
    if (!printing || printLatch.current) return;
    printLatch.current = true;
    const root = document.documentElement;
    const media = window.matchMedia ? window.matchMedia("print") : null;
    let done = false;
    let timer: ReturnType<typeof setTimeout> | undefined;
    function finish() {
      if (done) return;
      done = true;
      root.classList.remove(ROUTE_PRINTING_CLASS);
      window.removeEventListener("afterprint", finish);
      media?.removeEventListener?.("change", onMedia);
      if (timer !== undefined) clearTimeout(timer);
      printLatch.current = false;
      releasePrint.current = null;
      setPrinting(false);
    }
    function onMedia(event: MediaQueryListEvent) {
      if (!event.matches) finish();
    }
    releasePrint.current = finish;
    root.classList.add(ROUTE_PRINTING_CLASS);
    window.addEventListener("afterprint", finish);
    media?.addEventListener?.("change", onMedia);
    timer = setTimeout(finish, PRINT_RELEASE_MS);
    // One frame, so the sheet has been laid out under the print rules before the engine
    // snapshots it. Chrome blocks inside `print()` until the dialog closes; Firefox returns
    // immediately. Both ends are handled above. `done` is re-read here because an unmount in
    // that one frame has already released the print, and a dialog opened after the sheet was
    // removed would print a blank page.
    window.requestAnimationFrame(() => {
      if (done) return;
      try { window.print(); } catch { finish(); }
    });
  }, [printing]);
  const settleTimer = useRef<number | null>(null);
  const settleAbort = useRef<AbortController | null>(null);
  const settleGeneration = useRef(0);

  /** C1 keeps both halves explicit: a missing coordinate is a named fixed anchor, never a stop
   *  silently omitted from either the UI or the apply merge. */
  const locationPartition = useMemo(
    () => routeLocationPartition(stopIds, stopLabels, stopCoords),
    [stopIds, stopLabels, stopCoords],
  );
  const locatedStops = locationPartition.located;
  const locatedPids = locationPartition.locatedPids;
  const unlocated = locationPartition.unlocated;

  /**
   * ⭐⭐ W46-T22 / W46-T20 — THE MAPS LINKS MUST NOT OUTLIVE A REMOVED STOP.
   *
   * `mapLinks` and `mapLinkRefusal` are computed by MapView from the route's SERVER stop list, and
   * removing a stop writes only `removedStops` here: the host is never told, so until
   * `loadNamedRoutes` next fires the Google Maps section would still list, and Copy Maps links
   * would still copy, a customer the person has just removed. The printed PDF is already safe
   * because `routePrintStops` reads the pruned `stopIds`, and that is exactly why this one is
   * worth closing: the two hand-offs a rep actually leaves the building with would otherwise
   * DISAGREE about who is on the route.
   *
   * ⚠ Recomputed ONLY while a removal is pending. With none pending the host's own value is used
   * verbatim, so the normal path keeps MapView's `coarsePointer` and this cannot drift from it.
   */
  const removalPending = removedStops.routeId === activeStopRouteId && removedStops.pids.length > 0;
  const prunedMapLinks = useMemo(
    () => (removalPending ? normalizedRouteMapLinks(stopIds, locatedStops) : null),
    [removalPending, stopIds, locatedStops]
  );
  const shownMapLinks = prunedMapLinks ? prunedMapLinks.links : mapLinks;
  const shownMapLinkRefusal = prunedMapLinks ? prunedMapLinks.refusal : mapLinkRefusal;
  const startUnavailable = routeStartPid !== null && !locatedPids.includes(routeStartPid);
  const endUnavailable = routeEndPid !== null && !locatedPids.includes(routeEndPid);
  const endpointChoicesReady = locatedPids.length >= 2;
  // Endpoint and trip-shape choices change the route just as surely as a drag does.  Include
  // them in the debounce key so a chosen end cannot leave the previous open-path timing visible.
  const timerKey = `${activeStopRouteId}:${locatedPids.join(",")}:${unlocated.map((stop) => `${stop.pid}:${stop.reason}`).join("|")}:${roundTrip ? "round" : "one"}:${routeStartPid ?? ""}:${roundTrip ? "" : routeEndPid ?? ""}`;

  /**
   * The number a drag moves. ⛔ ARITHMETIC ONLY: `previewSeconds` is `tourLength` over
   * coordinates already on screen, so this runs at pointer speed and costs nothing. Nothing in
   * this function, or in the two handlers that call it, may reach the network.
   */
  const dragPreviewSeconds = (pids: number[]): number | null => {
    if (locatedStops.length < 2) return null;
    const seat = new Map(locatedStops.map((stop, index) => [stop.pid, index]));
    const order: number[] = [];
    for (const pid of pids) {
      const index = seat.get(pid);
      if (index !== undefined) order.push(index);
    }
    if (order.length < 2) return null;
    const geo: GeoStop[] = locatedStops.map((stop) => ({ lat: stop.lat, lon: stop.lon }));
    return previewSeconds(order, geo, haversineKm, roundTrip);
  };

  const cancelSettle = () => {
    if (settleTimer.current !== null) {
      window.clearTimeout(settleTimer.current);
      settleTimer.current = null;
    }
    settleAbort.current?.abort();
    settleAbort.current = null;
  };

  /** The one request. It is never called from a drag; only from the debounced timer below. */
  const settleRoute = async (pids: number[]) => {
    const byPid = new Map(locatedStops.map((stop) => [stop.pid, stop]));
    const stops = pids.map((pid) => byPid.get(pid)).filter(Boolean)
      .map((stop) => ({ lat: stop!.lat, lon: stop!.lon, pid: stop!.pid }));
    if (stops.length < 2) {
      setRouteAnswer(null);
      return;
    }
    const controller = new AbortController();
    settleAbort.current = controller;
    const generation = settleGeneration.current + 1;
    settleGeneration.current = generation;
    setTimerBusy(true);
    setTimerError(null);
    try {
      const res = await fetch(routeApplicationPath(ROUTE_DOOR, applicationId), {
        method: "POST", credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        signal: controller.signal,
        // ⛔ `pid` PER STOP IS LOAD-BEARING: without it the door answers with seat indices and
        // the one-click apply has no record to move. `fallback: true` is what makes an
        // arithmetic answer come back as `source: "haversine"` instead of an error.
        body: JSON.stringify({
          stops,
          locatedPids: pids,
          unlocated,
          mode: ROUTE_MODE,
          roundTrip,
          fallback: true,
          // The server owns the exact closing leg and constrained optimization.  Pids make the
          // selection stable across an order update; coordinates alone would turn it into seats.
          startPid: routeStartPid ?? undefined,
          endPid: roundTrip ? undefined : routeEndPid ?? undefined,
        }),
      });
      const payload = await res.json().catch(() => null);
      if (!routingAlive.current) return;
      if (settleGeneration.current !== generation) return;
      const answer = res.ok ? parseRouteAnswer(payload) : null;
      if (!answer) {
        setRouteAnswer(null);
        setTimerError(payload?.error?.message || "This Route could not be timed just now.");
        return;
      }
      setRouteAnswer(answer);
    } catch (failure) {
      if ((failure as { name?: string } | null)?.name === "AbortError") return;
      if (settleGeneration.current !== generation) return;
      setRouteAnswer(null);
      setTimerError("This Route could not be timed just now.");
    } finally {
      if (settleGeneration.current === generation) setTimerBusy(false);
    }
  };

  const scheduleSettle = (pids: number[]) => {
    cancelSettle();
    settleTimer.current = window.setTimeout(() => {
      settleTimer.current = null;
      void settleRoute(pids);
    }, SETTLE_DEBOUNCE_MS);
  };

  useEffect(() => {
    setRouteAnswer(null);
    setTimerError(null);
    if (locatedPids.length < 2) {
      cancelSettle();
      return;
    }
    scheduleSettle(locatedPids);
    return () => cancelSettle();
  // The key already carries the Route and its located stops in order; the callbacks below are
  // recreated every render and would restart the request on every keystroke elsewhere.
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [timerKey]);

  const beginStopDrag = (pid: number) => {
    holdTimerCard(false);
    cancelSettle();
    setDragPid(pid);
    setDragOrder(stopIds);
    setDragSeconds(dragPreviewSeconds(stopIds));
  };

  const previewStopDrag = (overPid: number) => {
    const moved = dragPid;
    if (moved === null || moved === overPid) return;
    const base = dragOrder || stopIds;
    const next = orderAfterMove(base, moved, overPid);
    if (next === base) return;
    setDragOrder(next);
    setDragSeconds(dragPreviewSeconds(next));
  };

  const endStopDrag = () => {
    setDragPid(null);
    setDragOrder(null);
    setDragSeconds(null);
  };

  const dropStopDrag = (target: MapRouteDto, overPid: number) => {
    const moved = dragPid;
    const order = moved === null ? null : orderAfterMove(dragOrder || stopIds, moved, overPid);
    endStopDrag();
    if (moved === null || !order) return;
    const seat = order.indexOf(moved);
    if (seat < 0 || stopIds[seat] === moved) return;
    commitStopMove(target, moved, String(seat + 1));
    scheduleSettle(order.filter((pid) => locatedPids.includes(pid)));
  };

  // A committed hold ends when the move has landed and a new drive time has settled. The timer
  // bounds it when no new answer comes (a refused move, fewer than two located stops).
  useEffect(() => {
    if (!timerHold?.committed) return;
    if (!busy && !timerBusy && routeAnswer !== null && routeAnswer !== timerHold.from) {
      setTimerHold(null);
      return;
    }
    const timer = window.setTimeout(() => setTimerHold(null), 8000);
    return () => window.clearTimeout(timer);
  }, [timerHold, busy, timerBusy, routeAnswer]);

  /** One click fills only the Route's located slots with the optimized located permutation. */
  const applyOptimizedOrder = (target: MapRouteDto) => {
    const answer = routeAnswer;
    if (!answer || applyBusy) return;
    const merged = mergeLocatedOrderAtAnchors(
      stopIds,
      locatedPids,
      answer.optimized.ordered,
    );
    const moves = merged && locatedRouteMovePlan(stopIds, merged, locatedPids);
    if (!merged || !moves) {
      setTimerError("The faster order no longer matches this Route's located stops.");
      return;
    }
    setApplyBusy(true);
    setTimerError(null);
    void (async () => {
      let failed = false;
      for (const move of moves) {
        const message = await onMoveToOrder(target, move.pid, move.position);
        if (message) {
          setTimerError(message);
          failed = true;
          break;
        }
      }
      setApplyBusy(false);
      if (!failed) scheduleSettle(answer.optimized.ordered);
    })();
  };

  const dragging = dragOrder !== null;
  const timerSaving = routeAnswer ? routeSaving(routeAnswer) : null;
  const timerCaveats = routeAnswer ? routeCaveats(routeAnswer) : [];
  const shownSeconds = dragging ? dragSeconds : dragPreviewSeconds(stopIds);
  const settledLabel = routeAnswer ? routeTimeLabel(routeAnswer.current) : null;
  const estimateLabel = shownSeconds === null ? null : `${formatSeconds(shownSeconds)} estimated`;
  const timerLabel = !dragging && settledLabel ? settledLabel : estimateLabel;
  const timerTone = !dragging && routeAnswer ? routeTimeTone(routeAnswer.current) : "estimated";

  /* ═════════ W51-T28 / C8 — ESCAPE BACKS OUT OF AN OPEN SAVED ROUTE ══════════════════════
   *
   * ⭐ THE LADDER THIS COMPLETES, TOP DOWN: the kit dialog, then the open Route, then the map
   * NAVIGATOR itself. The third rung is genuinely unreachable from this file and from MapView:
   * `mapNavigator === "routes"` is `routePanelOpen && !zoneNavigatorOpen`, and `routePanelOpen`
   * is `useState` in `CustomerGrid.tsx:3206` handed down as a read-only prop with no close
   * callback and no event channel. An optional prop nobody passes, or a client-side emit with no
   * listener, would each look exactly like a working close to a source scan while doing nothing
   * at all, so neither is here and no gate leg claims the rung.
   *
   * ⛔ THE CLAIM IS DROPPED WHILE THE TITLE IS BEING RENAMED, and that is not fussiness. The
   * arbiter's listener is CAPTURE PHASE on `document` and calls `stopPropagation`, so it runs
   * ahead of React's own handlers and the rename input's `Escape`-cancels-the-draft would simply
   * never fire again. Standing down while `titleDraft` is live leaves that behaviour exactly as
   * it shipped, and one Escape still means one close everywhere else.
   *
   * ⛔ `!deleteConfirm` IS THE SAME RULE APPLIED TO THE OTHER LIVE OVERLAY IN THIS PANEL. The
   * inline `role="alertdialog"` delete confirm below does not register with the arbiter and is
   * deliberately left as it is, because `verify_w44_map_routes.py`'s `route-update-delete` leg
   * pins that markup. Without this term Escape would resolve past it and close the whole Route
   * out from under an open confirm, which is a behaviour this ticket would have INTRODUCED.
   * ⚠ AND IT IS REACHED, THOUGH A GREP SAYS OTHERWISE. `grep deleteConfirm` finds no setter,
   * because the setter is `setDeleteConfirm` and the capital D breaks the substring; `Delete
   * Route` calls it, so that confirm really does open.
   *
   * ⚠ `cancelEditFirst` STAYS FALSE, matching the two Zone panels. One press, one close, which is
   * what every other overlay in this app already does.
   */
  const backToRoutes = useCallback(() => onActiveRouteChange(null), [onActiveRouteChange]);
  useEscapeClose(route !== null && titleDraft === null && !deleteConfirm, backToRoutes);

  /* ═════════ W54-T21 / D-673 — THE RUNGS THAT USED TO BE COVERED BY SILENCE ═══════════════
   *
   * ⛔⛔ THE STAND-DOWNS ABOVE ONLY WORKED WHILE NOTHING ELSE CLAIMED ESCAPE. Standing down means
   * "let the key fall through", and until this ticket it fell through to NOBODY, so React's own
   * handlers on the rename input and the search box still saw it and the delete confirm simply
   * ignored the press. D-673 puts a claim UNDERNEATH this whole panel - `CustomerGrid.tsx` closes
   * the navigator - so a fall-through now closes the entire navigator instead. Every surface the
   * open Route stands down for therefore has to claim the key itself, or the press it was meant
   * to reach would take the panel down with it.
   *
   * The route's close claim precedes these edit claims so the topmost edit receives Escape.
   *
   * ⚠ `renameEscaping` IS THE SAME ORDERING PROBLEM THE SHEET'S FORMULA EDITOR HAS. The arbiter
   * blurs the focused element before it calls close, and the folder rename input's blur is what
   * SAVES the new name, so a bare claim would have made Escape commit a rename it was pressed to
   * cancel. The blur defers its decision by one microtask and this flag, raised by the close,
   * wins that race by construction rather than by luck.
   *
   * ⚠ THE QUERY RUNG IS THE ONE BEHAVIOUR CHANGE, AND IT IS THE SMALL ONE. Escape with a typed
   * route filter clears the filter and leaves the panel open, which is what the box's own
   * handler always did; with the box empty there is nothing to clear and the press reaches the
   * navigator's close. The box keeps its own handler because `verify_map.py` pins it.
   */
  useEscapeClose(titleDraft !== null, () => setTitleDraft(null));
  useEscapeClose(deleteConfirm, () => setDeleteConfirm(false));
  useEscapeClose(renameId !== null, () => {
    renameEscaping.current = true;
    setRenameId(null);
  });
  useEscapeClose(routeQuery !== "", () => setRouteQuery(""));

  const routeDetail = () => {
    if (!route) return null;
    // ⭐ W46-T25 / RULING R2's guard stood here: a Route projected from a legacy `route_order`
    // column was refused until an administrator migrated it, because unlocking an unmigrated one
    // would leave two divergent copies. R2's order was migrate, verify, unlock, delete — and it
    // has now run to the end on every tenant schema, so there is no unmigrated Route left to
    // refuse and no legacy column left behind one.
    const canEdit = route.permission.canEdit;
    // ⚠ POSITIONS ARE READ OFF THE LIST THE PERSON IS LOOKING AT. Earlier, Later and the typed
    // Position box are all ordinal, and `routeStopMovePlan` validates against the ids it is
    // handed, so a just-removed stop still counted here would make every arrow below it move the
    // wrong stop for as long as the host had not refetched.
    const stopView: MapRouteDto = { ...route, visibleStopIds: stopIds };
    const editActionReason = !canEdit
      ? "Only the owner or an editor of the source View can change this Route."
      : busy
        ? "Wait for the current Route update to finish."
        : null;
    const applyActionReason = editActionReason
      || (applyBusy ? "The faster order is being applied."
        : locatedPids.length < 2 ? "Add map locations to at least two stops before optimizing."
          : timerBusy ? "The located stops are still being measured."
            : !routeAnswer ? "A measured route is needed before a faster order can be applied."
              : !timerSaving?.offer ? "The current located order is already the fastest measured order."
                : null);
    // ⚠ THE LIST SHOWS THE DRAG, THE ROUTE STILL HOLDS THE SAVED ORDER. `stopView` above is
    // built from `stopIds` on purpose: a drop is validated against the order the server last
    // confirmed, never against the arrangement being previewed on screen.
    const displayIds = dragOrder || stopIds;
    // ⚠ THE SAVED ORDER, NOT THE DRAG PREVIEW. A sheet handed to a rep states what the Route
    // IS, and `stopIds` is the order the server last confirmed. `routeStopIdentity` is passed in so
    // the name on paper is the same function as the name on screen, and every stop is on the
    // page whether or not it has a coordinate.
    const printStops = routePrintStops(
      stopIds, stopLabels, stopCoords,
      (label, pid) => routeStopIdentity(label, pid, stopLabelErrors[pid]), reversePrintLabels,
    );
    // ⚠ THE NAME HAS EXACTLY ONE WRITER NOW. `Save` below sends only the Maps URL, so an
    // abandoned draft in the title can never be committed by a control that says nothing about
    // names, and a saved rename can never be overwritten by a stale copy of the old one.
    const commitRouteRename = () => {
      const next = (titleDraft || "").trim();
      if (!next || busy) return;
      if (next === route.name) { setTitleDraft(null); return; }
      setBusy(true);
      void onUpdate(route, { name: next }).then((message) => {
        setError(message);
        if (!message) setTitleDraft(null);
      }).finally(() => setBusy(false));
    };
    return (
      <section className="cg-w44-route-nav" aria-label={`${route.name} route`}>
        <div className="cg-route-primary-actions" aria-label="Route actions">
          <button type="button" className="cg-w44-route-back" onClick={backToRoutes}>
            Back to routes
          </button>
        {/* ── W46-T23 / INSTRUCTION 19: THE ONE PLACE A ROUTE IS RENAMED. ──────────────
            It used to be two: the row menu on the list, and a "Route name" box buried in the
            edit block far below. Both are gone. The title itself turns into the field, so what
            a person reads when they are not renaming is still a title. */}
        <div className="cg-w44-route-title">
          <i style={{ backgroundColor: route.color }} aria-hidden="true" />
          {titleDraft === null ? <>
            <span className="cg-w46-route-name">{route.number}. {route.name}</span>
            {mayRouteAction(route, "rename") && (
              <button type="button" className="cg-w46-route-rename" aria-label={`Rename ${route.name}`}
                onClick={() => { setError(null); setTitleDraft(route.name); }}>Rename</button>
            )}
          </> : <span className="cg-w46-route-rename-edit">
            <input className="cg-input cg-w46-route-name-input" autoFocus value={titleDraft} maxLength={120}
              aria-label={`Rename ${route.name}`}
              onChange={(event) => setTitleDraft(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === "Enter") { event.preventDefault(); commitRouteRename(); }
                else if (event.key === "Escape") { event.preventDefault(); setTitleDraft(null); }
              }} />
            <button type="button" className="cg-w46-route-rename" disabled={busy || !titleDraft.trim()}
              onClick={commitRouteRename}>Save name</button>
            <button type="button" className="cg-w46-route-rename" disabled={busy}
              onClick={() => setTitleDraft(null)}>Cancel</button>
          </span>}
        </div>
        <p className="cg-w44-route-meta">
          {route.shared ? `Shared by ${route.owner || "another user"}` : route.sharedOut ? "Shared with others" : "Private"}
        </p>
        {/* ── W46-T19 / R9: the timer sits at the TOP, above the stops it is about. ─────────
            The figure is muted and says "estimated" until a road answer settles, per C2, and
            every caveat the answer carries is placed here rather than dropped. */}
        <section ref={timerCardRef}
          className={"cg-w46-route-timer" + (dragging ? " is-dragging" : "") + (timerHold ? " is-held" : "")}
          style={timerHold ? { height: `${timerHold.height}px` } : undefined} aria-label="Route drive time">
          <div className="cg-w46-timer-head">
            <span className={`cg-w46-timer-time${timerTone === "estimated" ? " is-estimated" : ""}`}>
              {timerLabel || "No drive time yet"}
            </span>
            <span className="cg-w46-timer-caption">
              {dragging ? "While this stop moves"
                : timerBusy ? "Measuring the drive"
                : timerLabel ? "Drive time" : "Add two located stops"}
            </span>
          </div>
          {/* ⭐⭐ OWNER 2026-08-31 - ONE WAY, OR BACK TO THE START. It sits INSIDE the timer,
              against the figure it changes, because a round trip adds the closing edge and
              therefore a different number; a control for it anywhere else would move a number
              the reader is not looking at. */}
          {onRoundTripChange && (
            <div className="w46-recur-row cg-w46-timer-trip">
              <span className="w46-recur-label">Trip</span>
              <div className="w46-recur-controls" role="group" aria-label="Trip shape">
                <button type="button" className={"w46-recur-pill" + (roundTrip ? "" : " is-on")}
                  aria-pressed={!roundTrip} onClick={() => onRoundTripChange(false)}>One way</button>
                <button type="button" className={"w46-recur-pill" + (roundTrip ? " is-on" : "")}
                  aria-pressed={roundTrip} onClick={() => { onRouteEndChange?.(null); onRoundTripChange(true); }}>Round trip</button>
              </div>
            </div>
          )}
          {(onRouteStartChange || onRouteEndChange) && (
            <div className="cg-w46-route-endpoints" role="group" aria-label="Route endpoints">
              <label>Start
                <select disabled={!endpointChoicesReady} value={routeStartPid ?? ""}
                  title={endpointChoicesReady ? undefined : "Add coordinates to at least two Route stops to choose endpoints."}
                  onChange={(e) => onRouteStartChange?.(e.target.value ? Number(e.target.value) : null)}>
                  <option value="">Automatic</option>
                  {startUnavailable && <option value={routeStartPid!} disabled>
                    {routeStopIdentity(stopLabels[routeStartPid!], routeStartPid!, stopLabelErrors[routeStartPid!])} (no map location)
                  </option>}
                  {locatedPids.map((pid) => <option key={pid} value={pid}>{routeStopIdentity(stopLabels[pid], pid, stopLabelErrors[pid])}</option>)}
                </select>
              </label>
              <label>End
                <select disabled={roundTrip || !endpointChoicesReady} value={roundTrip ? "" : (routeEndPid ?? "")}
                  title={roundTrip ? "Round trips return to the selected start."
                    : endpointChoicesReady ? undefined : "Add coordinates to at least two Route stops to choose endpoints."}
                  onChange={(e) => onRouteEndChange?.(e.target.value ? Number(e.target.value) : null)}>
                  <option value="">Automatic</option>
                  {endUnavailable && <option value={routeEndPid!} disabled>
                    {routeStopIdentity(stopLabels[routeEndPid!], routeEndPid!, stopLabelErrors[routeEndPid!])} (no map location)
                  </option>}
                  {locatedPids.filter((pid) => pid !== routeStartPid).map((pid) => <option key={pid} value={pid}>{routeStopIdentity(stopLabels[pid], pid, stopLabelErrors[pid])}</option>)}
                </select>
              </label>
            </div>
          )}
          {unlocated.length > 0 && (
            <p className="cg-w46-timer-note">
              Optimization covers {locatedPids.length.toLocaleString()} located stop{locatedPids.length === 1 ? "" : "s"}.
              The {unlocated.length.toLocaleString()} named stop{unlocated.length === 1 ? "" : "s"} without a usable map location
              stay at their current positions and are listed below.
            </p>
          )}
          {/* S78-T08: a drag hides the apply block but keeps its box, so the stop list under the
              pointer does not jump up when a stop is picked up. */}
          <div className={"cg-w46-timer-saving" + (dragging ? " is-drag-held" : "")}>
            {timerSaving?.offer && applyActionReason === null && <p>
              Reordering {unlocated.length ? "the located stops" : "these stops"} saves {formatSeconds(timerSaving.seconds)}, about{" "}
              {Math.abs(timerSaving.percent)}% of the drive.
            </p>}
            <button type="button" className="cg-w46-timer-apply"
              disabled={applyActionReason !== null}
              aria-describedby={applyActionReason
                ? applyActionReason === editActionReason
                  ? "cg-route-edit-reason"
                  : "cg-route-apply-reason"
                : undefined}
              title={applyActionReason || undefined}
              onClick={() => applyOptimizedOrder(stopView)}>
              {applyBusy ? "Applying the faster order" : "Apply the faster order"}
            </button>
            {applyActionReason && applyActionReason !== editActionReason && (
              <span id="cg-route-apply-reason" className="cg-route-action-reason">
                {applyActionReason}
              </span>
            )}
          </div>
          {timerSaving?.costs && (
            <p className={"cg-w46-timer-note" + (dragging ? " is-drag-held" : "")}>
              Reordering {unlocated.length ? "the located stops" : "these stops"} would add {formatSeconds(timerSaving.seconds)} on the road,
              so the current located order is the faster one.
            </p>
          )}
          {timerCaveats.map((caveat) => (
            <p className="cg-w46-timer-caveat" key={caveat}>{caveat}</p>
          ))}
          {timerError && <p className="cg-w46-timer-error" role="alert">{timerError}</p>}
        </section>
          <div className="cg-form-actions cg-route-save-actions">
            <button type="button" className="cg-btn cg-btn--primary"
              disabled={editActionReason !== null} title={editActionReason || undefined}
              onClick={() => finish(onUpdate(route, { mapsUrl: editMapsUrl.trim(),
                zoneId: editZoneId || null, color: editColor }))}>
              Save
            </button>
            <button type="button" className="cg-btn" disabled={editActionReason !== null}
              title={editActionReason || undefined} onClick={() => finish(onShare(route))}>
              Share
            </button>
            <button type="button" className="cg-btn" disabled={editActionReason !== null}
              title={editActionReason || undefined} onClick={() => setDeleteConfirm(true)}>
              Delete
            </button>
          </div>
          {/* During a stop move the busy reason stays announced but takes no line, so the list holds. */}
          {editActionReason && (
            <span id="cg-route-edit-reason"
              className={"cg-route-action-reason" + (timerHold?.committed ? " cg-sr-only" : "")}>
              {editActionReason}
            </span>
          )}
        </div>
        {/* S63-T01: the primary action region ends before this independently scrolling list. */}
        <div className="cg-route-stop-scroll" role="region" aria-label="Route stops" tabIndex={0}>
        {/* ⭐⭐ OWNER 2026-08-31 - THE STOP LIST IS THE RAIL, SAME FORMATTING.
            Owner: *"Same as the rail, same formatting too i believe"*, and then the exact scope:
            *"The only difference with the rail is that route you can have an x button to remove a
            record, and also an add record button where it provides the dropdown for the user to
            add more customer to the route."* So the row wears `.cg-view-row` / `.cg-view-main` /
            `.cg-view-text` / `.cg-view-name` exactly as a Route row does, drags whole rather than
            by a grip, and carries the ordinal in the purple disc where the rail carries the Route
            mark. The `<ol>` stays an `<ol>`: a drive IS an ordered list, and the class the panel's
            own stylesheet targets rides alongside the rail's. */}
        {stopIds.length ? (
          <ol className="cg-w44-route-stops cg-view-list">
            {displayIds.map((pid, index) => (
              <li key={pid}
                className={"cg-view-row cg-w46-stop-row" + (dragPid === pid ? " is-viewdrag" : "")}
                draggable={canEdit}
                onDragStart={(event) => {
                  if (!canEdit) return;
                  // S78-T08: a name tip opened by the press closes before the row moves.
                  const main = event.currentTarget.querySelector<HTMLElement>(".cg-view-main");
                  main?.dispatchEvent(new PointerEvent("pointerleave"));
                  if (main && document.activeElement === main) main.blur();
                  event.dataTransfer.effectAllowed = "move";
                  try { event.dataTransfer.setData("text/plain", String(pid)); }
                  catch { /* Some browsers refuse a payload; the drag still works. */ }
                  beginStopDrag(pid);
                }}
                onDragEnd={() => {
                  endStopDrag();
                  setTimerHold((current) => current && !current.committed ? null : current);
                }}
                onDragOver={(event) => {
                  if (dragPid === null) return;
                  event.preventDefault();
                  previewStopDrag(pid);
                }}
                onDrop={(event) => {
                  if (dragPid === null) return;
                  event.preventDefault();
                  dropStopDrag(stopView, pid);
                }}>
                {/* ⭐⭐ D-619 CLOSED WITHOUT REOPENING WHAT THE OWNER REMOVED. Deleting the per-stop
                    `< >` and the typed Position took the only KEYBOARD reorder with them, because
                    the drag grip is pointer-only. The owner's instruction was that drag replaces
                    those CONTROLS, not that reordering becomes pointer-only, so the gesture moves
                    onto the row's EXISTING focusable element: Alt + Up / Alt + Down, calling the
                    same `commitStopMove` the arrows called, with the same `stopView` target that
                    keeps a pruned list honest. No new tab stop, no new control, nothing wider.
                    ⛔ ALT IS DELIBERATE. A bare ArrowUp/ArrowDown inside a scrolling panel is the
                    reader moving through the list, and stealing it would make the list impossible
                    to walk. `aria-keyshortcuts` is what announces the pair. */}
                <button type="button" className="cg-view-main"
                  aria-label={`Open stop ${index + 1} record`}
                  aria-keyshortcuts={canEdit ? "Alt+ArrowUp Alt+ArrowDown" : undefined}
                  onKeyDown={(event) => {
                    if (!canEdit || !event.altKey || busy) return;
                    if (event.key === "ArrowUp" && index > 0) {
                      event.preventDefault();
                      commitStopMove(stopView, pid, String(index));
                    } else if (event.key === "ArrowDown" && index < displayIds.length - 1) {
                      event.preventDefault();
                      commitStopMove(stopView, pid, String(index + 2));
                    }
                  }}
                  aria-describedby={`cg-route-stop-name-${pid}`} onClick={() => onOpenRecord(pid)}>
                  {/* The ordinal is furniture: it says where in the drive this falls, and the
                      accessible name above already carries it, so it is hidden from the reader
                      rather than announced twice. */}
                  <span className="cg-w46-stop-index" aria-hidden="true">{index + 1}</span>
                  {/* S78-T08: a long name ends in an ellipsis and TruncatedName shows it in full on
                      hover and focus. The id moves to the wrapper because TruncatedName takes none. */}
                  <span className="cg-view-text" id={`cg-route-stop-name-${pid}`}>
                    {/* Keyed by seat: a reorder remounts the tip, so it never paints at a stale row. */}
                    <TruncatedName key={index} className={"cg-view-name" + (!stopLabels[pid] && stopLabelErrors[pid] ? " cg-w44-route-order-error" : "")}>
                      {routeStopIdentity(stopLabels[pid], pid, stopLabelErrors[pid])}
                    </TruncatedName>
                  </span>
                </button>
                {/* ⛔ OWNER 2026-08-31, TWICE: *"the < > for the route panel where you can choose
                    the numbers i thought they're deleted. I still see them up"*. Move earlier,
                    Position, Move and Move later are gone; DRAG IS THE GESTURE, exactly as it now
                    is for a Route row. The x stays because removing a stop is not a reorder and a
                    drag cannot express it - it is the one difference the owner named.
                    ⚠ THE COST, SAID OUT LOUD: those four controls were the KEYBOARD path, so a
                    stop can no longer be reordered without a pointer. Recorded here so the next
                    reader does not read it as an oversight and quietly put them back. */}
                {canEdit && (
                  <button type="button" className="cg-view-more cg-w46-stop-remove" disabled={busy}
                    aria-label={`Remove stop ${index + 1} from this route`}
                    title="Remove stop" onClick={() => commitStopRemove(route, pid)}>
                    <svg viewBox="0 0 16 16" aria-hidden="true"><path d="m4 4 8 8M12 4l-8 8" /></svg>
                  </button>
                )}
                {orderErrors[pid] && <span id={`cg-route-order-error-${pid}`}
                  className="cg-w44-route-order-error" role="alert">{orderErrors[pid]}</span>}
              </li>
            ))}
          </ol>
        ) : <p className="cg-w44-route-empty">No stops yet. Add customers from a route source.</p>}
        </div>
        {/* S63-T01 STOP SCROLL END — secondary Route tools follow; primary actions never do. */}
        {unlocated.length > 0 && (
          <section className="cg-w44-route-map-links" aria-labelledby="cg-route-unlocated-title">
            <div>
              <h3 id="cg-route-unlocated-title">Stops without map locations</h3>
              <p>These fixed anchors stay in their current positions when the located stops reorder.</p>
            </div>
            <div role="list" aria-label="Route stops without a map location">
              {unlocated.map((stop) => (
                <p className="cg-w46-timer-note" role="listitem" key={stop.pid}>
                  <strong>{routeStopIdentity(stopLabels[stop.pid], stop.pid, stopLabelErrors[stop.pid])}</strong>: {stop.reason}
                </p>
              ))}
            </div>
          </section>
        )}
        {/* ⭐⭐ OWNER 2026-08-31 - THE OTHER DIFFERENCE FROM THE RAIL: *"an add record button
            where it provides the dropdown for the user to add more customer to the route."*
            It wears the rail's own `.cg-create-new` shape, and its list is the rail's
            `.cg-find-view` box over the book the panel ALREADY HOLDS: `stopLabels` is built from
            `allRows` in `MapView`, so this needs no second fetch and can only offer records the
            reader can already see. ⛔ The write is the SAME membership door the x uses, with
            `present: true` - one door for both directions, so a stop cannot be added through a
            path the removal wall does not guard. */}
        {canEdit && (
          <div className="cg-create-new cg-w46-stop-add">
            <button type="button" className="cg-link-btn cg-create-btn" aria-haspopup="menu"
              aria-expanded={!!addStop} disabled={busy}
              onClick={(event) => {
                const anchor = event.currentTarget;
                setAddStop((current) => (current ? null : { anchor }));
                setAddStopQuery("");
              }}>
              <span className="cg-create-icon" aria-hidden="true">+</span>
              <span className="cg-create-label">Add record…</span>
            </button>
            {/* ⚠ `#cg-route-popover .cg-w46-stop-addmenu` in `styles/wave42/route-nav.css` is a
                DESCENDANT rule, so portalling takes this node out of its reach. That is the right
                outcome for every declaration in it: position, z-index, left/right and max-height
                are all supplied by `AnchoredOverlay` itself, and `.cg-view-menu` already declares
                `overflow-y: auto`. The one thing genuinely lost is the row's own
                `overflow: hidden; text-overflow: ellipsis`, and a candidate label is a CUSTOMER
                NAME of arbitrary length against a 260px menu — hence `.cg-mi-text` on the label
                below, which is the app's own ellipsis backstop and what every other
                `.cg-view-menu` row already wears. NO CSS FILE WAS TOUCHED FOR THIS. */}
            {addStop && (
              <AnchoredOverlay anchor={addStop.anchor} className="cg-view-menu cg-w46-stop-addmenu"
                placement="bottom-start" role="menu" ariaLabel="Add a record to this route"
                initialFocus=".cg-find-view input" onDismiss={() => setAddStop(null)}
                dataKind="route-add-stop-menu">
                <div className="cg-find-view">
                  <svg className="cg-find-view-icon" width="14" height="14" viewBox="0 0 16 16"
                    fill="none" aria-hidden="true">
                    <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
                    <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35"
                      strokeLinecap="round" />
                  </svg>
                  {/* ⛔ NO AUTO-FOCUS ATTRIBUTE AND NO ESCAPE HANDLER OF ITS OWN. The overlay
                      is what focuses this
                      input through `initialFocus`, and it takes Escape on a document capture
                      listener; a second owner of either would mean one key press racing two
                      handlers. The route search box further down keeps its own Escape, which
                      clears the query rather than closing anything, and is untouched. */}
                  <input type="text" value={addStopQuery} placeholder="Find…"
                    aria-label="Find a record to add to this Route"
                    onChange={(event) => setAddStopQuery(event.target.value)} />
                </div>
                {addableStops.length ? addableStops.map((candidate) => (
                  <button type="button" role="menuitem" key={candidate.pid} disabled={busy}
                    onClick={() => { setAddStop(null); commitStopAdd(route, candidate.pid); }}>
                    <span className="cg-mi-text">{candidate.label}</span>
                  </button>
                )) : (
                  <span className="cg-w44-route-empty">
                    {addStopQuery.trim()
                      ? "No record matches that search."
                      : "Every record you can see is already on this Route."}
                  </span>
                )}
              </AnchoredOverlay>
            )}
          </div>
        )}
        {mapsUrl && <a className="cg-w44-route-maps" href={mapsUrl} target="_blank" rel="noopener noreferrer">Open Maps</a>}
        {route.mapsUrl && !mapsUrl && <span className="cg-w44-route-empty">Maps link is unavailable.</span>}
        <section className="cg-w44-route-map-links" aria-labelledby="cg-route-map-links-title">
          <div>
            <h3 id="cg-route-map-links-title" className="cg-gmaps-heading"><GoogleMapsMark />Google Maps</h3>
            <p>Current ordered Route stops, split into links of at most 10 stops.</p>
          </div>
          {shownMapLinkRefusal ? (
            <span className="cg-w44-route-warning" role="alert">{shownMapLinkRefusal}</span>
          ) : shownMapLinks.length ? <>
            <ol>
              {shownMapLinks.map((link) => (
                <li key={`${link.index}:${link.start}:${link.end}`}>
                  <a href={link.url} target="_blank" rel="noopener noreferrer">
                    Link {link.index} - Stops {link.start + 1} to {link.end}
                  </a>
                  <small>{link.stopIds.length.toLocaleString()} stops</small>
                </li>
              ))}
            </ol>
            <button type="button" className="cg-route-copy-links" onClick={copyMapLinks}>
              Copy Maps links
            </button>
          </> : (
            <span className="cg-w44-route-empty">Add at least two located stops to open this Route in Maps.</span>
          )}
          {mapCopyNotice && <span className="cg-w44-route-empty" role="status">{mapCopyNotice}</span>}
          {mapCopyError && <span className="cg-w44-route-warning" role="alert">{mapCopyError}</span>}
        </section>
        {/* ── W46-T20 / INSTRUCTION 10 / R6: the sheet the sales team is handed. ───────────
            A plain print, so the person keeps their browser's own Save as PDF, its paper
            size and its margins. A div, and deliberately neither a section nor an outer
            complementary landmark element: this panel's structure is pinned by
            verify_grid_ux, which counts the one and forbids the other outright, and the
            export is a control on the Route rather than a region of it. */}
        <div className="cg-w46-route-export">
          <h3>Export</h3>
          <p>A printable stop list with a Google Maps link on every stop. Choose Save as PDF
            in the print dialog.</p>
          <button type="button" className="cg-w46-route-export-open"
            disabled={printing || preparingPrint || !stopIds.length}
            onClick={() => {
              if (preparingPrint) return;
              setError(null);
              setPreparingPrint(true);
              // R10: this is an address fallback for coordinate-only stops, not a browser-side
              // geocoder.  An unavailable/configuration failure intentionally still opens the
              // PDF with the established honest no-address copy.
              void routeReversePrintLabels(storageKey, stopIds, stopLabels, stopCoords)
                .catch(() => ({}))
                .then((labels) => { setReversePrintLabels(labels); setPrinting(true); })
                .finally(() => setPreparingPrint(false));
            }}>
            {preparingPrint ? "Preparing printable addresses…" : "Export to PDF"}
          </button>
          {!stopIds.length && (
            <span className="cg-w44-route-empty">Add a stop before exporting this route.</span>
          )}
        </div>
        {printing && createPortal(
          /* ⛔ MOUNTED ON `document.body`, WHICH IS THE POINT. The isolation rule hides every
             child of `<body>` and reveals this one, so the shell, the grid, the map and this
             very panel stay off the paper. Inside the Route panel it would inherit that
             panel's scroll and overflow, and a long Route would print its first page only.
             ⭐ EVERY MAP LINK IS A REAL `<a href>` WITH VISIBLE TEXT: that is what makes a
             browser emit a clickable link annotation into the saved PDF. A CSS `content:`
             string, or a URL printed as text, is not one. */
          <div className="cg-w46-route-print-portal">
            <div className="cg-w46-route-print-sheet">
              <h1 className="cg-w46-route-print-title">{route.number}. {route.name}</h1>
              <p className="cg-w46-route-print-meta">
                {printStops.length.toLocaleString()} stops, in driving order.
              </p>
              <ol className="cg-w46-route-print-stops">
                {printStops.map((stop) => (
                  <li key={stop.pid} className="cg-w46-route-print-stop">
                    <span className="cg-w46-print-pos">{stop.position}</span>
                    <span className="cg-w46-print-body">
                      <span className="cg-w46-print-name">{stop.name}</span>
                      {/* The address line is ALWAYS printed, because a rep drives to an
                          address. When the record has no name at all the line above already
                          IS the address, and saying so beats printing it twice. */}
                      <span className="cg-w46-print-address">
                        {stop.nameIsAddress
                          ? "No name on record. The line above is the address."
                          : stop.address || "No address on record."}
                      </span>
                      {stop.mapsUrl ? (
                        <a className="cg-w46-print-link" href={stop.mapsUrl}
                          rel="noopener noreferrer">
                          Open {stop.name} in Google Maps
                        </a>
                      ) : (
                        <span className="cg-w46-print-nolink">
                          No map pin for this stop. Drive to the address above.
                        </span>
                      )}
                    </span>
                  </li>
                ))}
              </ol>
            </div>
          </div>,
          document.body,
        )}
        {canEdit ? (
          <div className="cg-w44-route-edit" aria-label="Edit Route">
            <label className="cg-w44-route-label">Google Maps URL
              <input className="cg-input" type="url" value={editMapsUrl} maxLength={2048}
                placeholder="https://www.google.com/maps/..." onChange={(event) => setEditMapsUrl(event.target.value)} />
            </label>
            {/* OWNER 2026-08-31 item 4, second half: the Maps link cap belongs to the Google Maps
                block, not to Daily delivery. It is a property of the LINK, and it was sitting
                under a scheduling heading where nobody looking for it would think to read. The
                value still travels in the delivery request; only its place on screen moved. */}
            <label className="cg-w44-route-label">Stops per Maps link
              <input className="cg-input" type="number" min={2} max={10} value={deliveryMapsPerLink}
                onChange={(event) => setDeliveryMapsPerLink(
                  Math.max(2, Math.min(10, Number(event.target.value) || 2))
                )} />
            </label>
            {/* OWNER 2026-08-31 item 2 - EVERY ROUTE GETS ITS OWN COLOUR, EDITABLE HERE.
                The colour was already the record's own and already painted the line and the
                sidebar swatch (`MapView.tsx::overlaidRoutes`); what did not exist was any way to
                CHANGE it. `route_system.py::put_route` already reads `raw.get("color", ...)`
                through `_color`, so the server door needed nothing: an unrecognised value falls
                back to the ordinal default rather than painting the SVG initial black. */}
            <div className="cg-w44-route-label">Route colour
              <div className="cg-w44-route-colors">
                {ROUTE_SWATCHES.map((swatch) => (
                  <button key={swatch} type="button" disabled={busy}
                    className={"cg-w44-route-swatch" + (editColor.toUpperCase() === swatch ? " is-on" : "")}
                    style={{ backgroundColor: swatch }} aria-pressed={editColor.toUpperCase() === swatch}
                    aria-label={`Use ${swatch} for this Route`} onClick={() => setEditColor(swatch)} />
                ))}
                <input className="cg-w44-route-colorpick" type="color" value={editColor} disabled={busy}
                  aria-label="Pick any colour for this Route"
                  onChange={(event) => setEditColor(event.target.value.toUpperCase())} />
              </div>
            </div>
            {/* ⭐⭐ D-599 / W46-T22 - THE ROUTE'S ZONE. Until wave 46's hotfix no route record
                carried a zone at all, so this control had nothing to write and did not exist:
                Routes and Zones were two separate tables and `__zone__` was a field on a CUSTOMER
                row. It saves through the same Save button as the Maps URL beside it,
                because both are properties of the Route and two save buttons on one form is how
                a user loses the edit they did not press.
                ⚠ THE UNAVAILABLE ARM IS DELIBERATE. A Route can hold a zone this reader cannot
                currently see; rendering the raw id as a disabled option says so, where dropping
                it would silently clear the field on the next save. */}
            <label className="cg-w44-route-label">Zone
              <select className="cg-input" value={editZoneId} disabled={busy}
                onChange={(event) => setEditZoneId(event.target.value)}>
                <option value="">No zone</option>
                {editZoneId && !zones.some((zone) => zone.id === editZoneId) && (
                  <option value={editZoneId} disabled>{editZoneId} (unavailable)</option>
                )}
                {zones.map((zone) => (
                  <option key={zone.id} value={zone.id}>{zone.name}</option>
                ))}
              </select>
            </label>
            {!zones.length && (
              <span className="cg-w44-route-empty">Draw a Zone on the map first, then a Route
                can belong to it.</span>
            )}
            {deleteConfirm && (
              <div role="alertdialog" aria-label={`Delete ${route.name} Route`} aria-describedby="cg-route-delete-copy">
                <p id="cg-route-delete-copy">Delete this Route and its saved stop order?</p>
                <div className="cg-form-actions">
                  <button type="button" className="cg-btn cg-btn--danger" disabled={busy}
                    onClick={() => { setBusy(true); void onDelete(route).then((message) => {
                      setError(message); if (!message) onActiveRouteChange(null);
                    }).finally(() => setBusy(false)); }}>Confirm delete</button>
                  <button type="button" className="cg-btn" disabled={busy} onClick={() => setDeleteConfirm(false)}>Cancel</button>
                </div>
              </div>
            )}
          </div>
        ) : null}
        {canEdit && (
          /* ⭐ OWNER 2026-08-31 item 4 - THIS IS THE "REPEAT EVERY" CONTROL, SAID ABOUT A ROUTE.
             Owner: *"this whole function needs to be almost the exact same formatting as our
             'Repeat every' layout under date field. its practically the same thing."* It IS the
             same thing: a rule that fires on a cadence. So it borrows the date editor's own
             `w46-recur-*` contract (`field-panels.css`) rather than growing a second look for
             one idea, and the sentence reads left to right the way that one does.
             ⛔ THE CADENCE IS NOT A CHOICE YET, AND THE CONTROL SAYS SO RATHER THAN OFFERING
             ONE. `route_delivery` mints a fixed daily 08:00 cron; rendering an interval box
             this server would ignore is the shape of a control that lies. */
          <section className="cg-w44-route-delivery" aria-labelledby="cg-route-delivery-title">
            <div className="w46-recur-head">
              <h3 className="cg-pop-title" id="cg-route-delivery-title">Daily delivery</h3>
            </div>
            <div className="w46-recur-card">
              <div className="w46-recur-row">
                <span className="w46-recur-label">Repeat every</span>
                <div className="w46-recur-controls">
                  <span className="w46-recur-word">day, at 08:00 ({deliveryTimezone})</span>
                </div>
              </div>
              <div className="w46-recur-row">
                <label className="w46-recur-label" htmlFor="cg-route-delivery-recipient">Send to</label>
                <div className="w46-recur-controls">
                  <select id="cg-route-delivery-recipient" className="cg-input" style={{ width: "100%" }}
                    title={deliveryRecipient || "Choose recipient"}
                    value={deliveryRecipient} disabled={deliveryBusy || deliveryRecipients === null}
                    onChange={(event) => {
                      setDeliveryRecipient(event.target.value);
                      setDeliveryError(null);
                      setDeliveryNotice(null);
                    }}>
                    <option value="">Choose recipient</option>
                    {(deliveryRecipients || []).map((person) => (
                      <option key={person.username} value={person.username}>
                        {person.name} ({person.username})
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              <div className="w46-recur-row">
                <span className="w46-recur-label">Stop order</span>
                <div className="w46-recur-controls">
                  <span className="w46-recur-word">
                    Frozen as it stands now, {stopIds.length.toLocaleString()} stops.
                  </span>
                </div>
              </div>
              <div className="cg-form-actions">
                <button type="button" className="cg-btn cg-btn--primary"
                  disabled={deliveryBusy || stopIds.length < 2 || !recipientNames.has(deliveryRecipient)}
                  onClick={() => scheduleDelivery(route)}>
                  {deliveryBusy ? "Scheduling" : "Schedule delivery"}
                </button>
              </div>
            </div>
            {stopIds.length < 2 && (
              <span className="cg-w44-route-empty">Add at least two stops before scheduling.</span>
            )}
            {deliveryRecipientError && (
              <div className="cg-form-actions">
                <span className="cg-w44-route-warning" role="alert">{deliveryRecipientError}</span>
                <button type="button" className="cg-btn" onClick={onReloadDeliveryRecipients}>Retry</button>
              </div>
            )}
            <div className="cg-w44-route-delivery-list" aria-label="Existing Route deliveries">
              {deliveries === null ? (
                <span className="cg-w44-route-empty">Loading deliveries.</span>
              ) : deliveries.length === 0 ? (
                <span className="cg-w44-route-empty">No deliveries scheduled.</span>
              ) : (
                <ul>
                  {deliveries.map((delivery) => (
                    <li key={delivery.id}>
                      <div className="cg-w44-route-delivery-audit">
                        <strong>{delivery.name}</strong>
                        <dl>
                          <div><dt>Source View</dt><dd>{delivery.snapshot.sourceViewName} <code>{delivery.snapshot.sourceViewId}</code></dd></div>
                          <div><dt>Pinned revision</dt><dd><code>{delivery.snapshot.sourceViewRevision}</code></dd></div>
                          <div><dt>Schedule</dt><dd>{delivery.schedule.cron || "Not scheduled"} - {delivery.schedule.enabled === false ? "Paused" : "Active"}</dd></div>
                          <div><dt>Timezone</dt><dd>{delivery.snapshot.timezone}</dd></div>
                          <div><dt>Recipient</dt><dd>{delivery.recipient}</dd></div>
                          <div><dt>Ordered stop IDs</dt><dd><code>{delivery.snapshot.orderedStopIds.join(", ")}</code></dd></div>
                          <div><dt>Maps link cap</dt><dd>{delivery.snapshot.mapsPerLink} stops per link</dd></div>
                        </dl>
                      </div>
                      <button type="button" className="cg-btn" disabled={deliveryBusy}
                        aria-label={`Remove ${delivery.name}`} onClick={() => removeDelivery(route, delivery)}>
                        Remove
                      </button>
                    </li>
                  ))}
                </ul>
              )}
            </div>
            {deliveryNotice && <span className="cg-w44-route-empty" role="status">{deliveryNotice}</span>}
            {deliveryError && <span className="cg-w44-route-warning" role="alert">{deliveryError}</span>}
          </section>
        )}
        {error && <span className="cg-w44-route-empty" role="status">{error}</span>}
      </section>
    );
  };
  if (route && !applicationName) return routeDetail();

  if (creating) {
    const createReason = busy
      ? "Wait for the Route creation to finish."
      : !name.trim() ? "Enter a Route name."
        : !source ? "Choose a Route source."
          : source.pids.length === 0 ? "Choose a source with at least one record."
            : null;
    return (
      <section className="cg-w44-route-nav" aria-label="Create route">
        <div className="cg-route-primary-actions" aria-label="Route actions">
          <button type="button" className="cg-w44-route-back" disabled={busy}
            title={busy ? "Wait for the Route creation to finish." : undefined}
            onClick={() => setCreating(false)}>Back to routes</button>
          <div className="cg-form-actions">
            <button type="button" className="cg-btn cg-btn--primary"
              disabled={createReason !== null} title={createReason || undefined}
              onClick={() => { if (!source) return; setBusy(true); void onCreate(name.trim(), source).then((message) => {
                setError(message); if (!message) { setName(""); setCreating(false); }
              }).finally(() => setBusy(false)); }}>Create route</button>
          </div>
          {createReason && <span className="cg-route-action-reason">{createReason}</span>}
          {error && <span className="cg-w44-route-warning" role="status">{error}</span>}
        </div>
        <label className="cg-w44-route-label">Route name
          <input className="cg-input" value={name} maxLength={120} onChange={(event) => setName(event.target.value)} />
        </label>
        <fieldset className="cg-w44-route-sources"><legend>Route source</legend>
          {sources.map((item) => <label key={item.id}><input type="radio" name="route-source"
            checked={sourceId === item.id} onChange={() => setSourceId(item.id)} />
            {item.label} ({item.pids.length.toLocaleString()})</label>)}
        </fieldset>
      </section>
    );
  }

  /* ── The rail itself ─────────────────────────────────────────────────────────────────────
     One recursive level: folders first as `.cg-fold` disclosure groups, then the Routes filed
     at that level as `.cg-view-row`s. Both kinds of row drag, and both drop ABOVE the row they
     are released on, which is the gesture `ViewSidebar` teaches.

     ⛔ MOVE UP / MOVE DOWN ARE GONE FROM THE "..." MENU, on the owner's ruling that drag
     REPLACES them. Two ways to reorder in one rail is what made the menu long enough to need
     scrolling, and the length of that menu is half of why the row could not be compact. */
  const dropReorder = (siblings: string[], moved: string, over: string, kind: "route" | "folder") => {
    const from = siblings.indexOf(moved);
    const to = siblings.indexOf(over);
    if (from < 0 || to < 0 || from === to) return;
    const next = [...siblings];
    next.splice(to, 0, next.splice(from, 1)[0]);
    finish(kind === "route" ? onRouteReorder(next) : onFolderReorder(next));
  };

  const renderLevel = (parent: string, depth: number): ReactElement[] => {
    const out: ReactElement[] = [];
    const childFolders = (foldersByParent.get(parent) || [])
      .filter((folder) => !query || folderMatches.has(folder.id));
    const childRoutes = (routesByFolder.get(parent) || [])
      .filter((item) => !query || item.name.toLowerCase().includes(query));
    const folderIds = childFolders.map((folder) => folder.id);
    const routeIds = childRoutes.map((item) => item.id);

    for (const folder of childFolders) {
      // A live find shows every surviving folder open, whatever the stored set holds, and the
      // chevron is drawn from THAT state so a click means what it looks like (W41-T34's rule).
      const shut = !query && shutFolders.has(folder.id);
      const empty = !(foldersByParent.get(folder.id) || []).length
        && !(routesByFolder.get(folder.id) || []).length;
      out.push(
        <div className={"cg-fold" + (rowOver === `folder:${folder.id}` && rowDrag ? " is-drop" : "")}
          key={`folder:${folder.id}`} style={depth ? { marginLeft: 12 } : undefined}>
          <div className="cg-fold-head"
            draggable={renameId !== `folder:${folder.id}`}
            onDragStart={(event) => {
              event.dataTransfer.setData(ROUTE_FOLDER_DRAG, folder.id);
              event.dataTransfer.effectAllowed = "move";
              setRowDrag(`folder:${folder.id}`);
            }}
            onDragEnd={() => { setRowDrag(null); setRowOver(null); }}
            onDragOver={(event) => {
              if (!event.dataTransfer.types.includes(ROUTE_FOLDER_DRAG) && !event.dataTransfer.types.includes(ROUTE_DRAG)) return;
              event.preventDefault();
              setRowOver(`folder:${folder.id}`);
            }}
            onDragLeave={() => setRowOver((current) => current === `folder:${folder.id}` ? null : current)}
            onDrop={(event) => {
              const movedRoute = event.dataTransfer.getData(ROUTE_DRAG);
              const moved = event.dataTransfer.getData(ROUTE_FOLDER_DRAG);
              setRowDrag(null); setRowOver(null);
              const routeToMove = routes.find((item) => item.id === movedRoute);
              if (routeToMove) { event.preventDefault(); finish(onRouteMove(routeToMove, folder.id)); return; }
              if (!moved || moved === folder.id) return;
              event.preventDefault();
              dropReorder(folderIds, moved, folder.id, "folder");
            }}>
            <button type="button" className="cg-fold-toggle" aria-expanded={!shut}
              aria-label={`${shut ? "Open" : "Close"} folder ${folder.name}`}
              onClick={() => toggleFolder(folder.id)}>
              <FolderMark size={16} />
              {renameId === `folder:${folder.id}` ? (
                <input className="cg-input cg-fold-rename" autoFocus defaultValue={folder.name}
                  aria-label={`Rename ${folder.name}`} onClick={(event) => event.stopPropagation()}
                  onBlur={(event) => {
                    // W54-T21 - deferred by ONE microtask so an Escape that blurred this input on
                    // its way to cancelling the rename gets to say so first. A click away, a Tab
                    // and the Enter path all still save, one microtask later, unchanged.
                    const value = event.target.value.trim();
                    renameEscaping.current = false;
                    queueMicrotask(() => {
                      if (renameEscaping.current) return;
                      if (value && value !== folder.name) finish(onFolderUpdate(folder, { name: value }));
                      setRenameId(null);
                    });
                  }}
                  onKeyDown={(event) => {
                    if (event.key === "Enter") event.currentTarget.blur();
                    if (event.key === "Escape") setRenameId(null);
                  }} />
              ) : <span className="cg-fold-name">{folder.name}</span>}
              <svg className={"cg-fold-chev" + (shut ? " is-shut" : "")} width="12" height="12"
                viewBox="0 0 16 16" fill="none" aria-hidden="true">
                <path d="m4 6 4 4 4-4" stroke="currentColor" strokeWidth="1.5"
                  strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
            <button type="button" className="cg-view-more" aria-label={`Actions for ${folder.name}`}
              aria-haspopup="menu" aria-expanded={menu?.id === `folder:${folder.id}`}
              onClick={(event) => {
                const anchor = event.currentTarget;
                setMenu((current) => (current?.id === `folder:${folder.id}`
                  ? null
                  : { id: `folder:${folder.id}`, anchor }));
              }}>...</button>
            {menu && menu.id === `folder:${folder.id}` && (
              <AnchoredOverlay anchor={menu.anchor} className="cg-view-menu" placement="bottom-end"
                role="menu" ariaLabel={`Actions for folder ${folder.name}`}
                onDismiss={() => setMenu(null)} dataKind="route-folder-menu">
              <button type="button" role="menuitem"
                onClick={() => { setRenameId(`folder:${folder.id}`); setMenu(null); }}>Rename</button>
              {folder.parent && <button type="button" role="menuitem"
                onClick={() => { setMenu(null); finish(onFolderUpdate(folder, { parent: null })); }}>Move to Routes</button>}
              {folders.filter((target) => target.id !== folder.id && target.id !== folder.parent).map((target) =>
                <button type="button" role="menuitem" key={target.id}
                  onClick={() => { setMenu(null); finish(onFolderUpdate(folder, { parent: target.id })); }}>
                  Move into {target.name}
                </button>)}
              <button type="button" role="menuitem"
                onClick={() => { setMenu(null); setPendingDelete({ kind: "folder", folder }); }}>Delete</button>
              </AnchoredOverlay>
            )}
          </div>
          {!shut && renderLevel(folder.id, depth + 1)}
          {!shut && empty && <p className="cg-fold-empty">This folder is empty.</p>}
        </div>
      );
    }

    for (const item of childRoutes) {
      out.push(
        <div key={item.id} style={depth ? { marginLeft: 12 } : undefined}
          className={"cg-view-row"
            + (activeRouteId === item.id ? " is-active" : "")
            + (item.outsideFilter ? " is-outside" : "")
            + (rowDrag === `route:${item.id}` ? " is-viewdrag" : "")
            + (rowOver === `route:${item.id}` && rowDrag && rowDrag !== `route:${item.id}`
              ? " is-drop-above" : "")}
          draggable={renameId !== item.id}
          onDragStart={(event) => {
            event.dataTransfer.setData(ROUTE_DRAG, item.id);
            event.dataTransfer.effectAllowed = "move";
            setRowDrag(`route:${item.id}`);
          }}
          onDragEnd={() => { setRowDrag(null); setRowOver(null); }}
          onDragOver={(event) => {
            if (!event.dataTransfer.types.includes(ROUTE_DRAG)) return;
            event.preventDefault();
            setRowOver(`route:${item.id}`);
          }}
          onDragLeave={() => setRowOver((current) => current === `route:${item.id}` ? null : current)}
          onDrop={(event) => {
            const moved = event.dataTransfer.getData(ROUTE_DRAG);
            setRowDrag(null); setRowOver(null);
            if (!moved || moved === item.id) return;
            event.preventDefault();
            dropReorder(routeIds, moved, item.id, "route");
          }}>
          {/* ⭐ W47-T07 / instruction 9: a REAL checkbox, not a pressed button.
              ⛔ OWNER 2026-08-31, ON SEEING IT DEPLOYED: *"remove the dots below the checkbox on
              the routes rail, its ugly af, what is that even there for"*. The dot was the Route's
              colour - the SAME `item.color` the drawn line uses - and it is gone as a separate
              element. The colour is NOT lost: it tints the checkbox itself through `accentColor`,
              so ticking a Route still shows you which line on the map is about to be yours,
              without a second mark in the row. */}
          <label className="cg-w44-route-toggle" title={`Show ${item.name} on the map`}>
            {/* ⚠ `accent-color` PAINTS A CHECKED BOX ONLY, so on its own it left an unticked rail
                with no colour anywhere - a real gap against the owner's *"each route should have a
                color edit function"*, and one the removal of the dot created. The ring is the
                same checkbox wearing its own colour at rest, NOT the second mark that was
                removed: it is drawn on the input itself, adds no element and no width. */}
            <input type="checkbox" checked={selectedIds.has(item.id)}
              style={{ accentColor: item.color, boxShadow: `0 0 0 1.5px ${item.color}` }}
              aria-label={`Show ${item.name} on the map`}
              onChange={() => onToggle(item)} />
          </label>
          <button type="button" className="cg-view-main" onClick={(event) => {
            // ⚠ Read the scroll at the click: the last `onScroll` can land a frame late.
            const list = event.currentTarget.closest<HTMLElement>(".cg-route-index-scroll");
            if (list) listScroll.current = list.scrollTop;
            setError(null); setCreating(false); onActiveRouteChange(item.id);
          }}>
            {/* Owner item 3: the ONE difference from a view row. Every Route wears the same
                waypoint mark; the ordinal that used to prefix the name is gone from the rail. */}
            <IconRoute />
            <span className="cg-view-text">
              <span className="cg-view-name">{item.name}</span>
              {(item.shared || item.sharedOut || item.outsideFilter) && (
                <span className="cg-view-desc">
                  {item.shared ? `Shared by ${item.owner || "another user"}`
                    : item.sharedOut ? "Shared" : "Outside filter"}
                </span>
              )}
            </span>
          </button>
          <button type="button" className="cg-view-more" aria-label={`Actions for ${item.name}`}
            aria-haspopup="menu" aria-expanded={menu?.id === item.id}
            onClick={(event) => {
              const anchor = event.currentTarget;
              setMenu((current) => (current?.id === item.id ? null : { id: item.id, anchor }));
            }}>...</button>
          {menu && menu.id === item.id && (
            <AnchoredOverlay anchor={menu.anchor} className="cg-view-menu" placement="bottom-end"
              role="menu" ariaLabel={`Actions for ${item.name}`} onDismiss={() => setMenu(null)}
              dataKind="route-menu">
            <button type="button" role="menuitem" disabled={!mayRouteAction(item, "duplicate")}
              onClick={() => { setMenu(null); finish(onDuplicate(item)); }}>Duplicate</button>
            <button type="button" role="menuitem" disabled={!mayRouteAction(item, "star")}
              onClick={() => { setMenu(null); finish(onUpdate(item, { starred: !item.starred })); }}>
              {item.starred ? "Unstar" : "Star"}
            </button>
            <button type="button" role="menuitem" disabled={!mayRouteAction(item, "share")}
              onClick={() => { setMenu(null); finish(onShare(item)); }}>Share</button>
            {folders.filter((folder) => folder.id !== item.folderId).map((folder) =>
              <button type="button" role="menuitem" key={folder.id}
                onClick={() => { setMenu(null); finish(onRouteMove(item, folder.id)); }}>Move to {folder.name}</button>)}
            {item.folderId && <button type="button" role="menuitem"
              onClick={() => { setMenu(null); finish(onRouteMove(item, null)); }}>Move to Routes</button>}
            <button type="button" role="menuitem" disabled={!mayRouteAction(item, "delete")}
              onClick={() => { setMenu(null); setPendingDelete({ kind: "route", item }); }}>Delete</button>
            </AnchoredOverlay>
          )}
        </div>
      );
    }
    return out;
  };

  const levelRows = renderLevel(ROOT_LEVEL, 0);
  // A failed read is not "no routes": the load error leads the list and stands in for the empty state.
  const rows = routesLoadError ? [
    <div key="routes-load-error" className="cg-form-actions">
      <span className="cg-w44-route-warning" role="alert">Routes could not load</span>
      {onRetryRoutes && <button type="button" className="cg-btn" onClick={onRetryRoutes}>Retry</button>}
    </div>,
    ...levelRows,
  ] : levelRows;
  const inventory = (
    <>
      <div className="cg-route-primary-actions" aria-label="Route actions">
        {applicationName ? (
          <p className="cg-app-route-context"><strong>{applicationName}</strong></p>
        ) : null}
      {/* Owner item 3 - the SAME create door the Views rail mounts (`.cg-create-new` /
          `.cg-create-btn` are a shared contract, see `ViewSidebar.tsx`'s note on them), with the
          two things a Routes rail can make behind it. */}
        <div className="cg-create-new">
        <button type="button" className="cg-link-btn cg-create-btn" aria-haspopup="menu"
          aria-expanded={!!createMenu}
          onClick={(event) => {
            /* ⚠ THE CROSS-CLEAR SURVIVES THE CONVERSION: opening Create still closes any open row
               or folder menu, which is what kept two menus from standing open at once. */
            const anchor = event.currentTarget;
            setMenu(null);
            setCreateMenu((current) => (current ? null : { anchor }));
          }}>
          <span className="cg-create-icon" aria-hidden="true">+</span>
          <span className="cg-create-label">Create new…</span>
        </button>
        {createMenu && (
          <AnchoredOverlay anchor={createMenu.anchor} className="cg-view-menu"
            placement="bottom-start" role="menu" ariaLabel="Create a route or a folder"
            onDismiss={() => setCreateMenu(null)} dataKind="route-create-menu">
          <button type="button" role="menuitem" onClick={() => {
            setCreateMenu(null); setError(null); onCreateStart(); setCreating(true);
          }}>Route</button>
          <button type="button" role="menuitem" onClick={() => {
            setCreateMenu(null); setCreatingFolder(true);
          }}>Folder</button>
          </AnchoredOverlay>
        )}
        </div>
        {createdRoute && <div className="cg-w44-route-created" role="dialog" aria-label="Route privacy choice">
          <p><strong>{createdRoute.name}</strong> was created. Keep it private or share it now?</p>
          <div className="cg-form-actions">
            <button type="button" className="cg-btn cg-btn--primary" disabled={busy}
              title={busy ? "Wait for the Route update to finish." : undefined}
              onClick={() => { setBusy(true); void onShare(createdRoute).then((message) => {
                setError(message); if (!message) onCreatedDismiss();
              }).finally(() => setBusy(false)); }}>Share</button>
            <button type="button" className="cg-btn" disabled={busy}
              title={busy ? "Wait for the Route update to finish." : undefined}
              onClick={onCreatedDismiss}>Keep private</button>
          </div>
        </div>}
        {error && <span className="cg-w44-route-warning" role="status">{error}</span>}
      </div>
      <div className="cg-route-index-scroll" role="region" aria-label="Saved routes" tabIndex={0}
        onScroll={(event) => { listScroll.current = event.currentTarget.scrollTop; }}>
      <div className="cg-find-view">
        <svg className="cg-find-view-icon" width="14" height="14" viewBox="0 0 16 16" fill="none"
          aria-hidden="true">
          <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
          <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35" strokeLinecap="round" />
        </svg>
        <input type="text" value={routeQuery} placeholder="Find…" aria-label="Find a route"
          onChange={(event) => setRouteQuery(event.target.value)}
          onKeyDown={(event) => { if (event.key === "Escape") setRouteQuery(""); }} />
      </div>
      {creatingFolder && <div className="cg-view-create cg-create-form cg-fold-form">
        <input className="cg-input" value={folderName} maxLength={80} autoFocus
          aria-label="New Route folder name" onChange={(event) => setFolderName(event.target.value)} />
        <div className="cg-form-actions">
          <button type="button" className="cg-btn cg-btn--primary" disabled={busy || !folderName.trim()}
            onClick={() => { setBusy(true); void onFolderCreate(folderName.trim(), null).then((message) => {
              setError(message); if (!message) { setFolderName(""); setCreatingFolder(false); }
            }).finally(() => setBusy(false)); }}>Create</button>
          <button type="button" className="cg-btn" disabled={busy}
            onClick={() => { setFolderName(""); setCreatingFolder(false); }}>Cancel</button>
        </div>
      </div>}
      <div className="cg-view-list" aria-label="Route folder contents">
        {rows}
        {!rows.length && <p className="cg-w44-route-empty">
          {!routesLoaded ? "Loading routes."
            : query ? "No Route matches that search."
            : "No routes yet. Create one from selected Zones or records."}
        </p>}
      </div>
      </div>
    </>
  );
  return (
    <section ref={rail} className="cg-w44-route-nav" aria-label="Named routes">
      {/* ⛔ An open Route REPLACES the Routes list: Back to routes is its only way out. */}
      {route ? routeDetail() : inventory}
      {/* ⛔ RENDERED FROM THE COMPONENT ROOT, OUTSIDE `renderLevel` AND OUTSIDE EVERY MENU
          CONDITIONAL. See the note over `pendingDelete`: a dialog inside the menu subtree that
          set it would never paint. `ConfirmDialog` portals to <body> itself, so its position in
          this tree governs only its LIFETIME, and that is exactly what needed fixing. */}
      <ConfirmDialog
        open={pendingDelete !== null}
        title={pendingDelete ? `Delete ${pendingDelete.kind === "folder" ? pendingDelete.folder.name : pendingDelete.item.name}?` : ""}
        body={pendingDelete?.kind === "folder"
          ? "Its contents move to Routes."
          : "The Route and its saved stop order are removed; the customer records are untouched."}
        confirmLabel={pendingDelete?.kind === "folder" ? "Delete folder" : "Delete route"}
        tone="destructive"
        busy={busy}
        /* ⛔ `finish` IS INLINED HERE RATHER THAN CALLED, and not for style. `finish` swallows
           the promise, so there is no moment at which this dialog could learn the write had
           settled; clearing `pendingDelete` before the dispatch instead would close the dialog in
           the same batched render and `busy={busy}` would never paint on anything. The error still
           lands in the rail exactly where the native confirm's did. */
        onConfirm={() => {
          const target = pendingDelete;
          if (!target || busy) return;
          setBusy(true);
          void (target.kind === "folder" ? onFolderDelete(target.folder) : onDelete(target.item))
            .then(setError)
            .finally(() => { setBusy(false); setPendingDelete(null); });
        }}
        onCancel={() => setPendingDelete(null)}
      />
    </section>
  );
}