File size: 64,430 Bytes
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b80130d
ce4ad7b
bdac669
e88a3a3
792ee39
 
 
 
992a41f
bdac669
ce4ad7b
b80130d
39a9177
 
 
bdac669
39a9177
bdac669
c8a9b67
aa1490a
 
81a8217
39a9177
992a41f
ce4ad7b
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
792ee39
 
 
 
 
 
ce4ad7b
bdac669
 
 
ce4ad7b
39a9177
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
b80130d
ce4ad7b
 
 
 
 
dcd43e2
ce4ad7b
39a9177
 
 
 
 
 
 
 
 
 
ce4ad7b
 
39a9177
 
 
 
 
 
 
 
 
cfa8541
 
 
1ad1eea
 
cfa8541
 
1ad1eea
 
cfa8541
 
e13472e
 
 
1ad1eea
 
e13472e
 
1ad1eea
e13472e
1ad1eea
 
e13472e
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
39a9177
 
 
ce4ad7b
 
 
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
b80130d
ce4ad7b
 
1ad1eea
792ee39
ce4ad7b
bdac669
 
 
ce4ad7b
 
 
 
b80130d
bdac669
ce4ad7b
 
 
 
 
39a9177
 
ce4ad7b
1ad1eea
 
 
bdac669
 
 
9a6cb9a
 
1ad1eea
 
9a6cb9a
bdac669
 
 
dcd43e2
39a9177
 
 
 
 
 
 
 
 
1ad1eea
39a9177
aa1490a
 
 
 
 
 
 
1ad1eea
 
 
cfa8541
aa1490a
 
 
 
 
 
 
 
 
 
 
1ad1eea
aa1490a
1ad1eea
aa1490a
 
 
cfa8541
 
 
 
 
 
 
 
1ad1eea
 
 
 
cfa8541
 
 
 
 
 
 
1ad1eea
cfa8541
 
1ad1eea
cfa8541
1ad1eea
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
 
ce4ad7b
b80130d
1ad1eea
b80130d
 
 
 
e13472e
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
bdac669
 
 
 
39a9177
 
 
 
 
bdac669
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
0e600b9
 
992a41f
ce4ad7b
792ee39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e600b9
 
 
 
792ee39
 
ce4ad7b
 
 
 
 
 
e13472e
 
b80130d
e13472e
 
 
1ad1eea
b80130d
 
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
b80130d
e13472e
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
ce4ad7b
 
 
 
 
 
 
 
 
1ad1eea
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
ce4ad7b
dcd43e2
ce4ad7b
bdac669
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
bdac669
ce4ad7b
bdac669
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
ce4ad7b
 
 
 
 
 
 
 
bdac669
ce4ad7b
 
 
 
 
 
 
 
bdac669
ce4ad7b
 
 
 
 
 
 
 
 
 
dcd43e2
 
ce4ad7b
 
39a9177
 
 
 
 
 
 
 
 
bdac669
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
 
 
 
 
39a9177
 
b80130d
bdac669
b80130d
ce4ad7b
 
 
 
 
 
 
 
 
39a9177
aa1490a
 
39a9177
 
 
1ad1eea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
 
aa1490a
 
 
 
39a9177
81a8217
39a9177
aa1490a
 
 
39a9177
 
 
1ad1eea
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
39a9177
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
ce4ad7b
 
39a9177
bdac669
ce4ad7b
 
 
 
 
 
 
 
bdac669
 
ce4ad7b
bdac669
 
ce4ad7b
bdac669
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
ce4ad7b
bdac669
 
ce4ad7b
bdac669
ce4ad7b
 
bdac669
 
 
ce4ad7b
 
 
 
 
 
 
bdac669
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
bdac669
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e600b9
 
 
 
 
bdac669
b80130d
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
b80130d
 
ce4ad7b
 
 
 
 
 
39a9177
 
 
 
 
ce4ad7b
 
 
 
 
39a9177
ce4ad7b
 
 
 
bdac669
 
 
b80130d
ce4ad7b
39a9177
 
 
 
 
 
 
 
 
 
0e600b9
39a9177
 
ce4ad7b
992a41f
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
ce4ad7b
 
 
 
 
 
 
 
 
b80130d
ce4ad7b
bdac669
 
 
ce4ad7b
 
bdac669
1ad1eea
bdac669
ce4ad7b
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
ce4ad7b
 
 
bdac669
 
 
ce4ad7b
 
 
39a9177
ce4ad7b
 
 
 
39a9177
ce4ad7b
39a9177
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
 
bdac669
 
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
39a9177
 
 
 
ce4ad7b
 
 
 
bdac669
 
 
ce4ad7b
 
39a9177
 
 
ce4ad7b
39a9177
ce4ad7b
 
39a9177
ce4ad7b
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
39a9177
 
 
 
 
 
 
bdac669
 
 
 
39a9177
 
 
e88a3a3
39a9177
 
 
 
 
 
bdac669
39a9177
bdac669
 
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
 
 
39a9177
 
bdac669
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e600b9
 
 
 
 
 
 
39a9177
 
 
992a41f
 
 
 
 
 
 
1ad1eea
aa1490a
 
 
ce4ad7b
 
 
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
// ---------------------------------------------------------------------------
// sheet/SheetRail.tsx β€” the Sheet module's view rail (wave 50 Β· W50-T17, owner instruction 20).
//
// ⭐⭐ THE OWNER'S WORDS ARE "THE SHEET RAIL MUST BE EXACTLY THE DATA RAIL", AND PARITY HERE IS
// BY CLASSES AND BEHAVIOUR, NOT BY IMPORT. `customer-grid/ViewSidebar.tsx` is not a portable
// props component and its own header says why: it reads `localStorage` directly, dispatches on
// the shared `apiContract` event bus, pulls six sibling `customer-grid` modules, and mounting
// it needs a `SavedView[]`, an `onViewReorder`, an `alertCounts` map and eight more required
// callbacks. So this file reproduces the rail's CSS VOCABULARY instead β€” `cg-views`,
// `cg-view-row`, `cg-view-main`, `cg-view-more`, `cg-fold`, `cg-fold-head`, `cg-fold-toggle`,
// `cg-data-create`, `cg-create-new`, `cg-find-view`, `cg-segmented-path` β€” every one of which is
// declared at TOP LEVEL and UNSCOPED in `index.css`, so they paint identically here with no
// extra rule. Nothing below re-declares a measure, a colour or a font that those rules already
// own; `styles/wave50/sheet.css` carries only what the shared vocabulary has no class for.
//
// β›”β›” WAVE-49 R2's SECOND HALF IS THE RULE THAT SHAPED WHAT IS *NOT* HERE: "any control the Data
// rail shows that the Sheet cannot honour must be ABSENT, not present-and-inert. A dead button is
// a fake affordance." Two of the Data rail's controls are therefore deliberately missing:
//
//   Β· ROW REORDER (`is-drop-above`, the insertion rule). The Data rail persists an arrangement
//     through `save_view_order`; the workbook index has no order stratum, so a drag that promised
//     to reorder would spring back on every reload. The drag that IS honoured is FILING, which
//     the index does store, so `is-viewdrag` and `is-drop` are here and `is-drop-above` is not.
//   Β· THE VIEW-KIND PICKER inside "+ Create new…". R2 gives the Sheet EXACTLY ONE view kind, so
//     a picker would offer a choice with one item. The create menu offers Workbook and Folder,
//     which are the two things this rail can actually make.
//
// β›” WAVE-49 R7: ONE RAIL ENTRY IS A WORKBOOK WITH TABS. Tabs live inside a workbook and are NOT
// rail rows, so nothing below ever renders a tab.
//
// ⚠ THE FOLDER INTERACTION IS THE DATA LAYER'S, NOT THE VIEW LAYER'S: walking into a folder
// REPLACES the list and the breadcrumb says where you are (`Sheet / <folder>`), exactly as
// `ViewSidebar`'s `cg-data-path-level` does. That is why no `.cg-view-row` is ever rendered
// INSIDE a `.cg-fold` here β€” `index.css:5946` (`.cg-fold .cg-view-row { margin-left: 12px }`)
// indents a NESTED row, and a path-replacing level has no nested rows to indent.
// ---------------------------------------------------------------------------

import { useEffect, useMemo, useRef, useState } from "react";
import type { DragEvent as ReactDragEvent } from "react";
import "../styles/wave46/rail-select.css";
import "../styles/wave52/parity.css";
// W53-T04 (instr 15). Loaded AFTER wave52's parity patch and at a higher specificity, so the
// path row's seating is decided by weight rather than by emission order. See the file's header
// for the two measured row heights that make the extra pixel necessary.
import "../styles/wave53/sheet-rail.css";
import "../styles/wave59/templates.css";
import "../styles/wave61/rails.css";
import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
import FolderNameDialog, { FOLDER_NAME_MAX } from "../home/FolderNameDialog";
import { FolderMark, MenuLabel } from "../customer-grid/icons";
import { SHARE_SHAPE, SHEET_SHAPE } from "../customer-grid/iconShapes";
import { StarIcon } from "../ui/icons";
import { openExistingItem, useItemDeletions, useStarred } from "../starred/starredApi";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { useRailSelection } from "../ui/useRailSelection";
import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
import { NAV_PANEL_EVENT, RailHeaderIcons, useNarrowRailFold, useRailHeaderSlot } from "../shell/railHeader";
import type { NavPanelDetail } from "../shell/railHeader";
import PanelToggleIcon from "../shell/PanelToggleIcon";
import ImportDialog from "./ImportDialog";
import TemplateGallery from "./templates/TemplateGallery";
import { ROOT_FOLDER_ID } from "./types";
import type { SheetFolder, WorkbookRow } from "./types";

/** The three strata the rail owns. Sent wholesale, because a placement needs its folder. */
export interface RailStrata {
  folders: SheetFolder[];
  itemFolders: Record<string, string>;
  starred: string[];
}

export interface SheetRailProps {
  /** C3: each embedded page supplies its own storage and event namespace. */
  storagePrefix?: string;
  /**
   * W53-T09: a monotonic counter the page bumps when the RIBBON's Import button is pressed. Any
   * change opens the import dialog this rail already owns. Optional, so every existing mount and
   * every test that renders this rail without the page compiles unchanged.
   */
  importRequest?: number;
  loading: boolean;
  /** Has GET /sheets/index answered? A strata write before it has is a wholesale PUT of an
   * empty folder tree over the stored one. Optional and defaults to true for existing callers. */
  indexKnown?: boolean;
  rows: readonly WorkbookRow[];
  /**
   * W51-T10 (contract C5) β€” the workbooks OTHER people have shared with this account.
   *
   * β›” OPTIONAL, AND ABSENT IS THE ORDINARY CASE TODAY. `GET /sheets/index` grows this list in
   * W51-T25; until it does the server sends nothing, and a section with a heading and no rows
   * would tell a person that sharing exists and has given them nothing. So the whole section is
   * rendered only when the list has something in it.
   */
  sharedWithMe?: readonly WorkbookRow[];
  folders: readonly SheetFolder[];
  itemFolders: Record<string, string>;
  starred: readonly string[];
  activeId: string;
  revealFolder?: string;
  onOpen: (id: string) => void;
  onCreateWorkbook: () => void;
  onRenameWorkbook: (id: string, name: string) => void;
  onDuplicateWorkbook: (id: string) => void;
  onDeleteWorkbook: (id: string) => void;
  /** Folder and placement changes preserve the legacy index star stratum through this door. */
  onStrataChange: (next: RailStrata) => void;
  /**
   * W51-T09 (owner instruction 2, ruling R12) β€” whether the page's assistant dock is open, and
   * the one door that flips it.
   *
   * β›” THE PAGE OWNS THE STATE, NOT THIS RAIL, exactly as `CustomerGrid` owns it for the Data
   * rail. The launcher and the panel are two halves of one thing; a rail holding its own copy
   * would let the button say "close" over a dock that was never open.
   */
  chatOpen: boolean;
  onToggleChat: () => void;
}

/**
 * ⭐⭐ THE FOLD KEY IS THE DATA RAIL'S OWN, AND THAT IS THE TICKET RATHER THAN A COINCIDENCE.
 * `ViewSidebar.tsx:1463` reads and writes this same string, the name is after neither module, and
 * that file's own comment says the two rails "are one idea (a navigation bar folds)". The
 * done-when asks for "the same shut state Data uses", so ONE stored state serves both rails and a
 * person who folds the navigation in Data finds it folded here.
 */
const RAIL_FOLD_KEY = "aios-views-rail";

/** W63-T07: reopening after a cell-driven fold holds only for this browser session. */
const SHEET_WORKBOOK_RAIL_HOLD_KEY = "aios-sheet-workbook-rail-held-open";

function readWorkbookRailHold(prefix = ""): boolean {
  try { return sessionStorage.getItem(prefix + SHEET_WORKBOOK_RAIL_HOLD_KEY) === "1"; } catch { return false; }
}

function writeWorkbookRailHold(prefix = ""): void {
  try { sessionStorage.setItem(prefix + SHEET_WORKBOOK_RAIL_HOLD_KEY, "1"); } catch { /* in-memory state remains */ }
}

/** W56-T05: one last folder id, separate from the rail-fold and workbook stores. */
const LAST_FOLDER_KEY = "aios-sheet-last-folder";

function readLastFolder(prefix = ""): string | null {
  try { return localStorage.getItem(prefix + LAST_FOLDER_KEY) || null; } catch { return null; }
}

function writeLastFolder(folderId: string | null, prefix = ""): void {
  try {
    if (folderId) localStorage.setItem(prefix + LAST_FOLDER_KEY, folderId);
    else localStorage.removeItem(prefix + LAST_FOLDER_KEY);
  } catch { /* session only */ }
}

/** How many rows the rail draws while it is loading. Matches `Shell.tsx::RAIL_SKELETON_ROWS`. */
const SKELETON_ROWS = 6;

const STAR_PATH =
  "M8 2.9l1.63 3.3 3.64.53-2.63 2.57.62 3.63L8 11.24 4.74 12.93l.62-3.63L2.73 6.73l3.64-.53z";

/**
 * The rail's loading state (DESIGN.md 5: skeletons over spinners for a RAIL).
 *
 * β›” THE CLASSES ARE `shell/navExtras.css`'s AND THEY ARE USED BY NAME, NOT BY IMPORT. That sheet
 * is imported by `shell/NavExtras.tsx`, which `shell/Shell.tsx` imports statically, which
 * `App.tsx` renders unconditionally, so the rules are in the bundle whenever the app is. Adding
 * a second import here would put the same rules in a second chunk, and editing `shell/**` is
 * outside this ticket's fence anyway. The skeleton is `aria-hidden` per row with ONE `role=
 * "status"` on the container, so a screen reader hears "loading" once rather than six times.
 */
function RailSkeleton() {
  return (
    <div className="shell-rail-skeleton" role="status" aria-label="Loading workbooks">
      {Array.from({ length: SKELETON_ROWS }, (_, i) => (
        <div className="shell-rail-skeleton-row" key={i} aria-hidden="true">
          <span className="shell-rail-skeleton-mark" />
          <span className="shell-rail-skeleton-bar" />
        </div>
      ))}
    </div>
  );
}

/**
 * The mark one workbook row wears: a page ruled into cells. 16x16, painted by
 * `.sheet-view-icon` (wave49/sheet.css), which sets the fill, the stroke and the muted tone on the
 * element itself, so the paths carry no attributes of their own.
 *
 * ⭐ W51-T10 β€” THE GEOMETRY IS `SHEET_SHAPE`'s NOW, not a third hand-drawn sheet. The rail's row
 * mark, the create menu's Workbook mark and the shell's nav mark were three drawings of one idea
 * with three sets of coordinates; two of them now read the same constant and the third is the one
 * it was traced from.
 */
function SheetViewIcon() {
  return (
    <svg className="sheet-view-icon" viewBox="0 0 16 16" aria-hidden="true">
      {SHEET_SHAPE.map((s) => (
        <path key={s.d} d={s.d} />
      ))}
    </svg>
  );
}

/**
 * β›”β›” THESE TWO ARE LOCAL BECAUSE THE COMPONENTS THEY MIRROR CANNOT BE IMPORTED, AND THAT IS A
 * FENCE RATHER THAN A PREFERENCE. `ViewSidebar.tsx::ShareMark` and `Shell.tsx::SheetIcon` are both
 * private to files this lane may not edit this wave, so exporting either one is off the table.
 * What travels instead is the GEOMETRY: `SHARE_SHAPE` and `SHEET_SHAPE` in `iconShapes.ts`, the
 * vocabulary's own home, drawn here at the menu's stroke conventions. This is exactly the
 * precedent `ViewSidebar::ShareMark` set for the same shape, and it keeps the icon LANGUAGE single
 * while touching no other lane's file.
 *
 * ⚠ NOT PAINTED BY A CLASS. A menu row's mark takes its colour from `.cg-view-menu button:hover
 * .cg-mi-ic` and from `.is-danger`; an svg carrying its own `color` rule would out-rank that
 * inheritance and the row's hover state would leave one glyph behind.
 */
function ShareMark({ size = 16 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" aria-hidden="true">
      {SHARE_SHAPE.map((s) => (
        <path
          key={s.d}
          d={s.d}
          fill={s.fill ? "currentColor" : "none"}
          stroke={s.fill ? "none" : "currentColor"}
          strokeWidth={1.35}
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      ))}
    </svg>
  );
}

function SheetMark({ size = 16 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" aria-hidden="true">
      {SHEET_SHAPE.map((s) => (
        <path
          key={s.d}
          d={s.d}
          fill="none"
          stroke="currentColor"
          strokeWidth={1.35}
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      ))}
    </svg>
  );
}

function StarMark() {
  return (
    <svg className="sheet-view-star" viewBox="0 0 16 16" aria-hidden="true">
      <path d={STAR_PATH} />
    </svg>
  );
}

function FindIcon() {
  return (
    <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>
  );
}

function PathArrow({ back }: { back: boolean }) {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path
        d={back ? "M9.8 3.6 5.4 8l4.4 4.4" : "M6.2 3.6 10.6 8l-4.4 4.4"}
        stroke="currentColor"
        strokeWidth="1.35"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

type Menu =
  | { kind: "workbook"; id: string; anchor: HTMLElement }
  | { kind: "folder"; id: string; anchor: HTMLElement };

type Dragged =
  | { kind: "workbook"; id: string; ids?: readonly string[] }
  | { kind: "folder"; id: string };

// The index projects the server's role onto each row. Filing and deletion belong to owners.
const mayManageWorkbook = (row: WorkbookRow | undefined) =>
  !!row && "role" in row && row.role === "owner";

const newFolderId = () =>
  "f" + Date.now().toString(36) + Math.floor(Math.random() * 46656).toString(36);

/**
 * ⚠ A NAME IS COLLAPSED, NOT MERELY TRIMMED. `core/sheets.py` collapses runs of whitespace on
 * the way in, so a client that only trimmed would show one name and store another.
 */
const cleanName = (raw: string) => raw.trim().replace(/\s+/g, " ").slice(0, FOLDER_NAME_MAX);

export default function SheetRail({
  storagePrefix = "",
  importRequest,
  loading,
  indexKnown = true,
  rows: suppliedRows,
  sharedWithMe: suppliedSharedWithMe = [],
  folders,
  itemFolders,
  starred,
  activeId,
  revealFolder,
  onOpen: requestOpen,
  onCreateWorkbook,
  onRenameWorkbook,
  onDuplicateWorkbook,
  onDeleteWorkbook,
  onStrataChange,
  chatOpen,
  onToggleChat,
}: SheetRailProps) {
  const embedded = storagePrefix.startsWith("embed:");
  const minimizeEvent = embedded ? `${NAV_MINIMIZE_EVENT}:${storagePrefix}` : NAV_MINIMIZE_EVENT;
  const panelEvent = embedded ? `${NAV_PANEL_EVENT}:${storagePrefix}` : NAV_PANEL_EVENT;
  const { isDeleted } = useItemDeletions();
  const rows = suppliedRows.filter((row) => !isDeleted({ kind: "workbook", id: row.id }));
  const sharedWithMe = suppliedSharedWithMe.filter((row) => !isDeleted({ kind: "workbook", id: row.id }));
  const onOpen = (id: string) => {
    requestOpen(id);
    // The embedded page fetches the workbook and renders refusals without the helper's hash reads.
    if (!embedded) void openExistingItem({ kind: "workbook", id }, () => {});
  };
  const indexPendingReason = indexKnown ? undefined : "Folders are still loading.";
  // Menu and picker rules override native disabled styling, so the wait must stay visible.
  const indexPendingStyle = indexKnown ? undefined : { opacity: 0.45, cursor: "not-allowed" };
  const { load: starLoad, starred: userStarred, busy: starBusy, toggle } = useStarred();
  /**
   * W51-T09 β€” IS THE RAIL FOLDED. Read from storage on the first render only, exactly as
   * `ViewSidebar.tsx:1463` does, so the fold survives a reload and a walk between the two modules.
   *
   * β›” THE `try` IS NOT DECORATION. `localStorage` THROWS on a browser with storage blocked, and an
   * unguarded read here would take the whole rail down with it. Blocked storage must still fold
   * for the session, which is what a `false` start plus an ignored write gives.
   */
  const [railShut, setRailShut] = useState<boolean>(() => {
    try { return localStorage.getItem(storagePrefix + RAIL_FOLD_KEY) === "1"; } catch { return false; }
  });
  const narrow = useNarrowRailFold();
  const [narrowOpen, setNarrowOpen] = useState(false);
  useEffect(() => {
    if (!narrow) setNarrowOpen(false);
  }, [narrow]);
  const folded = narrow ? !narrowOpen : railShut;
  const [railEl, setRailEl] = useState<HTMLElement | null>(null);
  const sharedHeaderSlot = useRailHeaderSlot("sheet", railEl);
  const headerSlot = embedded ? null : sharedHeaderSlot;
  const [railHeldOpen, setRailHeldOpen] = useState(() => readWorkbookRailHold(storagePrefix));
  const [railAutoFolded, setRailAutoFolded] = useState(false);
  const railShutRef = useRef(railShut);
  const narrowOpenRef = useRef(narrowOpen);
  railShutRef.current = railShut;
  narrowOpenRef.current = narrowOpen;
  const panelSavedRef = useRef<{ railShut: boolean; narrowOpen: boolean } | null>(null);
  const toggleRail = () => {
    panelSavedRef.current = null;
    setRailShut((v) => {
      const next = !v;
      if (v) {
        setRailHeldOpen(true);
        writeWorkbookRailHold(storagePrefix);
      }
      try { localStorage.setItem(storagePrefix + RAIL_FOLD_KEY, next ? "1" : "0"); } catch { /* session only */ }
      return next;
    });
  };
  useEffect(() => {
    if (railHeldOpen || railAutoFolded) return;
    const onCellKey = (event: KeyboardEvent) => {
      if (event.repeat || (event.key !== "Enter" && event.key !== "F2")) return;
      const target = event.target as Element | null;
      // Glide focuses this scroller for cell-key handling. Formula inputs, ribbon controls,
      // dialogs, headers and both rails are outside this descendant selector.
      if (!target?.closest(".sheet-grid-canvas .dvn-scroller")) return;
      // An embedded cell belongs only to the rail in its own page.
      const page = target.closest(".sheet-page");
      if (embedded ? page !== railEl?.closest(".sheet-page") : page?.getAttribute("data-embedded") === "true") return;
      signal(minimizeEvent);
    };
    const onNavMinimize = () => {
      // Automatic collapse is deliberately not persisted: a fresh Sheet/session starts eligible.
      setRailShut(true);
      setRailAutoFolded(true);
    };
    document.addEventListener("keydown", onCellKey);
    window.addEventListener(minimizeEvent, onNavMinimize);
    return () => {
      document.removeEventListener("keydown", onCellKey);
      window.removeEventListener(minimizeEvent, onNavMinimize);
    };
  }, [embedded, minimizeEvent, railEl, railHeldOpen, railAutoFolded]);
  // R21 (SDLC 68): Edit and View data always fold; closing restores how the user had the rail.
  // A manual toggle clears the saved state so the user's newest choice wins.
  useEffect(() => {
    const onNavPanel = (event: Event) => {
      const { open } = (event as CustomEvent<NavPanelDetail>).detail;
      if (open) {
        if (panelSavedRef.current === null) {
          panelSavedRef.current = {
            railShut: railShutRef.current,
            narrowOpen: narrowOpenRef.current,
          };
        }
        setRailShut(true);
        setNarrowOpen(false);
      } else if (panelSavedRef.current) {
        const saved = panelSavedRef.current;
        setRailShut(saved.railShut);
        setNarrowOpen(saved.narrowOpen);
        panelSavedRef.current = null;
      }
    };
    window.addEventListener(panelEvent, onNavPanel);
    return () => window.removeEventListener(panelEvent, onNavPanel);
  }, [panelEvent]);
  /** The folder whose contents are on screen, or null for the top level. */
  const openedFolder = (): string | null => {
    const folder = revealFolder ?? itemFolders[activeId] ?? (activeId ? null : readLastFolder(storagePrefix));
    return folder === ROOT_FOLDER_ID ? null : folder;
  };
  const [at, setAt] = useState<string | null>(() => openedFolder());
  const lastReveal = useRef<{ activeId: string; revealFolder?: string } | null>(null);
  /** Restored folders start after root, so Back reaches root and Forward returns here. */
  const [history, setHistory] = useState<(string | null)[]>(
    () => at === null ? [null] : [null, at],
  );
  const [step, setStep] = useState(() => at === null ? 0 : 1);
  const [query, setQuery] = useState("");
  const [menu, setMenu] = useState<Menu | null>(null);
  const [renaming, setRenaming] = useState("");
  const [createAt, setCreateAt] = useState<HTMLElement | null>(null);
  const [namingFolder, setNamingFolder] = useState(false);
  const [folderName, setFolderName] = useState("");
  const [dragged, setDragged] = useState<Dragged | null>(null);
  const [dropOn, setDropOn] = useState<string | null>(null);
  /**
   * W51-T10 / R13 β€” "Move to folder", the picker the menu item opens.
   *
   * β›” THE MENU CLOSES AND A SECOND OVERLAY OPENS ON THE SAME ANCHOR. That is the Data rail's own
   * shape (`ViewSidebar.tsx`'s `moveFor`), and it is the shape because a picker nested INSIDE the
   * menu overlay would be an outside click as far as the menu's own dismiss handler is concerned:
   * choosing a folder would close the thing being clicked. One overlay at a time, anchored to the
   * `…` button both times, so the picker opens where the menu was.
   */
  const [moveFor, setMoveFor] = useState<{
    id: string; anchor: HTMLElement; ids?: readonly string[];
  } | null>(null);
  const [railLeftInPlace, setRailLeftInPlace] = useState<string[]>([]);
  /**
   * W51-T10 / R6 β€” the pending destructive act, or null. ONE ConfirmDialog for the workbook and
   * the folder both, because R6 is about there being one shape for the promise, not one per noun.
   */
  const [confirmDelete, setConfirmDelete] =
    useState<
      | { kind: "workbook" | "folder"; id: string; name: string }
      | { kind: "workbooks"; ids: readonly string[]; name: string }
      | null
    >(null);
  /**
   * W51-T13 (owner instruction 7, contract C4) β€” is the import dialog on screen.
   *
   * β›” THE DIALOG IS MOUNTED CONDITIONALLY, AND THAT IS THE RESET. It holds the chosen file, the
   * poll's run token, the job and its report; a component kept mounted behind an `open={false}`
   * would hand the next import the previous one's progress bar, and the previous poll would still
   * be ticking behind it. Unmounting is one of the poll's five terminal conditions.
   */
  const [importing, setImporting] = useState(false);
  // Keep the server's summary after the import dialog unmounts to open the workbook.
  const [importSummary, setImportSummary] = useState("");
  const [pickingTemplate, setPickingTemplate] = useState(false);

  /**
   * ⭐⭐ W53-T09 (owner instruction 20) β€” THE RIBBON'S IMPORT BUTTON IS THE SECOND DOOR ONTO THIS
   * SAME DIALOG, AND UNTIL NOW IT OPENED NOTHING. The owner reported "the import button doesn't do
   * anything" and the ribbon looked correctly wired, which is why it survived a code read: the
   * chain `Ribbon.tsx case "import"` -> `onOpenImport?.()` -> `SheetGrid.tsx` -> `SheetPage.tsx`
   * is intact end to end, and the LAST link was a function whose entire body was `return;`,
   * carrying the comment *"W51-T13 mounts the import dialog on this handler. Deliberately inert
   * until then."* W51-T13 never landed, so a deliberate placeholder shipped as a dead button.
   * β›” THE DIALOG IS NOT MOVED, and that is the point: one dialog, two doors. `importing` above
   * stays this rail's own state because the rail's "Import .xlsx" menu item is the other door,
   * and the counter below only ever REQUESTS an open, so the two cannot fight over who owns it.
   * ⚠ A COUNTER, NOT A BOOLEAN. A boolean prop would latch: the page would have to be told when
   * the dialog closed in order to reset it, which is exactly the two-way coupling this shape
   * avoids. Every increment is one fresh request to open.
   */
  useEffect(() => {
    if (importRequest) {
      setImportSummary("");
      setImporting(true);
    }
  }, [importRequest]);

  const byId = useMemo(() => {
    const map: Record<string, SheetFolder> = {};
    folders.forEach((f) => { map[f.id] = f; });
    return map;
  }, [folders]);

  /** A folder deleted here or belonging to another tenant silently restores the top level. */
  useEffect(() => {
    if (loading || !indexKnown || at === null || byId[at]) return;
    setAt(null);
    setHistory([null]);
    setStep(0);
    writeLastFolder(null, storagePrefix);
  }, [at, byId, loading, indexKnown]);

  // Wait for placement metadata, then reveal each address choice once. Rail browsing stays put.
  useEffect(() => {
    if (loading || !indexKnown) return;
    if (lastReveal.current?.activeId === activeId
      && lastReveal.current?.revealFolder === revealFolder) return;
    lastReveal.current = { activeId, revealFolder };
    const folder = openedFolder();
    const next = folder && byId[folder] ? folder : null;
    setAt(next);
    setHistory(next === null ? [null] : [null, next]);
    setStep(next === null ? 0 : 1);
    setQuery("");
    writeLastFolder(next, storagePrefix);
  }, [activeId, revealFolder, itemFolders, byId, loading, indexKnown]);

  const strata = (): RailStrata => ({
    folders: folders.map((f) => ({ ...f })),
    itemFolders: { ...itemFolders },
    starred: [...starred],
  });

  /** Where a workbook is filed. An absent placement and the root sentinel mean the same thing. */
  const placedIn = (id: string): string | null => {
    const fid = itemFolders[id];
    return !fid || fid === ROOT_FOLDER_ID ? null : fid;
  };

  const goTo = (next: string | null) => {
    writeLastFolder(next, storagePrefix);
    setAt(next);
    setQuery("");
    setHistory((prev) => [...prev.slice(0, step + 1), next]);
    setStep((prev) => prev + 1);
  };

  const walk = (delta: number) => {
    const target = step + delta;
    if (target < 0 || target >= history.length) return;
    writeLastFolder(history[target], storagePrefix);
    setStep(target);
    setAt(history[target]);
    setQuery("");
  };

  // ⚠ THE CRUMBS ARE WALKED FROM THE CURRENT FOLDER UPWARD AND THEN REVERSED, with a visited set
  // guarding the walk. The server refuses a cycle, so one should be unreachable; a rail that
  // hangs the browser rather than painting is not a defect worth risking on "should".
  const crumbs = useMemo(() => {
    const chain: SheetFolder[] = [];
    const seen = new Set<string>();
    let cursor = at;
    while (cursor && byId[cursor] && !seen.has(cursor)) {
      seen.add(cursor);
      chain.push(byId[cursor]);
      cursor = byId[cursor].parent ?? null;
    }
    chain.reverse();
    return [{ key: "__sheet__", label: "Sheet", target: null as string | null },
      ...chain.map((f) => ({ key: f.id, label: f.name, target: f.id as string | null }))];
  }, [at, byId]);

  const needle = query.trim().toLowerCase();
  const matches = (label: string) => !needle || label.toLowerCase().includes(needle);

  const levelFolders = folders.filter((f) => (f.parent ?? null) === at && matches(f.name));
  const levelRows = rows.filter((r) => placedIn(r.id) === at && matches(r.name));
  const levelRowIds = levelRows.map((row) => row.id);
  const {
    selected: railSelected,
    anchorId: railAnchorId,
    onRowClick: selectRailRow,
    clear: clearRailSelection,
    isSelected: isRailSelected,
  } = useRailSelection(levelRowIds);
  const workbookById = new Map(rows.map((row) => [row.id, row]));
  const blockedWorkbooks = (ids: readonly string[]) => ids.flatMap((id) => {
    const row = workbookById.get(id);
    return row && !mayManageWorkbook(row) ? [row.name] : [];
  });
  const railManageable = railSelected.filter((id) => mayManageWorkbook(workbookById.get(id)));
  const railBlocked = blockedWorkbooks(railSelected);
  const railNotice = railLeftInPlace.length > 0
    ? `Left in place: ${railLeftInPlace.join(", ")}.`
    : railBlocked.length > 0 ? `Will stay in place: ${railBlocked.join(", ")}.` : "";

  useEffect(() => {
    if (railSelected.length === 0 && railAnchorId === null && railLeftInPlace.length === 0) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key !== "Escape" || event.defaultPrevented) return;
      if (menu || createAt || moveFor || confirmDelete || renaming) return;
      const target = event.target as HTMLElement | null;
      if (target?.tagName === "INPUT" || target?.tagName === "TEXTAREA" || target?.isContentEditable) return;
      clearRailSelection();
      setRailLeftInPlace([]);
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [railSelected.length, railAnchorId, railLeftInPlace.length, menu, createAt, moveFor,
    confirmDelete, renaming, clearRailSelection]);
  /** The shared list obeys the find box like every other row, so one search covers the rail. */
  const sharedRows = sharedWithMe.filter((r) => matches(r.name));

  const isStarred = (id: string) => starLoad.phase === "ready" && userStarred.sheets.includes(id);

  const moveWorkbooks = (ids: readonly string[], target: string | null) => {
    if (!indexKnown) return;
    // The index PUT replaces all strata, so every placement must share this one snapshot.
    const next = strata();
    let moved = false;
    for (const id of ids) {
      if (!mayManageWorkbook(workbookById.get(id))) continue;
      next.itemFolders[id] = target ?? ROOT_FOLDER_ID;
      moved = true;
    }
    if (moved) onStrataChange(next);
    clearRailSelection();
    setRailLeftInPlace(blockedWorkbooks(ids));
  };

  const fileInto = (drag: Dragged, target: string | null) => {
    if (!indexKnown) return;
    if (drag.kind === "workbook") {
      moveWorkbooks(drag.ids ?? [drag.id], target);
      return;
    }
    if (drag.id === target) return;
    const next = strata();
    next.folders = next.folders.map((f) =>
      (f.id === drag.id ? { ...f, parent: target } : f));
    // β›” SENT EVEN WHEN IT MAKES A CYCLE. The wall is `core/sheets.py::validate_folder_tree`, and
    // a client-side pre-check would either duplicate it (two rules, one drifting) or hide the
    // refusal sentence the owner is supposed to read. The rail asks; the server answers by name.
    onStrataChange(next);
  };

  /**
   * β›”β›” EVERY LEG STOPS PROPAGATION, AND `onDragOver` IS THE ONE THAT MATTERS. A folder row sits
   * INSIDE the level container and both are drop targets, so React bubbles the same dragover from
   * the row to the box around it: the row sets `dropOn` to its own id and the container overwrites
   * it a microsecond later with the level's. The drop still LANDED in the right folder, because
   * `onDrop` already stopped there, so the bug was invisible to every functional check and showed
   * only as the wrong thing lighting up: drag a workbook onto "Plans" and the whole list glows
   * while "Plans" stays flat. A drop mark on the wrong target is worse than none, because it says
   * the drop is going somewhere it is not.
   */
  const dropProps = (target: string | null, key: string) => ({
    onDragOver: (event: ReactDragEvent) => {
      if (!indexKnown) {
        event.stopPropagation();
        event.dataTransfer.dropEffect = "none";
        setDropOn(null);
        return;
      }
      if (!dragged) return;
      if (dragged.kind === "folder" && dragged.id === target) return;
      event.preventDefault();
      event.stopPropagation();
      event.dataTransfer.dropEffect = "move";
      setDropOn(key);
    },
    onDragLeave: (event: ReactDragEvent) => {
      event.stopPropagation();
      setDropOn((prev) => (prev === key ? null : prev));
    },
    onDrop: (event: ReactDragEvent) => {
      event.preventDefault();
      event.stopPropagation();
      setDropOn(null);
      if (!indexKnown) { setDragged(null); return; }
      if (dragged) fileInto(dragged, target);
      setDragged(null);
    },
  });

  const closeMenu = () => { setMenu(null); setRenaming(""); };

  const renameFolder = (id: string, name: string) => {
    if (!indexKnown) return;
    const clean = cleanName(name);
    if (!clean) return;
    const next = strata();
    next.folders = next.folders.map((f) => (f.id === id ? { ...f, name: clean } : f));
    onStrataChange(next);
  };

  const deleteFolder = (id: string) => {
    if (!indexKnown) return;
    // ⚠ THE CHILDREN ARE LEFT DANGLING ON PURPOSE, and the server REPAIRS them to the top level
    // and says so. Reparenting them here would be a second implementation of the rule that
    // `validate_folder_tree` already owns, and the two would drift.
    const next = strata();
    next.folders = next.folders.filter((f) => f.id !== id);
    onStrataChange(next);
    if (at === id) goTo(null);
  };

  const toggleStar = (id: string) => {
    if (starLoad.phase !== "ready" || starBusy) return;
    toggle("sheet", id, !isStarred(id));
  };

  /**
   * W51-T10 / R13 β€” file one workbook into a folder, or back to the top level.
   *
   * ⚠ THE SAME DOOR THE DRAG USES, and deliberately so: `fileInto` already knows that an absent
   * placement and the root sentinel mean the same thing, and that the PUT carries all three strata
   * because a placement is only legal while its folder exists (D-639). A second write path here
   * would be a second chance to send half an index.
   */
  const moveWorkbook = (id: string, target: string | null) => {
    if (!indexKnown) return;
    fileInto({ kind: "workbook", id, ids: moveFor?.ids }, target);
    setMoveFor(null);
  };

  /**
   * W51-T10 / R16 β€” Share. The dispatch is the one channel the other three share controls use,
   * spelled here as the literal exactly as `ColumnMenu.tsx`, `MapView.tsx` and `ViewSidebar.tsx`
   * spell it: the emitter and the dialog live in trees that must not import each other.
   *
   * β›” IT ONLY OPENS ANYTHING BECAUSE `"workbook"` IS IN `SHARE_KINDS`. `parseShareRequest`
   * fail-closes on a kind that tuple does not carry and returns null, so before this ticket a
   * workbook dispatch was DROPPED IN SILENCE: no dialog, no error, nothing in the console.
   */
  const shareWorkbook = (id: string, name: string) => {
    window.dispatchEvent(
      new CustomEvent("aios:share-open", { detail: { kind: "workbook", id, label: name } }),
    );
  };

  const nameOfWorkbook = (id: string) => rows.find((r) => r.id === id)?.name ?? "";

  const runDelete = () => {
    const pending = confirmDelete;
    setConfirmDelete(null);
    if (!pending) return;
    if (pending.kind === "folder") deleteFolder(pending.id);
    else {
      const ids = pending.kind === "workbooks" ? pending.ids : [pending.id];
      for (const id of ids) {
        if (mayManageWorkbook(workbookById.get(id))) onDeleteWorkbook(id);
      }
      clearRailSelection();
      setRailLeftInPlace(blockedWorkbooks(ids));
    }
  };

  const createFolder = (name: string) => {
    if (!indexKnown) return;
    const clean = cleanName(name);
    if (!clean) return;
    const next = strata();
    next.folders = [...next.folders, { id: newFolderId(), name: clean, parent: at }];
    onStrataChange(next);
    setNamingFolder(false);
    setCreateAt(null);
  };

  return (
    <nav
      ref={setRailEl}
      className={"cg-views" + (folded ? " is-collapsed" : "") + (folded && headerSlot ? " is-header-folded" : "") + (narrow && narrowOpen ? " is-narrow-open" : "")}
      aria-label="Sheet workbooks"
    >
      <div className="cg-views-top">
        {/* The first child stays visible when folded. C4 gives the expanded rail one header row. */}
        {!folded && (
          <>
            <button
              type="button"
              className="cg-path-history-button"
              aria-label="Back"
              title="Back"
              disabled={step <= 0}
              onClick={() => walk(-1)}
            >
              <PathArrow back />
            </button>
            <button
              type="button"
              className="cg-path-history-button"
              aria-label="Forward"
              title="Forward"
              disabled={step >= history.length - 1}
              onClick={() => walk(1)}
            >
              <PathArrow back={false} />
            </button>
            <span className="cg-rail-name" aria-current="page">
              {crumbs[crumbs.length - 1].label}
            </span>
          </>
        )}
        <button
          type="button"
          className="cg-rail-toggle"
          aria-label={folded ? "Expand views" : "Minimize views"}
          aria-expanded={!folded}
          title={folded ? "Expand views" : "Minimize views"}
          onClick={narrow ? () => { panelSavedRef.current = null; setNarrowOpen((open) => !open); } : toggleRail}
        >
          <PanelToggleIcon open={!folded} />
        </button>
        {/* R20 (SDLC 68) moves Ask to the C9 header slot when folded.
            Keep the in-rail launcher behind a render guard. */}
        {!folded && (
          <button
            type="button"
            className={"cg-chat-toggle" + (chatOpen ? " is-on" : "")}
            aria-label="Ask about this data"
            aria-expanded={chatOpen}
            title={chatOpen ? "Close the chat about this data" : "Ask about this data"}
            onClick={onToggleChat}
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path d="M13.4 9.2c0 1.5-1.3 2.7-2.9 2.7H6.9l-3 2.1v-2.3a2.8 2.8 0 0 1-1.3-2.3V5.1c0-1.5 1.3-2.7 2.9-2.7h5c1.6 0 2.9 1.2 2.9 2.7z"
                    stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" />
              <path d="M5.9 7.2h4.2" stroke="currentColor" strokeWidth="1.3"
                    strokeLinecap="round" />
            </svg>
          </button>
        )}
      </div>

      {loading ? (
        <RailSkeleton />
      ) : (
        <>
          {/* ⚠ `cg-data-create` WRAPS `cg-create-new`, which is the nesting the Data rail uses:
              the outer class is the host's slot and the inner one is the control.
              β›” W51-T09 CORRECTS WHAT THIS COMMENT USED TO CLAIM. It said flattening the pair
              "loses the 8px the outer wrapper contributes"; measured, the 8px is `.cg-create-new`'s
              OWN `margin-top` (index.css:504) and the wrapper contributes nothing on this page at
              all. What the wrapper does contribute is a BOX TYPE, and that was the real difference:
              in the Data rail `.cg-create-new` is a flex item of `.cg-data-database-views` and
              computed `min-height: auto`, while here it was a block child and computed `0px`. The
              slot is a flex column in `styles/wave50/sheet.css` for exactly that reason. */}
          <div className="cg-data-create">
            <div className="cg-create-new">
              <button
                type="button"
                className="cg-link-btn cg-create-btn"
                aria-haspopup="menu"
                aria-expanded={Boolean(createAt)}
                onClick={(event) => {
                  setMenu(null);
                  setNamingFolder(false);
                  setCreateAt(createAt ? null : event.currentTarget);
                }}
              >
                <span className="cg-create-icon" aria-hidden="true">+</span>
                <span className="cg-create-label">Create new…</span>
              </button>
            </div>
          </div>

          <div className="cg-find-view">
            <FindIcon />
            <input
              type="text"
              value={query}
              placeholder="Find…"
              aria-label="Find a workbook"
              onChange={(event) => setQuery(event.currentTarget.value)}
            />
          </div>

          {/* THE LEVEL. `cg-fold-root` is the Data rail's own drop target for "file it here",
              and dropping on it moves the dragged row into the folder currently open.
              β›”β›” W51-T09 β€” IT IS A BLOCK NOW, AND THAT IS A MEASURED FIX RATHER THAN A TIDY-UP.
              `.sheet-rail-level` made this a flex COLUMN with a 2px gap. `min-height: auto`
              resolves to the keyword `auto` for a flex ITEM and to `0px` for anything else, so
              every `.cg-view-row` in here computed `auto` while the Data rail's computed `0px` β€”
              the owner's "not exactly the same format". The Data rail's rows sit in a plain block
              `.cg-fold-root` inside a flex `.cg-view-list`, so the row rhythm there comes from the
              LIST between fold groups and rows inside one group are flush. Matching that is what
              makes the two computed styles identical, and the gap went with the class. */}
          <div
            className={
              "cg-views-scroll cg-fold-root"
              + (indexKnown && dropOn === "__level__" ? " is-drop" : "")
            }
            {...dropProps(at, "__level__")}
          >
            {levelFolders.map((folder) => (
              <div
                key={folder.id}
                className={
                  "cg-fold"
                  + (indexKnown && dragged?.kind === "folder" && dragged.id === folder.id ? " is-folddrag" : "")
                  + (indexKnown && dropOn === folder.id ? " is-drop" : "")
                }
                draggable={indexKnown}
                title={indexPendingReason}
                onDragStart={(event) => {
                  if (!indexKnown) { event.preventDefault(); return; }
                  event.dataTransfer.effectAllowed = "move";
                  event.dataTransfer.setData("text/plain", folder.id);
                  setDragged({ kind: "folder", id: folder.id });
                }}
                onDragEnd={() => { setDragged(null); setDropOn(null); }}
                {...dropProps(folder.id, folder.id)}
              >
                <div className="cg-fold-head">
                  <button
                    type="button"
                    className="cg-fold-toggle"
                    aria-label={`Open folder ${folder.name}`}
                    onClick={() => goTo(folder.id)}
                  >
                    <FolderMark size={16} />
                    <span className="cg-fold-name">{folder.name}</span>
                  </button>
                  <button
                    type="button"
                    className="cg-view-more"
                    aria-haspopup="menu"
                    aria-label={`Actions for folder ${folder.name}`}
                    onClick={(event) => {
                      setCreateAt(null);
                      setRenaming("");
                      setMenu({ kind: "folder", id: folder.id, anchor: event.currentTarget });
                    }}
                  >
                    …
                  </button>
                </div>
              </div>
            ))}

            {levelRows.map((row) => (
              <div
                key={row.id}
                className={
                  "cg-view-row"
                  + (row.id === activeId ? " is-active" : "")
                  + (isRailSelected(row.id) ? " is-railsel" : "")
                  + (indexKnown && dragged?.kind === "workbook" && dragged.id === row.id ? " is-viewdrag" : "")
                  + (indexKnown && dragged?.kind === "workbook" && (dragged.ids?.length ?? 0) > 1
                    && dragged.ids?.includes(row.id) ? " is-rail-multidrag" : "")
                }
                draggable={indexKnown}
                title={indexPendingReason}
                onDragStart={(event) => {
                  if (!indexKnown) { event.preventDefault(); return; }
                  event.dataTransfer.effectAllowed = "move";
                  event.dataTransfer.setData("text/plain", row.id);
                  const ids = isRailSelected(row.id) && railSelected.length > 1
                    ? railSelected : [row.id];
                  setDragged({ kind: "workbook", id: row.id, ids });
                }}
                onDragEnd={() => { setDragged(null); setDropOn(null); }}
              >
                <button
                  type="button"
                  className="cg-view-main"
                  aria-current={row.id === activeId ? "true" : undefined}
                  aria-pressed={isRailSelected(row.id)}
                  onClick={(event) => {
                    selectRailRow(row.id, event);
                    setRailLeftInPlace([]);
                    if (event.shiftKey || event.ctrlKey || event.metaKey) return;
                    onOpen(row.id);
                  }}
                >
                  <SheetViewIcon />
                  <span className="cg-view-text">
                    <span className="cg-view-name">{row.name}</span>
                  </span>
                  {isStarred(row.id) ? <StarMark /> : null}
                </button>
                <button
                  type="button"
                  className="cg-view-more"
                  aria-haspopup="menu"
                  aria-label={`Actions for ${row.name}`}
                  onClick={(event) => {
                    setCreateAt(null);
                    setRenaming("");
                    setMenu({ kind: "workbook", id: row.id, anchor: event.currentTarget });
                  }}
                >
                  …
                </button>
              </div>
            ))}

            {levelFolders.length === 0 && levelRows.length === 0 ? (
              <p className="cg-fold-empty">
                {needle ? "No workbook here matches what you typed." : "Nothing filed here yet."}
              </p>
            ) : null}

            {/* ⭐⭐ W51-T10 / CONTRACT C5 β€” "SHARED TO ME", AND IT IS ABSENT UNTIL SOMEBODY SHARES.
                The list arrives on `GET /sheets/index` once W51-T25 serves it; today it is empty,
                and an empty heading would announce a feature that has given this account nothing.
                So the guard is on the ROWS, not on the flag.
                β›” NO `…` MENU ON THESE ROWS. Rename, Duplicate, Star, Move and Delete are all acts
                on a workbook you own; a shared one is somebody else's, and the strata that would
                record a star or a placement are the OWNER's index, not this reader's. Wave-49 R2
                again: a control that cannot be honoured is absent.
                ⚠ TOP LEVEL ONLY. These workbooks are not filed into this account's folders, so
                repeating them inside every folder would say they were. */}
            {at === null && sharedRows.length > 0 ? (
              <div className="sheet-shared">
                <p className="sheet-shared-head">Shared to me</p>
                {sharedRows.map((row) => (
                  <div
                    key={row.id}
                    className={"cg-view-row" + (row.id === activeId ? " is-active" : "")}
                  >
                    <button
                      type="button"
                      className="cg-view-main"
                      aria-current={row.id === activeId ? "true" : undefined}
                      onClick={() => onOpen(row.id)}
                    >
                      <SheetViewIcon />
                      <span className="cg-view-text">
                        <span className="cg-view-name">{row.name}</span>
                      </span>
                    </button>
                  </div>
                ))}
              </div>
            ) : null}
          </div>
        </>
      )}

      {!railShut && railSelected.length > 0 ? (
        <div className="cg-railsel" role="group" aria-label="Selected workbooks">
          <span className="cg-railsel-count">
            {railSelected.length === 1 ? "1 workbook selected" : `${railSelected.length} workbooks selected`}
          </span>
          <button
            type="button"
            className="cg-railsel-move"
            disabled={!indexKnown || railManageable.length === 0}
            title={indexPendingReason}
            style={indexPendingStyle}
            onClick={(event) => {
              const anchor = event.currentTarget;
              closeMenu();
              setCreateAt(null);
              setMoveFor({ id: railSelected[0], ids: [...railSelected], anchor });
            }}
          >
            Move to folder
          </button>
          <button
            type="button"
            className="is-danger"
            disabled={railManageable.length === 0}
            onClick={() => setConfirmDelete({
              kind: "workbooks", ids: [...railSelected],
              name: `${railManageable.length} ${railManageable.length === 1 ? "workbook" : "workbooks"}`,
            })}
          >
            Delete
          </button>
          {railNotice ? (
            <span className="cg-railsel-left" role="status" title={railNotice}>{railNotice}</span>
          ) : null}
        </div>
      ) : null}
      {!railShut && railSelected.length === 0 && railNotice ? (
        <p className="cg-railsel-left" role="status" title={railNotice}>{railNotice}</p>
      ) : null}
      {!folded && importSummary ? (
        <p className="cg-railsel-left" role="status" style={{ whiteSpace: "normal" }}>
          {importSummary}
        </p>
      ) : null}

      {createAt && namingFolder ? (
        <FolderNameDialog
          anchor={createAt}
          title="New folder"
          siblingNames={folders.filter((folder) => (folder.parent ?? null) === at).map((folder) => folder.name)}
          disabled={!indexKnown}
          disabledReason={indexPendingReason}
          onSubmit={createFolder}
          onDismiss={() => { setCreateAt(null); setNamingFolder(false); }}
        />
      ) : createAt ? (
        <AnchoredOverlay
          anchor={createAt}
          className="cg-view-menu"
          role="menu"
          ariaLabel="Create new"
          placement="right-start"
          onDismiss={() => { setCreateAt(null); setNamingFolder(false); }}
        >
              {/* β›” A WORKBOOK IS MADE AND OPENED IN ONE ACT, with no name step. The page shows
                  the new workbook the moment the server answers, which is the done-when clause,
                  and renaming it is one item down in its own `…` menu. */}
              {/* ⭐ W51-T10 β€” EACH ROW WEARS A MARK, THROUGH `MenuLabel`, so the icon slot and the
                  label sit in the `cg-mi-ic` / `cg-mi-text` anatomy `index.css` already paints for
                  the Data rail's menus. A Workbook wears the Sheet module's own glyph and a Folder
                  wears `FolderMark`: the two things this rail can make, each named by the mark it
                  will wear once it exists. */}
              <button
                type="button"
                role="menuitem"
                onClick={() => { setCreateAt(null); onCreateWorkbook(); }}
              >
                <MenuLabel icon={<SheetMark size={16} />} text="Workbook" />
              </button>
              <button
                type="button"
                role="menuitem"
                disabled={!indexKnown}
                title={indexPendingReason}
                style={indexPendingStyle}
                onClick={() => { setNamingFolder(true); }}
              >
                <MenuLabel icon={<FolderMark size={16} />} text="Folder" />
              </button>
              {/* ⭐⭐ W51-T13 (owner instruction 7, ruling R1) β€” THE THIRD THING THIS RAIL CAN
                  MAKE: a workbook that already exists somewhere else. It sits with Workbook and
                  Folder because those two and this one answer the same question ("where does a new
                  workbook come from"), and it wears `upload` from `MENU_ICONS`, which is the
                  vocabulary's own word for bytes arriving from outside. Nothing new was drawn. */}
              <button
                type="button"
                role="menuitem"
                onClick={() => { setCreateAt(null); setImportSummary(""); setImporting(true); }}
              >
                <MenuLabel icon="upload" text="Import .xlsx" />
              </button>
              <button
                type="button"
                role="menuitem"
                onClick={() => { setCreateAt(null); setPickingTemplate(true); }}
              >
                <MenuLabel icon={<SheetMark size={16} />} text="From a template" />
              </button>
        </AnchoredOverlay>
      ) : null}

      {menu ? (
        <AnchoredOverlay
          anchor={menu.anchor}
          className="cg-view-menu"
          role={renaming ? "dialog" : "menu"}
          ariaLabel={menu.kind === "folder" ? "Folder actions" : "Workbook actions"}
          placement="right-start"
          onDismiss={closeMenu}
        >
          {renaming === menu.id ? (
            <form
              className="cg-data-folder-rename"
              onSubmit={(event) => {
                event.preventDefault();
                const clean = cleanName(folderName);
                if (!clean && menu.kind === "folder") return;
                if (menu.kind === "folder") renameFolder(menu.id, clean);
                else onRenameWorkbook(menu.id, clean);
                closeMenu();
              }}
            >
              <input
                className="cg-input"
                autoFocus
                value={folderName}
                maxLength={FOLDER_NAME_MAX}
                aria-label={menu.kind === "folder" ? "Folder name" : "Workbook name"}
                disabled={menu.kind === "folder" && !indexKnown}
                title={menu.kind === "folder" ? indexPendingReason : undefined}
                style={menu.kind === "folder" ? indexPendingStyle : undefined}
                onChange={(event) => setFolderName(event.currentTarget.value)}
              />
              <button type="submit" className="cg-btn cg-btn--primary"
                disabled={menu.kind === "folder" && (!indexKnown || !folderName.trim())}
                title={menu.kind === "folder" ? indexPendingReason : undefined}>
                Save
              </button>
            </form>
          ) : (
            <>
              {/* ⭐⭐ W51-T10 / R13 β€” THE WORKBOOK MENU IS THE VIEW MENU'S, WITH SHARE. Rename,
                  Duplicate, Star or Unstar, Move to folder, Share, Delete, IN THAT ORDER, each
                  through `MenuLabel` with the view menu's own icon component. The order is the
                  ruling's; before this ticket Duplicate came first and only four of the six
                  existed.
                  β›” A FOLDER KEEPS THE REDUCED SET (Rename and Delete). Wave-49 R2: a control the
                  rail cannot honour is ABSENT, not present and inert. There is no duplicate-folder
                  door, no folder star stratum and no folder share kind, and a folder already moves
                  by drag, so offering four dead rows would be four fake affordances. */}
              <button
                type="button"
                role="menuitem"
                disabled={menu.kind === "folder" && !indexKnown}
                title={menu.kind === "folder" ? indexPendingReason : undefined}
                style={menu.kind === "folder" ? indexPendingStyle : undefined}
                onClick={() => {
                  const current = menu.kind === "folder"
                    ? byId[menu.id]?.name ?? ""
                    : nameOfWorkbook(menu.id);
                  setFolderName(current);
                  setRenaming(menu.id);
                }}
              >
                <MenuLabel icon="rename" text="Rename" />
              </button>
              {/* ⭐ DUPLICATE IS COMPOSED FROM DOORS THAT ALREADY EXIST (read, create, write) and
                  needs no route of its own. It is here rather than absent because the Sheet CAN
                  honour it, which is the test R2 sets. */}
              {menu.kind === "workbook" ? (
                <button
                  type="button"
                  role="menuitem"
                  onClick={() => { const id = menu.id; closeMenu(); onDuplicateWorkbook(id); }}
                >
                  <MenuLabel icon="duplicate" text="Duplicate" />
                </button>
              ) : null}
              {menu.kind === "workbook" ? (
                <button
                  type="button"
                  role="menuitem"
                  onClick={() => { const id = menu.id; closeMenu(); toggleStar(id); }}
                >
                  <MenuLabel
                    icon={<StarIcon size={16} filled={isStarred(menu.id)} />}
                    text={isStarred(menu.id) ? "Unstar" : "Star"}
                  />
                </button>
              ) : null}
              {menu.kind === "workbook" ? (
                <button
                  type="button"
                  role="menuitem"
                  disabled={!indexKnown}
                  title={indexPendingReason}
                  style={indexPendingStyle}
                  onClick={() => {
                    const target = { id: menu.id, anchor: menu.anchor };
                    closeMenu();
                    setMoveFor(target);
                  }}
                >
                  <MenuLabel icon={<FolderMark size={16} />} text="Move to folder" />
                </button>
              ) : null}
              {menu.kind === "workbook" ? (
                <button
                  type="button"
                  role="menuitem"
                  onClick={() => {
                    const id = menu.id;
                    const name = nameOfWorkbook(id);
                    closeMenu();
                    shareWorkbook(id, name);
                  }}
                >
                  <MenuLabel icon={<ShareMark size={16} />} text="Share" />
                </button>
              ) : null}
              {/* β›”β›” R6 β€” THE DELETE ASKS FIRST, AND UNTIL THIS TICKET IT DID NOT. One click on
                  this row removed a workbook and everything in it with no confirmation anywhere in
                  `src/sheet/`: no dialog, no armed second click, not even a native confirm. The
                  row now only ARMS the one `ConfirmDialog` the whole app shares. */}
              <button
                type="button"
                role="menuitem"
                className="is-danger"
                disabled={menu.kind === "folder" && !indexKnown}
                title={menu.kind === "folder" ? indexPendingReason : undefined}
                style={menu.kind === "folder" ? indexPendingStyle : undefined}
                onClick={() => {
                  const target = menu;
                  const name = target.kind === "folder"
                    ? byId[target.id]?.name ?? ""
                    : nameOfWorkbook(target.id);
                  closeMenu();
                  setConfirmDelete({ kind: target.kind, id: target.id, name });
                }}
              >
                <MenuLabel icon="trash" text="Delete" />
              </button>
            </>
          )}
        </AnchoredOverlay>
      ) : null}

      {/* ⭐ W51-T10 / R13 β€” THE FOLDER PICKER, ANCHORED WHERE THE MENU WAS. Same anatomy as the
          Data rail's own move picker (`cg-pop`, `cg-pop-title`, `cg-pop-list`, `cg-pick-row`), so
          the two rails ask the same question the same way. Every folder in the workbook index is
          offered, flat: this rail navigates folders by walking INTO them rather than by unfolding
          a tree, so a path is the honest label and an indent would draw a shape the rail does not
          otherwise have. The folder a workbook is already in is marked, and Top level is a row
          rather than a "remove from folder" verb, because moving to the top is a move. */}
      {moveFor ? (
        <AnchoredOverlay
          anchor={moveFor.anchor}
          className="cg-pop"
          role="dialog"
          ariaLabel={moveFor.ids ? "Move selected workbooks to a folder" : `Move ${nameOfWorkbook(moveFor.id)} to a folder`}
          placement="right-start"
          onDismiss={() => setMoveFor(null)}
        >
          <div className="cg-pop-title">Move to folder</div>
          <div className="cg-pop-list">
            <button
              type="button"
              className={"cg-pick-row" + (!moveFor.ids && placedIn(moveFor.id) === null ? " is-on" : "")}
              disabled={!indexKnown}
              title={indexPendingReason}
              style={indexPendingStyle}
              onClick={() => moveWorkbook(moveFor.id, null)}
            >
              <FolderMark size={16} />
              My workbooks
            </button>
            {folders.map((folder) => (
              <button
                key={folder.id}
                type="button"
                className={
                  "cg-pick-row" + (!moveFor.ids && placedIn(moveFor.id) === folder.id ? " is-on" : "")
                }
                disabled={!indexKnown}
                title={indexPendingReason}
                style={indexPendingStyle}
                onClick={() => moveWorkbook(moveFor.id, folder.id)}
              >
                <FolderMark size={16} />
                {folder.name}
              </button>
            ))}
            {folders.length === 0 ? (
              <div className="cg-pop-note">
                There are no folders yet. Create one from Create new.
              </div>
            ) : null}
          </div>
        </AnchoredOverlay>
      ) : null}

      {/* β›”β›” R6 / CONTRACT C8 β€” THE ONE CONFIRM DIALOG, NOT A SECOND ONE SHAPED LIKE IT. It brings
          the centered panel, the quiet Cancel first, initial focus on Cancel, the focus trap,
          Escape, the backdrop and the return of focus to the opener. Re-implementing any of that
          here would be the second shape DESIGN.md Β§4 refuses.
          ⚠ THE TITLE IS A QUESTION on purpose, and it is the done-when's own wording: a title that
          names the workbook is what stops a person confirming the wrong one from muscle memory. */}
      <ConfirmDialog
        open={Boolean(confirmDelete)}
        title={`Delete ${confirmDelete?.name ?? ""}?`}
        body={
          confirmDelete?.kind === "folder"
            ? indexPendingReason ?? "The workbooks inside it are not deleted. They move back to the top level."
            : confirmDelete?.kind === "workbooks"
              ? "This deletes the selected workbooks and every sheet in them. It cannot be undone."
                + (blockedWorkbooks(confirmDelete.ids).length > 0
                  ? ` Left in place: ${blockedWorkbooks(confirmDelete.ids).join(", ")}.` : "")
              : "This deletes the workbook and every sheet in it. It cannot be undone."
        }
        confirmLabel="Delete"
        busy={confirmDelete?.kind === "folder" && !indexKnown}
        tone="destructive"
        onConfirm={runDelete}
        onCancel={() => setConfirmDelete(null)}
      />

      {/* ⭐ W51-T13 / CONTRACT C4 β€” THE IMPORT DIALOG, MOUNTED WHERE ITS DOOR IS. The create menu
          is this rail's, so the dialog it opens is this rail's too, and mounting it here needs no
          edit to `SheetPage.tsx` at all.
          β›” `onOpened` IS THE RAIL'S OWN `onOpen`, which is the page's `openWorkbook`. An import
          that finished and left the person looking at the dialog would have done the work and
          hidden the result. */}
      {importing ? (
        <ImportDialog
          open
          onCancel={() => setImporting(false)}
          onSummary={(summary) => {
            setImportSummary(summary);
            if (summary) {
              setRailShut(false);
              if (narrow) setNarrowOpen(true);
            }
          }}
          onOpened={(workbookId) => { setImporting(false); onOpen(workbookId); }}
        />
      ) : null}
      {pickingTemplate ? (
        <TemplateGallery
          open
          onCancel={() => setPickingTemplate(false)}
          onOpened={(workbookId) => { setPickingTemplate(false); onOpen(workbookId); }}
        />
      ) : null}
      {folded && !embedded && <RailHeaderIcons owner="sheet" anchor={railEl}
        onExpand={narrow ? () => { panelSavedRef.current = null; setNarrowOpen(true); } : toggleRail}
        chatOpen={chatOpen} onToggleChat={onToggleChat}
      />}
    </nav>
  );
}