File size: 125,566 Bytes
1d4419b
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
82cdb59
c1fc133
ce9586e
f530297
367a695
82cdb59
c1fc133
82cdb59
ce9586e
 
82cdb59
2e7e617
7b892a5
c1fc133
82cdb59
 
 
 
 
2eae9f0
ce9586e
 
82cdb59
1d4419b
ce9586e
2eae9f0
c1fc133
 
2e7e617
 
c1fc133
2eae9f0
2e7e617
 
 
7b892a5
c1fc133
9fdbff5
7b892a5
9fdbff5
82cdb59
 
367a695
2eae9f0
82cdb59
 
c1fc133
 
 
 
82cdb59
f530297
c1fc133
 
 
f530297
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
1d4419b
 
 
c1fc133
 
367a695
 
1d4419b
 
 
 
 
 
 
2e7e617
367a695
 
 
82cdb59
1d4419b
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
 
 
 
 
 
 
c1fc133
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
1d4419b
 
 
 
 
367a695
 
 
 
c1fc133
 
 
 
 
 
2e7e617
367a695
 
 
 
82cdb59
 
 
 
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
1d4419b
 
 
 
2e7e617
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
c1fc133
 
 
2e7e617
c1fc133
 
82cdb59
 
2e7e617
1d4419b
 
 
 
 
2e7e617
82cdb59
c1fc133
 
82cdb59
367a695
 
 
 
 
 
 
1d4419b
 
 
 
 
 
 
 
2e7e617
 
 
 
 
1d4419b
2e7e617
 
1d4419b
 
 
 
c1fc133
1d4419b
 
367a695
 
2eae9f0
 
 
 
 
 
 
1d4419b
2eae9f0
367a695
1d4419b
 
 
 
c1fc133
 
1d4419b
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eae9f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
82cdb59
ce9586e
 
 
 
82cdb59
 
f530297
 
 
 
 
 
 
 
9fdbff5
 
2eae9f0
 
 
 
 
 
 
 
f530297
 
 
2eae9f0
f530297
82cdb59
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
82cdb59
 
 
 
 
c1fc133
 
 
 
82cdb59
2eae9f0
82cdb59
 
 
 
 
 
 
 
 
 
f530297
2eae9f0
 
 
ce9586e
2eae9f0
ce9586e
2eae9f0
c1fc133
2eae9f0
82cdb59
 
 
 
 
 
ce9586e
 
82cdb59
 
 
 
 
 
 
 
 
 
ce9586e
 
 
 
 
 
 
 
82cdb59
f530297
 
 
1d4419b
 
 
 
c1fc133
1d4419b
 
 
 
 
 
367a695
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
82cdb59
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
ce9586e
 
c1fc133
 
 
 
 
 
 
 
 
 
 
1d4419b
 
 
 
 
 
 
 
 
 
 
 
ce9586e
 
f530297
 
 
82cdb59
 
 
 
 
ce9586e
 
 
 
 
 
 
f530297
 
 
82cdb59
 
 
 
 
f530297
 
2eae9f0
 
 
971c29d
2eae9f0
 
 
 
 
 
 
 
f530297
82cdb59
971c29d
82cdb59
 
971c29d
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
ce9586e
82cdb59
 
ce9586e
82cdb59
 
 
 
 
 
 
 
 
 
 
f530297
ce9586e
f530297
 
ce9586e
82cdb59
 
ce9586e
82cdb59
 
c1fc133
 
 
ce9586e
c1fc133
ce9586e
2eae9f0
c1fc133
 
 
 
 
 
2eae9f0
 
 
 
ce9586e
 
2eae9f0
 
 
 
 
c1fc133
2eae9f0
 
c1fc133
 
 
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
82cdb59
ce9586e
82cdb59
 
ce9586e
 
 
 
82cdb59
 
ce9586e
82cdb59
 
 
 
 
f530297
82cdb59
 
 
 
 
f530297
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
82cdb59
ce9586e
c1fc133
 
ce9586e
 
c1fc133
 
 
 
 
 
 
 
 
82cdb59
ce9586e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
ce9586e
 
 
82cdb59
1d4419b
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
c1fc133
971c29d
 
 
2eae9f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
2eae9f0
 
82cdb59
 
 
 
 
c1fc133
82cdb59
 
 
 
 
 
 
 
 
c1fc133
 
82cdb59
c1fc133
 
82cdb59
 
 
 
 
 
f530297
82cdb59
 
 
 
f530297
2eae9f0
 
 
f530297
1d4419b
 
 
 
f530297
8133df9
82cdb59
 
 
 
1d4419b
 
 
 
82cdb59
 
 
 
2eae9f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
c1fc133
2eae9f0
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
8133df9
367a695
c1fc133
 
2eae9f0
c1fc133
 
 
 
 
 
 
 
 
 
2eae9f0
 
 
 
 
c1fc133
2eae9f0
 
 
c1fc133
 
 
 
 
 
2eae9f0
c1fc133
 
 
 
 
 
 
2eae9f0
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
c1fc133
 
2eae9f0
f530297
 
 
 
 
 
 
ce9586e
82cdb59
 
971c29d
 
2eae9f0
c1fc133
 
 
 
 
367a695
 
971c29d
2eae9f0
 
367a695
ce9586e
971c29d
 
 
 
 
 
 
 
 
 
 
 
c1fc133
367a695
 
2eae9f0
c1fc133
367a695
c1fc133
 
 
 
 
 
ce9586e
 
 
 
2eae9f0
 
c1fc133
 
367a695
 
 
 
9fdbff5
 
 
367a695
 
 
 
 
 
 
f530297
1d4419b
 
 
 
 
 
f530297
7b892a5
 
 
 
 
 
 
 
 
2eae9f0
7b892a5
 
 
 
82cdb59
 
 
367a695
 
 
 
 
 
 
 
f530297
2eae9f0
 
 
 
971c29d
2eae9f0
 
971c29d
2eae9f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
 
 
82cdb59
1d4419b
 
82cdb59
1d4419b
 
 
 
82cdb59
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
82cdb59
 
 
c1fc133
1d4419b
82cdb59
1d4419b
82cdb59
 
367a695
 
82cdb59
1d4419b
c1fc133
 
ce9586e
 
1d4419b
 
82cdb59
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
1d4419b
c1fc133
82cdb59
 
 
 
 
367a695
82cdb59
 
 
 
367a695
82cdb59
 
 
 
 
 
ce9586e
82cdb59
 
 
971c29d
 
 
 
82cdb59
 
 
ce9586e
2eae9f0
ce9586e
367a695
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
82cdb59
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
ce9586e
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
ce9586e
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
 
 
 
 
816fa8a
ce9586e
 
 
 
 
 
 
 
82cdb59
 
 
ce9586e
 
2eae9f0
 
 
 
82cdb59
2eae9f0
82cdb59
 
 
 
 
 
 
 
7b892a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
ce9586e
c1fc133
 
 
 
 
 
 
ce9586e
c1fc133
 
 
 
2eae9f0
c1fc133
 
 
2eae9f0
c1fc133
 
 
ce9586e
c1fc133
ce9586e
c1fc133
 
 
 
 
 
82cdb59
c1fc133
 
 
 
 
 
82cdb59
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
82cdb59
 
c1fc133
 
 
 
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
82cdb59
971c29d
 
 
82cdb59
 
1d4419b
f530297
82cdb59
 
f530297
c1fc133
82cdb59
f530297
 
c1fc133
 
 
f530297
 
 
c1fc133
82cdb59
f530297
 
 
 
 
 
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
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
// sheet/BindingEditor.tsx β€” what a bound cell points at (wave 49, W49-T06, R4/R8/R14;
// wave 51, W51-T12, R9/R10/R11).
//
// ⭐⭐ R4 SAYS "THE FILTER USES THE EXACT SAME UI AS A VIEW'S FILTER", SO THIS MOUNTS
// `filter-kit/FilterBuilderPanel` ITSELF. That component turned out to need NO change to run here:
// its only required props are `fields`, `filters` and `onChange`, and its own docstrings already
// anticipate "a panel over a module whose rows it has never loaded" - which is exactly a Sheet
// cell. The ticket allowed adding an optional prop if one were needed; none was.
//
// β›” THE FILTER TREE SAVED HERE IS BYTE-COMPATIBLE WITH A VIEW'S. `FilterBuilderPanel` emits a
// `FilterTree` (`{conj, nodes}`) and that value is stored verbatim on the binding. Inventing a
// second shape here is the failure C2 names: the server compiles a view's filter and a cell's
// filter through the same `compile_filter_tree`, so two shapes would mean two dialects and one of
// them would eventually stop being tested.
//
// β›”β›” W51-T12 - THE ROOT NODE IS `.sheet-binding-panel` AND NOT `.sheet-binding`, AND THAT ONE
// CLASS IS THE WHOLE TICKET. `styles/wave49/sheet.css` declares `.sheet-binding` as
// `position: fixed; z-index: var(--cg-z-drawer)` - an OVERLAY, floating over the canvas it
// describes. W50-QA-1 is what that costs: an absolutely positioned panel over the map made every
// pin beneath it unclickable, and no z-index repairs document-order stacking. The design contract's
// clause is that the right-side panel is a real COLUMN and the content beside it SHRINKS.
// `.sheet-page` is already a flex row (`align-items: stretch`) and this component already renders
// as one of its direct children, so a root of `flex: 0 0 380px` narrows `.sheet-body` - and that is
// observable as a MEASUREMENT (the grid's own width with the panel open versus closed), which is
// the one thing a screenshot cannot tell apart from an overlay.
//
// ⚠ THE NEW CLASS IS DELIBERATE, NOT COSMETIC. `wave49/sheet.css` loads from inside SheetPage's
// LAZY chunk and therefore BEATS `styles/wave51/sheet-chrome.css` (imported eagerly by index.css)
// at equal specificity, so an override of `.sheet-binding`'s `position` written in this lane's
// sheet would lose the cascade and change nothing on screen
// ([[a-lazy-chunk-stylesheet-beats-an-eager-one]]). A name nothing else declares has no fight to
// lose. The INNER classes (`.sheet-field`, `.sheet-scope`, `.sheet-radio`, `.sheet-binding-title`,
// `.sheet-binding-actions`) are all top-level selectors rather than descendants of `.sheet-binding`,
// so every one of them keeps its shipped paint.
//
// ⚠ DESIGN CONTRACT: sentence case, quiet buttons, token-only colour and type, motion 150 ms
// ease-out on opacity and transform, no emoji, and no em dash or en dash in any string on screen.

import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { API_V1, CREDENTIALS } from "../apiContract";
import { fetchWorkspace, peekWorkspace } from "../customer-grid/apiBridge";
import type { SurfaceScope } from "../customer-grid/apiBridge";
import { dayText } from "../customer-grid/display";
import { FieldSelectButton } from "../customer-grid/FieldSelect";
import { FieldTypeIcon, MenuIcon } from "../customer-grid/icons";
import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
import type { Field, FilterNode, FilterTree, GridWorkspace, Measure, SavedView } from "../customer-grid/types";
import { choiceVocabulary, isFilterGroup, MULTI_VALUE_OPS } from "../customer-grid/types";
import type { WindowSpec } from "../customer-grid/windows";
import { normalizeWindow, WINDOW_KINDS, ENDING_KINDS, ENDING_LABELS, ENDING_STEPS, TO_DATE_KINDS,
  endingBounds, endingStepDefault, MAX_N, windowLabel } from "../customer-grid/windows";
import type { EndingKind, EndingStep } from "../customer-grid/windows";
// ⭐⭐ W53-T15 (ruling R8) β€” THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
// `FilterBuilderPanel` the Data module also uses is untouched; `SheetFilterPopup` wraps it in the
// base kit's centred dialog so its condition rows have room, and only the Sheet mounts that
// wrapper. This file therefore stops importing the panel itself.
import { countConditions, isNumericType } from "../filter-kit/ops";
import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup";
import { FilterFieldStatusContext } from "../filter-kit/FilterBuilderPanel";
import type { FilterValuesState, RelatedFilterField, UnavailableRelatedFilterDatabase } from "../filter-kit/FilterBuilderPanel";
import { WindowPicker } from "../filter-kit/WindowPicker";
import { useEscapeClose } from "../ui/useEscapeClose";
import { fetchDistinctValues, previewCell, readWorkbook } from "./sheetApi";
import type { Workbook } from "./types";
import DrillModal from "./DrillModal";
import { formatRef, parseRef } from "./a1";
import { bindingAggregate, bindingDisplay, bindingFilterClauses, bindingOnDrag, bindingPeriod, bindingRelated,
  PERIOD_UNITS, BINDING_ENDING_STEP, BINDING_PERIOD_STEP,
  VIEW_BINDING_TYPES, VIEW_BINDING_LIMIT_DEFAULT, VIEW_BINDING_LIMIT_MAX } from "./types";
import type { BindingAggregate, BindingDragStep, BindingOnDrag, BindingPeriod, PeriodUnit,
  ViewBinding, DragAcross as SharedDragAcross } from "./types";
// D-687: the drag arithmetic has ONE owner, and it is the file the drag path itself calls.
import { shiftPeriodStart } from "./sheetState";
import { useCellRefHighlight } from "./refHighlight";
import { bindingStepMode, bindingStepValues, resolveEndingCell, seedBindingStep,
  bindingRefSlots, filterValueLeaves, keepCellFilterValues, resolveFilterCell, showCellFilterValues,
  updateFilterValueLeaf, FILTER_REF_KEYS } from "./bindingRefs";
import type { ReadBindingCell } from "./bindingRefs";
import "../styles/wave57/binding-actions.css";
import "../styles/wave58/sheet.css";
import "../styles/wave59/binding.css";
import "../styles/wave66/binding.css";

const BINDING_SECTIONS = [
  { key: "data", label: "Data", icon: <MenuIcon name="description" /> },
  { key: "rows", label: "Filter", icon: <MenuIcon name="filter" /> },
  { key: "copied", label: "When copied", icon: <MenuIcon name="duplicate" /> },
  { key: "place", label: "Place", icon: <MenuIcon name="addEnd" /> },
] as const;

const clampViewLimit = (value: number): number => Number.isFinite(value)
  ? Math.min(VIEW_BINDING_LIMIT_MAX, Math.max(1, Math.trunc(value))) : VIEW_BINDING_LIMIT_DEFAULT;

const AGGREGATES = [
  { fn: "sum", label: "Sum" },
  { fn: "count", label: "Count" },
  { fn: "avg", label: "Average" },
  { fn: "min", label: "Minimum" },
  { fn: "max", label: "Maximum" },
] as const;

/** The fold's name inside a sentence. `AGGREGATES` carries the capitalised option text a select
 *  needs; a heading reading "takes its Sum over" would be title case in the middle of a line,
 *  which the design contract's sentence-case rule forbids. Same five folds, said the other way. */
const AGGREGATE_NOUN: Record<string, string> = {
  sum: "sum", count: "count", avg: "average", min: "minimum", max: "maximum",
};

// ══ W53-T13: WHICH COLUMNS THE SERVER CAN ACTUALLY TOTAL (R7, standing rule 9) ═══════════════
//
// ⭐⭐ THE PICKER MUST NOT OFFER A COLUMN THAT WILL REFUSE. `isNumericType` answers "does this
// column behave like a number", which is the right question for the filter builder and the wrong
// one here: a `formula` column is numeric to the filter kit and has NO SERVER VALUE AT ALL (it is
// worked out in the browser for each row by `formulaEngine.ts`), so totalling it would ask the
// database to add up a column it does not hold. `modules/sheet.py::aggregate_refusal` refuses it
// by name at bind time; this predicate is what stops the person being sent there in the first
// place, and the two have to agree or the picker offers a dead end.
//
// ⚠ IT IS A SECOND OPINION ABOUT THE SAME RULE, WHICH IS ACCEPTED HERE FOR ONE REASON: the server
// is still the one that decides, and it refuses by name if this list is ever wrong. The client's
// job is to keep a person out of a refusal, never to be the only thing checking.

/** The rollup folds that produce a number. Mirrors `core/user_tables.py::ROLLUP_FNS`, minus the
 *  folds that produce text or a boolean (`latest`, `and`/`or`/`xor`, `concatenate`, `arrayjoin`,
 *  `arraycompact`, `arrayunique`). */
const NUMERIC_ROLLUP_FNS = [
  "sum", "average", "stdev", "min", "max", "count", "counta", "countall",
];

/** A METRIC column: a business number measured over a window, rather than a value stored on the
 *  record. The test is the `measure` bag, exactly as `aios_grid.measure_fields_of` tests it, never
 *  the field's `type` (the two live ones on `customer_data` are typed `currency` and `int`). */
const isMetricField = (f: Field): boolean => Boolean(f.measure) || f.type === "metric";

/** Can this database add this column up? Mirrors `modules/sheet.py::aggregate_refusal`. */
const canTotal = (f: Field): boolean => {
  if (f.type === "formula") return false;
  if (f.type === "rollup") {
    const bag = f.rollup;
    if (!bag) return false;
    if (bag.source) return true;
    return NUMERIC_ROLLUP_FNS.includes(String(bag.fn ?? ""));
  }
  return true;
};

/** A Sheet names a DATABASE KEY; the workspace door speaks `SurfaceScope`. Same pair as DrillModal. */
const scopeOf = (database: string): SurfaceScope | null => {
  if (database === "customer_data") return "customer";
  if (database === "product_data") return "product";
  return database.startsWith("ut_") ? (database as SurfaceScope) : null;
};

// ══ THE PERIOD (R9) ═══════════════════════════════════════════════════════════════════════════
//
// β›”β›” CONTRACT C2 SPELLS THIS ON THE WIRE AND THE UI DOES NOT GET A VOTE:
// Unit values are lowercase on the wire. Day/Week starts use `YYYY-MM-DD`, with Week starting
// on Monday; Month/Quarter/Year starts retain `YYYY-MM`.
// A frozen period keeps that pair for returning to the calendar, and adds only
// `frozen: true, from: "YYYY-MM-DD", to: "YYYY-MM-DD"` in place of a cell reference.
//
// ⭐ `start` IS THE PERIOD'S FIRST MONTH, and that is the decision the ticket leaves implicit.
// `unit` and `start` have to jointly name exactly one period, so Q3 2026 is `2026-07` and the year
// 2026 is `2026-01`. Stamping today's month under a quarter unit would agree with nothing: the
// server compiler reads the pair, and two readings of `2026-08` under `quarter` (August, or Q3)
// are a silent disagreement that no screen shows.

export interface PeriodBinding extends BindingPeriod {
  frozen?: true;
  from?: string;
  to?: string;
  window?: WindowSpec;
}

// ⭐ D-687 - THE UNITS ARE `types.ts::PERIOD_UNITS` AND ARE NOT RE-TYPED HERE; ONLY THE WORDING IS
// LOCAL. The table is keyed `Record<PeriodUnit, ...>` so a unit ADDED to the shared tuple is a
// COMPILE ERROR here rather than a blank option, and the select is built by mapping the shared
// tuple, so a unit REMOVED there leaves this control without a second edit. Each entry is written
// out as an object literal because `verify_wiring.py:5641` reads three of them as literal text.
const PERIOD_UNIT_LABELS: Record<PeriodUnit, { unit: PeriodUnit; label: string }> = {
  day: { unit: "day", label: "Day" },
  week: { unit: "week", label: "Week" },
  month: { unit: "month", label: "Month" },
  quarter: { unit: "quarter", label: "Quarter" },
  year: { unit: "year", label: "Year" },
};
const PERIOD_UNIT_OPTIONS = PERIOD_UNITS.map((unit) => PERIOD_UNIT_LABELS[unit]);

const MONTH_NAMES = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
];

/** The noun a sentence uses for one step. Sentence case, and no dash anywhere near it. */
const UNIT_NOUN: Record<PeriodUnit, string> = {
  day: "day", week: "week", month: "month", quarter: "quarter", year: "year",
};

const pad2 = (n: number) => String(n).padStart(2, "0");

/** `{year, month}` out of a `"YYYY-MM"`; today when the string is absent or malformed. */
function splitYm(ym: string): { y: number; m: number } {
  const hit = /^(\d{4})-(\d{2})$/.exec(ym ?? "");
  if (!hit) {
    const now = new Date();
    return { y: now.getFullYear(), m: now.getMonth() + 1 };
  }
  const m = Number(hit[2]);
  return { y: Number(hit[1]), m: m >= 1 && m <= 12 ? m : 1 };
}

const joinYm = (y: number, m: number) => `${y}-${pad2(m)}`;

/** THE PERIOD'S FIRST MONTH, which is what `start` means. See the block above. */
export function normalizePeriodStart(unit: PeriodUnit, ym: string): string {
  if (unit === "day" || unit === "week") {
    const text = /^\d{4}-\d{2}$/.test(ym) ? `${ym}-01` : ym;
    const date = new Date(`${text}T00:00:00Z`);
    if (!Number.isFinite(date.getTime()) || date.toISOString().slice(0, 10) !== text) return text;
    if (unit === "week") date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 6) % 7);
    return date.toISOString().slice(0, 10);
  }
  const { y, m } = splitYm(ym.slice(0, 7));
  if (unit === "year") return joinYm(y, 1);
  if (unit === "quarter") return joinYm(y, 1 + 3 * Math.floor((m - 1) / 3));
  return joinYm(y, m);
}

/** The inclusive day range a calendar period covers. Mirrors
 *  `platform/modules/sheet.py::period_window`, whose `to` is the LAST DAY of the period. */
export function periodRange(unit: PeriodUnit, ym: string): { from: string; to: string } {
  const start = normalizePeriodStart(unit, ym);
  if (unit === "day" || unit === "week") {
    const last = new Date(`${start}T00:00:00Z`);
    if (!Number.isFinite(last.getTime())) return { from: "", to: "" };
    last.setUTCDate(last.getUTCDate() + (unit === "week" ? 6 : 0));
    return { from: start, to: last.toISOString().slice(0, 10) };
  }
  const last = new Date(`${shiftPeriodStart(start, unit, 1)}-01T00:00:00Z`);
  last.setUTCDate(last.getUTCDate() - 1);
  return { from: `${start}-01`, to: last.toISOString().slice(0, 10) };
}

// ⚠ W53-T16 (instruction 13) - `periodLabel` LIVED HERE and is gone with the summary block that
// was its only caller. The period a person reads is now the Year / Month / Quarter pickers
// themselves, which is where they set it, so a second rendering of the same value had nothing left
// to tell them.

const todayYm = () => {
  const now = new Date();
  return joinYm(now.getFullYear(), now.getMonth() + 1);
};

/**
 * ⭐⭐ W51-T12 - THE READ-SIDE MIGRATION, AND IT IS A NAMED FUNCTION SO A GATE CAN PIN IT.
 *
 * Before this ticket a binding's period was `{ref}` and nothing else: a raw typed A1 string, with
 * no unit, no start and no lock. Under R9 an UNLOCKED period SHIFTS when the cell is copied across
 * columns, so reading an old binding as unlocked would change what a shipped cell answers the first
 * time somebody dragged it - a value moving on its own, with no edit and no warning.
 *
 * β›” SO A `ref`-ONLY PERIOD BECOMES LOCKED. `unit` and `start` are non-optional in C2 and have to
 * carry something, but on a ref-driven period they are INERT: the referenced cell decides the
 * period, and `locked: true` is what stops the drag rule from touching it either way.
 *
 * β›”β›” W53-T16 / D-660 - A STORED PERIOD THAT NAMES NO WINDOW READS BACK AS NO PERIOD, and this is
 * the READ half of the fix whose write half is `platform/modules/sheet.py::clean_period`. A period
 * carrying a unit but no usable `start` and no `ref` used to have TODAY'S MONTH filled in for it
 * here, so an all-time cell opened as "September 2026" and the next save narrowed it to one month
 * with nobody told. Filling a missing start is only legitimate when a `ref` decides the period
 * anyway, which is the inert case the paragraph above describes.
 */
export function migratePeriod(raw: unknown): PeriodBinding | null {
  if (!raw || typeof raw !== "object") return null;
  const p = raw as Record<string, unknown>;
  // D-687: types.ts belongs to another lane this wave, so wrap its reader rather than widen it.
  const shared = bindingPeriod({ period: p });
  if (!shared) return null;
  const ref = shared.ref ?? "";
  // β›” C5 - A DECLARED WINDOW MUST VALIDATE AS THE SHARED WINDOW VOCABULARY. Letting an invalid
  // window fall through would misread it as the legacy ref-only dialect or invent a calendar month.
  if ("window" in p) {
    const window = normalizeWindow(p.window);
    if (!window) return null;
    return {
      unit: "month",
      start: normalizePeriodStart("month", todayYm()),
      locked: true,
      window,
      ...(p.ending && typeof p.ending === "object" ? {
        ending: p.ending as PeriodBinding["ending"],
        endingStep: (p.endingStep ?? endingStepDefault(window.kind)) as EndingStep,
        endingOffset: Number(p.endingOffset ?? 0), locked: shared.locked,
        ...(ref ? { ref } : {}),
      } : {}),
    };
  }
  const declared = PERIOD_UNITS.some((unit) => unit === p.unit);
  if (!declared) {
    // The legacy shape. Nothing shifts by surprise: it reads back LOCKED.
    if (!ref) return null;
    return { unit: "month", start: normalizePeriodStart("month", todayYm()), locked: true, ref };
  }
  const { unit, start: stored, locked } = shared;
  // D-660: no window named, and no cell to take one from, so there is no period to read.
  const startPattern = unit === "day" || unit === "week" ? /^\d{4}-\d{2}-\d{2}$/ : /^\d{4}-\d{2}$/;
  if (!startPattern.test(stored) && !ref && p.frozen !== true) return null;
  const start = normalizePeriodStart(unit, stored || todayYm());
  if (p.frozen === true) {
    return {
      unit, start, locked, frozen: true,
      from: typeof p.from === "string" ? p.from : "",
      to: typeof p.to === "string" ? p.to : "",
    };
  }
  return ref ? { unit, start, locked, ref } : { unit, start, locked };
}

// ══ THE DRAG RULES (R10) ══════════════════════════════════════════════════════════════════════
//
// TWO DIRECTIONAL SETTINGS, and C2 spells them `onDrag: {across: "period"|"none",
// down: {field: key}|"none"}`. Defaults: across = period, down = none.

// β›”β›” THIS UNION IS STATED HERE ON PURPOSE AND D-687 DOES NOT REVOKE IT. `verify_wiring.py:5782`
// reads this exact line as TEXT, because C2's wire vocabulary is what that leg was really for, and
// this is the file that documents the wire. D-687 is about a SECOND OPINION that can drift in
// silence, not about an absent declaration: the constant below makes any disagreement with
// `types.ts::DragAcross` stop compiling, which is the outcome D-687 exists to get.
export type DragAcross = "period" | "none";
export const DRAG_ACROSS_LOCK_STEP: [DragAcross, SharedDragAcross] extends
  [SharedDragAcross, DragAcross] ? true : never = true;

export interface OnDragBinding {
  across: DragAcross;
  down: { field: string } | "none";
  steps?: readonly BindingDragStep[];
}

/** A copy step walks a column's stored values. Measure-backed and Metric columns are computed
 *  numbers with no stored values to walk, so offering one promises a step `dragBoundCell`
 *  cannot perform.
 *
 *  S66-T16 / D-720 (R15, SDLC 66 board, 2026-09-25): a SET column (`multi`, or a multi-select)
 *  is refused too. One cell of it holds several values, so "the next value down" has no single
 *  answer, and the copy would bind a condition the person never picked. This supersedes the
 *  2026-09-16 re-anchor (W-145) that let a set column step by member; lane D's two
 *  `verify_wiring.py` W58-T17 legs that pin that reading are a COMBINE-AMEND (context/S66-T16.md). */
export function isDragDownField(f: Field): boolean {
  if (f.multi || f.type === "multiselect") return false;
  return Boolean(f.key) && !f.key.startsWith("__") && !f.measure && f.type !== "metric";
}

/** The saved `onDrag`, defaulted. `down` is carried as a field key, empty meaning nothing. */
export function readOnDrag(raw: unknown): { across: DragAcross; down: string } {
  const rules = bindingOnDrag({ onDrag: raw });
  return { across: rules.across, down: rules.down === "none" ? "" : rules.down.field };
}

/** `scope.adoptedFrom` (R11): the view was purged and its filter was copied into this cell. */
function adoptedFromOf(initial: Record<string, unknown> | null | undefined): string {
  const scope = initial?.scope as Record<string, unknown> | undefined;
  const adopted = scope?.adoptedFrom as Record<string, unknown> | undefined;
  const name = adopted?.name;
  return typeof name === "string" ? name : "";
}

/**
 * ⭐⭐ W53-T12 β€” THE PANEL READS BACK WHAT WAS SAVED, WHICH IT DID NOT DO BEFORE.
 *
 * `database`, `period` and `onDrag` were hydrated from `initial`; `fn`, `field`, the scope kind,
 * the view id and the filter tree were NOT, so opening an already bound cell showed Sum, no
 * column and "Choose a view" no matter what the cell actually pointed at, and pressing Save wrote
 * those defaults over the real binding. Nothing could tell a person their saved view had gone
 * missing while the editor never showed which view they had saved.
 *
 * ⚠ AN AGGREGATE MAY CARRY `metric_key` INSTEAD OF `fn` (the server's normalizer accepts it and no
 * control here speaks it yet), so an unrecognised aggregate falls back to the panel's own defaults
 * rather than seeding a `<select>` with a value it has no option for.
 */
export function readAggregate(raw: unknown): { fn: string; field: string } {
  const a = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
  const named = typeof a.fn === "string" ? a.fn : "";
  const known = AGGREGATES.some((x) => x.fn === named);
  return {
    fn: known ? named : "sum",
    field: known && typeof a.field === "string" ? a.field : "",
  };
}

/** The saved scope: a view id, or a filter tree built in this panel. Neither means an empty view. */
export function readScope(raw: unknown): {
  kind: "view" | "filter"; viewId: string; tree: FilterTree;
} {
  const empty: FilterTree = { conj: "and", nodes: [] };
  const s = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
  const viewId = typeof s.view_id === "string" ? s.view_id.trim() : "";
  if (viewId) return { kind: "view", viewId, tree: empty };
  const f = s.filter;
  if (f && typeof f === "object") {
    const t = f as Record<string, unknown>;
    return {
      kind: "filter",
      viewId: "",
      tree: {
        conj: t.conj === "or" ? "or" : "and",
        nodes: Array.isArray(t.nodes) ? (t.nodes as FilterTree["nodes"]) : [],
      },
    };
  }
  return { kind: "view", viewId: "", tree: empty };
}

/** The view the binding NAMES, kept even after the id is cleared, so the notice can still say it. */
function savedViewOf(initial: Record<string, unknown> | null | undefined): {
  database: string; id: string; name: string;
} {
  const scope = (initial?.scope ?? {}) as Record<string, unknown>;
  return {
    database: typeof initial?.database === "string" ? initial.database : "",
    id: typeof scope.view_id === "string" ? scope.view_id.trim() : "",
    name: typeof scope.view_name === "string" ? scope.view_name : "",
  };
}

/** One-release compatibility: qualify leaves without discarding any operand or group. */
function rekeyFilter(tree: FilterTree, keyOf: (key: string) => string): FilterTree {
  const visit = (node: FilterNode): FilterNode => isFilterGroup(node)
    ? { ...node, children: node.children.map(visit) }
    : { ...node, colId: keyOf(node.colId),
        ...(node.rhs && "colId" in node.rhs
          ? { rhs: { ...node.rhs, colId: keyOf(node.rhs.colId) } } : {}) };
  return { ...tree, nodes: tree.nodes.map(visit) };
}

function initialFilterScope(initial: Record<string, unknown> | null | undefined) {
  const scope = readScope(initial?.mode === "view"
    ? { filter: initial.filter ?? { conj: "and", nodes: [] } } : initial?.scope);
  const rawScope = initial?.scope as Record<string, unknown> | undefined;
  const original = scope.kind === "view" && rawScope?.filter
    ? readScope({ filter: rawScope.filter }).tree : scope.tree;
  const legacy = bindingRelated(initial);
  if (!legacy) return { ...scope, tree: original };
  const relatedTree = Array.isArray(legacy.filter)
    ? { conj: "and" as const, nodes: legacy.filter as FilterNode[] }
    : readScope({ filter: legacy.filter }).tree;
  const qualified = rekeyFilter(relatedTree, (key) => `related:${legacy.via}:${key}`);
  const nodes = original.conj === "or" && original.nodes.length
    ? [{ conj: original.conj, children: original.nodes }] : original.nodes;
  return { ...scope, tree: { conj: "and" as const, nodes: [...nodes,
    { conj: qualified.conj ?? "and", children: qualified.nodes }] } };
}

function usesMetric(tree: FilterTree, fields: Field[], measures: Measure[]): boolean {
  const visit = (node: FilterNode): boolean => isFilterGroup(node) ? node.children.some(visit)
    : fields.some((field) => field.key === node.colId && isMetricField(field))
      || measures.some((measure) => measure.key === node.colId);
  return tree.nodes.some(visit);
}

type BindingView = Pick<SavedView, "id" | "name"> & {
  config: Pick<SavedView["config"], "filterConj" | "filters">;
};

/** Workspace view names and the filter clauses a copied cell can step. */
function viewList(raw: unknown): BindingView[] {
  if (!Array.isArray(raw)) return [];
  return (raw as GridWorkspace["views"]).map((v) => ({
    id: v.id,
    name: v.name,
    config: {
      filterConj: v.config?.filterConj === "or" ? "or" : "and",
      filters: Array.isArray(v.config?.filters) ? v.config.filters : [],
    },
  }));
}

// ══ ⭐⭐ W54-T31 (ruling R8; owner instructions 6 and 8) β€” THE AGGREGATE'S COLUMN LIST ═════════
//
// ⭐⭐ R8, VERBATIM: "Aggregate is always visible. The Fields list appears in exactly two places:
// choosing the Aggregate's column, and choosing a field inside 'A filter I build here'. It is
// hidden everywhere else, including under 'A saved view', where the view already fixes the rows.
// Each Fields list is labelled with what it is picking, so several `sales.. metrics` entries are
// distinguishable."
//
// β›” WHAT CHANGED IS WHERE THE LIST LIVES, NOT WHETHER IT EXISTS. Before this ticket the list was
// a permanently expanded box inside a 380px column: it painted under "A saved view" as well, and
// it spent about 90px of the panel's height on a list nobody was currently choosing from
// (`shots/T31-fields-before.png`). Instruction 6 asks for the Data module's Fields presentation
// "but the popup in the middle, just like building a Filter under 'Rows to include'", so the list
// becomes a centred dialog opened from a control that shows the CHOSEN column. The panel keeps a
// single line for Column in every configuration, which is what instruction 8's "Fields should auto
// hide for everything that is not part of the Aggregate value Column or the Filter fields" buys.
//
// β›”β›” THE PROVIDER AROUND THE DIALOG IS THE SAME LOAD-BEARING ONE `SheetFilterPopup` DOCUMENTS,
// and it is why `SheetColumnPicker` is split from the dialog below it. The Sheet route mounts NO
// `OverlayProvider` of its own (`App.tsx` gives one to the hosted-grid branch only), so a
// body-level overlay opened here has a null `OverlayStackContext` and `useOverlayLayer` cannot
// tell whether a higher layer owns a pointerdown. Wrapping puts every layer opened underneath
// this dialog on one stack, so a click inside a nested picker is never read as an outside click
// that dismisses the surface below it. That failure is exactly the "clicking Fields just closes
// the window" report instruction 8 names.
//
// β›” AND IT IS MOUNTED LATE, CONDITIONALLY, for the reason the filter popup already records:
// `useOverlayLayer` claims Escape the moment it runs and `ui/useEscapeClose` hands the key to the
// LAST entry pushed. The editor's own claim was pushed at mount; this one is pushed when the
// dialog opens, so one Escape closes the column list and the next closes the panel.

interface ColumnPickerProps {
  /** The cell being bound, so the title says which cell this list is about. */
  addr: string;
  /** The fold, said inside a sentence: "sum", "average", "minimum". */
  aggregateNoun: string;
  /** The database's own label. Two databases can both offer a column called "Total". */
  databaseLabel: string;
  /** The offer after the search box, which is what the list renders. */
  shown: Field[];
  /** The offer before the search box. The empty state must tell a search miss from an empty
   *  database, and those two ask different things of the reader. */
  offered: Field[];
  /** Every field the database has, for the third empty-state sentence. */
  all: Field[];
  chosen: string;
  query: string;
  onQuery: (next: string) => void;
  onPick: (key: string) => void;
  onClose: () => void;
}

/** The dialog itself. Split from the export ONLY so `useOverlayLayer` runs BELOW the provider. */
function ColumnPickerDialog({
  addr, aggregateNoun, databaseLabel, shown, offered, all, chosen, query,
  onQuery, onPick, onClose,
}: ColumnPickerProps) {
  const panelRef = useRef<HTMLDivElement>(null);
  const titleId = useId();
  const listId = useId();
  useOverlayLayer({
    panelRef,
    onDismiss: onClose,
    dismissOnOutside: false,
    initialFocus: "first",
    restoreFocus: true,
    trapFocus: true,
  });


  return (
    <BodyPortal>
      <div className="lp-dialog-scrim">
        <div
          ref={panelRef}
          className="lp-dialog sheet-column-popup"
          role="dialog"
          aria-modal="true"
          aria-labelledby={titleId}
          data-overlay-kind="sheet-column"
        >
          <div className="lp-dialog-head">
            <h2 className="lp-dialog-title" id={titleId}>
              {`The column ${addr} takes its ${aggregateNoun} over`}
            </h2>
            <button
              type="button"
              className="lp-dialog-x"
              aria-label={`Close the column list for ${addr}`}
              onClick={onClose}
            >
              <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
                <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
                      strokeLinecap="round" />
              </svg>
            </button>
          </div>

          {/* ⭐ THE SHAPE IS `filter-kit/FieldsHidePanel.tsx`'s, which is what instruction 6 asks
              for by name: a quiet heading, then a find box, then the rows. Nothing here is a new
              control; `cg-fields-section-title`, `cg-type-search`, `cg-type-list`, `cg-type-row`
              and `cg-fsel-hint` are all shipped, top-level classes in `index.css`. */}
          <div className="sheet-col-pick">
            {/* ⭐⭐ THE HEADING R8 ASKS FOR, AND IT NAMES BOTH HALVES OF WHAT IS BEING PICKED:
                which database the columns come from, and what they are going to be used for. The
                owner's report was several entries reading "sales.. metrics" with nothing saying
                which list they belonged to; a list that says what it is picking answers that
                before a single row is read. */}
            <div className="cg-fields-section-title" id={listId}>
              {`Fields on ${databaseLabel} to take the ${aggregateNoun} over`}
            </div>

            {/* ⭐ THE SEARCH BOX HAS NO CONDITION AROUND IT (wave-50 R16). A control that appears
                at eleven fields and not at ten is a control nobody learns is there. */}
            <div className="cg-type-search sheet-pick-search">
              <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
                <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={query}
                placeholder="Find a column…"
                aria-label="Find a column"
                onChange={(e) => onQuery(e.currentTarget.value)}
              />
            </div>

            {/* β›” THE LIST IS NOT RENDERED WHEN IT HAS NO ROWS. `.sheet-pick-list` carries a
                border and 3px of padding, so an empty one painted a thin bordered strip under
                the search box with the explanation sitting outside it, which reads as a picker
                that failed rather than a database with nothing to offer. */}
            {shown.length > 0 && (
              <div className="cg-type-list sheet-pick-list" role="listbox"
                   aria-labelledby={listId}>
                {shown.map((f) => (
                  <button
                    key={f.key}
                    type="button"
                    role="option"
                    aria-selected={f.key === chosen}
                    className={"cg-type-row" + (f.key === chosen ? " is-on" : "")}
                    onClick={() => onPick(f.key)}
                  >
                    {/* ⭐ THE ICON COMES BEFORE THE NAME (owner instruction 24), and a Metric
                        wears the measure glyph rather than its storage type's. One glyph
                        vocabulary, one source: `iconShapes.ts::TYPE_SHAPES`. */}
                    <FieldTypeIcon
                      type={isMetricField(f) ? "measure" : f.type}
                      title={isMetricField(f) ? "Metric" : f.type}
                    />
                    <span className="cg-type-label">
                      {f.label}
                      {/* ⭐⭐ WHAT MAKES TWO ROWS TELLABLE APART. Labels collide - the owner saw
                          several reading "sales.. metrics" - and the field's own key never does,
                          because it is what the database stores the column under. `cg-fsel-hint`
                          is the shipped quiet second line `FieldSelect` already paints under a
                          label, so this is that pattern's second caller and not a new one. */}
                      <span className="cg-fsel-hint">{f.key}</span>
                    </span>
                    {/* ⚠ THE WORD IS THERE TOO, because a glyph alone is only legible to somebody
                        who already knows the vocabulary. */}
                    {isMetricField(f) && (
                      <span className="sheet-period-note">Metric</span>
                    )}
                  </button>
                ))}
              </div>
            )}

            {/* AN EMPTY LIST SAYS WHY (R16). The causes need different acts from the reader. */}
            {shown.length === 0 && (
              <p className="sheet-pick-empty">
                {offered.length > 0
                  ? "No column matches that search."
                  : (all.some((f) => isNumericType(f.type))
                    ? "The number columns on this database are worked out in the browser for "
                      + "each row, so there is nothing stored here to total."
                    : "This database has no number column to total.")}
              </p>
            )}

          </div>
        </div>
      </div>
    </BodyPortal>
  );
}

/** The centred column list, on its own overlay stack. See the block above for why the provider
 *  is not decoration. */
export function SheetColumnPicker(props: ColumnPickerProps) {
  return (
    <OverlayProvider>
      <ColumnPickerDialog {...props} />
    </OverlayProvider>
  );
}

/** The field control's own footprint, using the existing static skeleton tone. */
function BindingSkeleton({ addr }: { addr: string }) {
  // Keep the picker footprint while its field list arrives, without hiding the editor body.
  return <span className="cg-select cg-fsel" role="status" aria-label={`Loading fields for ${addr}`}>
    <span className="sheet-binding-skeleton-control" style={{ width: "100%" }} aria-hidden="true" />
  </span>;
}

export interface BindingEditorProps {
  workbookId: string;
  addr: string;
  /** Every database this reader may open (R8). The page supplies it; this panel invents nothing. */
  databases: { key: string; label: string }[];
  initial?: Record<string, unknown> | null;
  onSave: (binding: Record<string, unknown>) => void;
  onCancel: () => void;
  /** What a referenced cell reads now, so a filter value taken from a cell is shown, not blank. */
  readCell?: ReadBindingCell;
  /**
   * HOTFIX 2026-09-29 (owner: "clicking edit for cell database ... is still very slow"). The
   * workbook the page is already painting. Preview and Save read their cell values from it
   * instead of downloading the whole workbook again (twice per Preview, before this).
   */
  workbook?: Workbook;
  /** The tab the edited cell is on, so a bare reference like `F8` is read on THAT tab. */
  homeTab?: { id: string; name: string };
}

export default function BindingEditor({
  workbookId, addr, databases, initial, onSave, onCancel, readCell, workbook, homeTab,
}: BindingEditorProps) {
  const [activeSection, setActiveSection] = useState<typeof BINDING_SECTIONS[number]["key"]>("data");
  const [shape, setShape] = useState<"value" | "view">(initial?.mode === "view" ? "view" : "value");
  const [viewType, setViewType] = useState<ViewBinding["viewType"]>(() =>
    VIEW_BINDING_TYPES.includes(initial?.viewType as ViewBinding["viewType"])
      ? initial!.viewType as ViewBinding["viewType"] : "grid");
  const [viewFields, setViewFields] = useState<string[]>(() => initial?.mode === "view"
    && Array.isArray(initial.fields) ? initial.fields.filter((key): key is string => typeof key === "string") : []);
  const [viewLimit, setViewLimit] = useState(() => clampViewLimit(
    typeof initial?.limit === "number" ? initial.limit : VIEW_BINDING_LIMIT_DEFAULT));
  const [viewSort, setViewSort] = useState<ViewBinding["sort"]>(() =>
    initial?.mode === "view" && Array.isArray(initial.sort) ? initial.sort.flatMap((item) => {
      if (!item || typeof item !== "object" || typeof item.field !== "string"
        || (item.dir !== "asc" && item.dir !== "desc")) return [];
      return [{ field: item.field, dir: item.dir }];
    }) : []);
  const [database, setDatabase] = useState<string>(
    String((initial?.database as string) ?? databases[0]?.key ?? ""),
  );
  // ⚠ SEEDED ONCE, AT MOUNT, the same way `migratePeriod` and `readOnDrag` below already are. A
  // `useEffect` that re-read `initial` would clobber a live edit the next time the parent
  // re-rendered for an unrelated reason, which is the failure the period note already describes.
  const savedAgg = useState(() => readAggregate(initial?.aggregate))[0];
  const savedSource = useState(() => bindingAggregate(initial?.aggregate))[0];
  // Seed new builders here; changing the shared fallback would alter other readers of saved bindings.
  const [sourceKind, setSourceKind] = useState<BindingAggregate["kind"]>(
    initial?.aggregate == null ? "number" : savedSource.kind,
  );
  const [metricKey, setMetricKey] = useState(savedSource.kind === "number" ? savedSource.metric_key : "");
  const savedScope = useState(() => initialFilterScope(initial))[0];
  const savedView = useState(() => savedViewOf(initial))[0];

  const [fn, setFn] = useState<string>(savedAgg.fn);
  const [field, setField] = useState<string>(savedAgg.field);
  const [scopeKind, setScopeKind] = useState<"view" | "filter">(savedScope.kind);
  const [viewId, setViewId] = useState<string>(savedScope.viewId);
  const [tree, setTree] = useState<FilterTree>(savedScope.tree);
  // W53-T15 β€” what the door below reports. `countConditions` walks nested groups too, so a filter
  // built out of groups is not undercounted into reading as empty.
  const conditionCount = useMemo(() => countConditions(tree.nodes ?? []), [tree]);
  const [fields, setFields] = useState<Field[]>([]);
  const [relatedOffer, setRelatedOffer] = useState<{
    database: string; fields: RelatedFilterField[];
    databases: { via: string; database: string; databaseLabel: string; relationLabel: string }[];
    unavailable: UnavailableRelatedFilterDatabase[];
    loaded: boolean;
  }>({ database: "", fields: [], databases: [], unavailable: [], loaded: false });
  const [relatedNotice, setRelatedNotice] = useState("");
  const filterFields = useMemo(() => [...fields,
    ...(relatedOffer.database === database ? relatedOffer.fields : [])], [fields, relatedOffer, database]);
  const [measures, setMeasures] = useState<Measure[]>([]);
  const [views, setViews] = useState<BindingView[]>([]);
  // β›” THE NOTICE BELOW IS GATED ON THIS FLAG AND NOT ON `views.length`. Before the first answer
  // arrives the list is legitimately empty, and a notice keyed on emptiness would flash "that view
  // is gone" at every perfectly valid binding for as long as the fetch took.
  const [viewsLoaded, setViewsLoaded] = useState(false);
  // Field-dependent controls wait for C2's workspace door. The editor body paints immediately.
  // `viewsLoaded` separately protects saved-view deletion notices from a failed read.
  const [optionsResolved, setOptionsResolved] = useState(false);
  // ⭐⭐ W53-T15 (ruling R8) β€” WHETHER THE CENTRED FILTER DIALOG IS ON SCREEN, and the ONLY state
  // this ticket adds. The tree itself stays in `tree`/`setTree` below and the dialog writes
  // straight into that setter, so there is no draft to reconcile when it closes.
  const [filterPopupOpen, setFilterPopupOpen] = useState(false);
  // ⭐⭐ W54-T31 (ruling R8) β€” WHETHER THE CENTRED COLUMN LIST IS ON SCREEN. It starts CLOSED on
  // every configuration including an unbound cell: the panel's job on open is to show what the
  // cell points at, and a list that opens itself would be back to spending the panel's height on
  // a choice nobody has asked to make.
  const [colPickerOpen, setColPickerOpen] = useState(false);
  // S68-T24: small related-field offers keep their own trigger; values start at a picker.
  const [relatedWanted, setRelatedWanted] = useState(savedScope.kind === "filter" || savedScope.tree.nodes.length > 0);
  const [valuesState, setValuesState] = useState<Record<string, FilterValuesState>>({});
  const valuesRef = useRef<Record<string, FilterValuesState>>({});
  const valuesRequests = useRef(new Map<string, Promise<FilterValuesState | undefined>>());
  const valuesGeneration = useRef(0);
  const stepRequest = useRef(0);
  const [stepNotice, setStepNotice] = useState("");
  const [userOptions, setUserOptions] = useState<string[]>([]);
  const [preview, setPreview] = useState<string>("");
  const [notice, setNotice] = useState<string>("");

  // ⚠ THE MIGRATION RUNS ONCE, AT MOUNT, and its result seeds the controls. Running it on every
  // render would re-read `initial` after the person had already changed a control, which is how an
  // editor forgets an edit the moment its parent re-renders for an unrelated reason.
  const migrated = useState(() => migratePeriod(initial?.period))[0];
  const savedDrag = useState(() => bindingOnDrag(initial))[0];

  const [unit, setUnit] = useState<PeriodUnit>(migrated?.unit ?? "month");
  const [start, setStart] = useState<string>(
    migrated?.start ?? normalizePeriodStart("month", todayYm()),
  );
  const [locked, setLocked] = useState<boolean>(migrated?.locked ?? false);
  // An absent flag is rolling, including every binding saved before frozen dates existed.
  const [frozen, setFrozen] = useState<boolean>(Boolean(migrated?.frozen));
  const [frozenFrom, setFrozenFrom] = useState<string>(
    () => migrated?.from ?? periodRange(unit, start).from,
  );
  const [frozenTo, setFrozenTo] = useState<string>(
    () => migrated?.to ?? periodRange(unit, start).to,
  );
  const range = frozen ? { from: frozenFrom, to: frozenTo } : periodRange(unit, start);
  const resumeRollingPeriod = () => {
    setFrozen(false);
    setFrozenFrom("");
    setFrozenTo("");
  };
  const editPeriodDate = (key: "from" | "to", value: string) => {
    // Capture the other displayed endpoint too: the dropdowns may have moved since mount.
    setFrozenFrom(key === "from" ? value : range.from);
    setFrozenTo(key === "to" ? value : range.to);
    setFrozen(true);
  };
  // β›”β›” W57-T17 - THE DATABASE IS SEEDED AT MOUNT OUT OF A LIST THAT ARRIVES LATER, AND AN EMPTY
  // SEED NEVER HEALED. `databases` is fetched by `SheetPage` from `/api/v1/nav`; a panel opened
  // before that answer lands seeds `database` to `""`, and nothing re-seeds it. A `<select>` whose
  // value matches no option paints its FIRST option, so the panel then SHOWED "Odoo customers"
  // while `database` was empty: `scopeOf("")` is null, the workspace effect takes its no-door
  // branch, and every list in the panel is legitimately empty for a database the reader can see
  // named above them. Observed on a lane screenshot, where the column list read "Fields on to take
  // the sum over" with `databaseLabel` blank and "This database has no number column to total."
  //
  // ⭐ IT ONLY EVER FILLS AN EMPTY VALUE, which is what makes it safe beside the seed-once rule
  // the block above states: a database the person chose is never overwritten, and neither is one
  // read off `initial`. The condition can only be true before any choice has been made.
  useEffect(() => {
    if (!database && databases.length > 0) setDatabase(databases[0].key);
  }, [database, databases]);
  const [periodRef, setPeriodRef] = useState<string>(migrated?.ref ?? "");
  // ⭐ C5 - THE TWO PERIOD SPELLINGS ARE SIBLINGS. The mode is seeded from the saved dialect so
  // opening and saving a rolling window cannot silently turn it into this month's calendar period.
  const [periodMode, setPeriodMode] = useState<"calendar" | "window">(
    migrated?.window ? "window" : "calendar",
  );
  const [windowSpec, setWindowSpec] = useState<WindowSpec>(migrated?.window ?? { kind: "ytd" });
  const [ending, setEnding] = useState<EndingKind>(migrated?.ending?.kind ?? "today");
  const [endingFixed, setEndingFixed] = useState(migrated?.ending?.date ?? "");
  const [endingN, setEndingN] = useState(String(migrated?.ending?.n ?? 1));
  const [endingUnit, setEndingUnit] = useState<EndingStep>(migrated?.ending?.unit ?? "month");
  const [endingStep, setEndingStep] = useState<EndingStep>(
    migrated?.endingStep ?? endingStepDefault(windowSpec.kind));
  const [endingOffset, setEndingOffset] = useState(migrated?.endingOffset ?? 0);
  const [endingSheets, setEndingSheets] = useState<{ id: string; name: string }[]>([]);
  const [endingSheet, setEndingSheet] = useState(() => parseRef(migrated?.ref ?? "")?.sheet ?? "");
  const parsedEndingRef = parseRef(periodRef);
  const endingRef = parsedEndingRef && !parsedEndingRef.sheet && endingSheet
    ? formatRef({ ...parsedEndingRef, sheet: endingSheet }) : periodRef.trim();
  const hasEnding = (TO_DATE_KINDS as readonly string[]).includes(windowSpec.kind);
  const endingToday = new Date();
  const relativeEndingBounds = ending === "n_before_today" && hasEnding
    ? endingBounds(windowSpec.kind, ending, "",
      `${endingToday.getFullYear()}-${pad2(endingToday.getMonth() + 1)}-${pad2(endingToday.getDate())}`,
      endingStep, endingOffset, Number(endingN), endingUnit) : null;
  // "Use a cell" is a LINK that REVEALS the A1 input (R9). The input was the whole period control
  // before this ticket and it is not deleted, only demoted to the thing behind that link.
  const [refOpen, setRefOpen] = useState<boolean>(Boolean(migrated?.ref));
  // β›”β›” D-660 - `period` MUST NOT BE EMITTED UNLESS SOMEBODY ACTUALLY CHOSE ONE. A binding opened
  // with no saved period (`migrated === null`, an all-time sum) seeds `unit`/`start`/`locked` with
  // DEFAULTS purely so the controls have something to display; those defaults are not a decision
  // anybody made. Saving them unconditionally is exactly the bug: Save stamps `{unit:"month",
  // start:<this month>}` over an all-time binding the person never touched. So this flag starts
  // TRUE only when a period was already on the binding, and re-saving that binding unchanged keeps
  // saving it.
  //
  // ⭐⭐ W53-T16 - AND IT IS NOW A CONTROL SOMEBODY CAN SEE AND TURN OFF, not a hidden flag. Before
  // this ticket the flag was raised by any touch of any period control and could never be lowered:
  // an all-time cell LOOKED like it was set to this month (the pickers show a default they are not
  // applying) and a cell narrowed to a period could not be widened back to all time from this panel
  // at all, which is standing rule 1's second sentence - a limit nobody was told about. The switch
  // below states which of the two a cell is, and either answer is one click from the other.
  // New Metrics require a period. A saved Metric with no period keeps its all-time scope;
  // a malformed saved period is not an absent one. Field and view filters opt in.
  const savedAllTimeMetric = useState(() => initial != null && initial.mode !== "view"
    && initial.period == null && savedSource.kind === "number" && Boolean(savedSource.metric_key))[0];
  const [valuePeriodOn, setValuePeriodOn] = useState<boolean>(Boolean(migrated)
    || (sourceKind === "number" && !savedAllTimeMetric));
  const [viewPeriodOn, setViewPeriodOn] = useState<boolean>(Boolean(migrated));
  const periodOn = shape === "view" ? viewPeriodOn : valuePeriodOn;
  const setPeriodOn = shape === "view" ? setViewPeriodOn : setValuePeriodOn;
  const [copySteps, setCopySteps] = useState<readonly BindingDragStep[]>(() =>
    (savedDrag.steps ?? []).filter((step) =>
      (step.field !== BINDING_PERIOD_STEP && step.field !== BINDING_ENDING_STEP) || !migrated?.locked));
  const [copyStepsEdited, setCopyStepsEdited] = useState(false);
  const updateCopySteps = (steps: readonly BindingDragStep[]) => {
    stepRequest.current += 1;
    setStepNotice("");
    setCopySteps(steps); setCopyStepsEdited(true);
  };
  const across: DragAcross = copySteps.some((step) =>
    step.field === BINDING_PERIOD_STEP || step.field === BINDING_ENDING_STEP) ? "period" : "none";
  const setAcross = (value: DragAcross) => {
    const field = hasEnding ? BINDING_ENDING_STEP : BINDING_PERIOD_STEP;
    const kept = copySteps.filter((step) => step.field !== field);
    updateCopySteps(value === "none" ? kept : [...kept, { field, axis: "across",
      ...(hasEnding ? { size: endingStep } : {}),
    }]);
  };

  const adoptedFrom = adoptedFromOf(initial);

  // ⭐ ESCAPE CLOSES THE PANEL, through the base kit's ONE arbiter (C8) rather than a listener of
  // this component's own. `cancelEditFirst` stays FALSE: the done-when says the panel closes on
  // Escape, and opting in would make the FIRST Escape do nothing whenever focus sat in one of the
  // text inputs this panel is full of.
  const panelRef = useRef<HTMLElement | null>(null);
  const onEscape = useCallback(() => onCancel(), [onCancel]);
  const escapeContainer = useCallback(() => panelRef.current, []);
  useEscapeClose(true, onEscape, { container: escapeContainer });

  // C2 owns workspace memoisation in the existing client door; Sheet keeps no workspace cache.
  // Its field list fills the skeleton controls and revalidates saved fields/views as before.
  useEffect(() => {
    let live = true;
    const scope = scopeOf(database);
    setViewsLoaded(false);
    setOptionsResolved(false);
    setFields([]);
    setViews([]);
    setMeasures([]);
    // Picker pages belong to one mounted editor and one database, never to another caller.
    valuesGeneration.current += 1;
    valuesRef.current = {};
    valuesRequests.current.clear();
    setValuesState({});
    setStepNotice("");
    stepRequest.current += 1;
    if (!scope) {
      setFields([]);
      setViews([]);
      setUserOptions([]);
      // β›” W54-T33 β€” RESOLVED, NOT LOADING. This database has no workspace door, so its empty
      // lists are the true and final answer; leaving the flag down would leave a skeleton running
      // forever over a panel that is never going to be given anything else.
      setOptionsResolved(true);
      return () => { live = false; };
    }
    // HOTFIX 2026-09-29: a scope this page read moments ago paints NOW from the memo, so a second
    // Edit does not sit on a skeleton for a multi-second assembly. The server read below still
    // runs and replaces these lists (and drops a view that no longer exists) when it answers.
    const memo = peekWorkspace(scope, { fieldsOnly: true });
    if (memo) {
      setFields((memo.fields ?? []) as Field[]);
      setMeasures(memo.measures ?? []);
      setViews(viewList(memo.views));
      setUserOptions(memo.userOptions ?? []);
      setViewsLoaded(true);
      setOptionsResolved(true);
    }
    (async () => {
      // ONE door, and it is the one that knows what exists now.
      const fresh = await fetchWorkspace(scope, { fieldsOnly: true });
      if (!live) return;
      if (!fresh) {
        // A failed fresh permission question cannot leave an earlier offer writable.
        setFields([]);
        setMeasures([]);
        setViews([]);
        setUserOptions([]);
        setViewsLoaded(false);
        setNotice("These fields could not be loaded. Close and reopen this panel to try again.");
        // β›” W54-T33 β€” BUT THE PANEL REVEALS EITHER WAY. Nothing better is coming for this
        // database, and a skeleton that outlives the request it was waiting on tells the reader
        // the panel is broken rather than that the server would not answer.
        setOptionsResolved(true);
        return;
      }
      const list = viewList(fresh.views);
      setFields((fresh.fields ?? []) as Field[]);
      setMeasures(fresh.measures ?? []);
      setViews(list);
      // Keep declared people choices from the workspace without a records download.
      setUserOptions(fresh.userOptions ?? []);
      setViewsLoaded(true);
      // β›” A SELECTED VIEW THAT NO LONGER EXISTS IS CLEARED, so Save cannot store a dead id β€” that
      // stored id is exactly the state this ticket was reported for. The notice in `Rows to
      // include` is what explains the empty control; clearing without saying so would read as the
      // panel losing the choice on its own.
      setViewId((cur) => (cur && !list.some((v) => v.id === cur) ? "" : cur));
      // β›” W54-T33 β€” LAST, AFTER THE DEAD ID IS CLEARED. React batches these into one paint, so
      // the first frame the reader sees is the settled one: a view that no longer exists has
      // already been dropped and its notice is already computed, rather than showing for a frame.
      setOptionsResolved(true);
    })();
    return () => { live = false; valuesGeneration.current += 1; stepRequest.current += 1; };
  }, [database]);

  // Reaching the filter still asks for its related-field list, independently of value pickers.
  useEffect(() => {
    if (scopeKind === "filter" || filterPopupOpen || colPickerOpen || activeSection === "copied")
      setRelatedWanted(true);
  }, [scopeKind, filterPopupOpen, colPickerOpen, activeSection]);

  // The related grid's field wall is checked on the server. Keep its labelled fields in the
  // existing Filter picker only; a customer's amount is not an order aggregate column.
  useEffect(() => {
    if (!relatedWanted || !database) return undefined;
    const controller = new AbortController();
    setRelatedOffer({ database, fields: [], databases: [], unavailable: [], loaded: false });
    setRelatedNotice("");
    (async () => {
      try {
        const response = await fetch(`${API_V1}/sheets/filter-fields/${encodeURIComponent(database)}`, {
          credentials: CREDENTIALS, signal: controller.signal,
        });
        const body = await response.json().catch(() => null);
        if (!response.ok || !Array.isArray(body?.fields) || !Array.isArray(body?.databases))
          throw new Error(body?.error?.message || "Related fields could not be loaded. Close and reopen this panel to retry.");
        if (!controller.signal.aborted) {
          setRelatedOffer({ database, fields: body.fields as RelatedFilterField[],
            databases: body.databases, unavailable: Array.isArray(body.unavailable) ? body.unavailable : [],
            loaded: true });
          const aliases = new Map<string, string>();
          for (const field of body.fields as RelatedFilterField[])
            for (const legacy of field.related?.legacyKeys ?? []) aliases.set(legacy, field.key);
          setTree((current) => rekeyFilter(current, (key) => aliases.get(key) ?? key));
        }
      } catch (error) {
        if (!controller.signal.aborted) setRelatedNotice(error instanceof Error ? error.message
          : "Related fields could not be loaded. Close and reopen this panel to retry.");
      }
    })();
    return () => controller.abort();
  }, [database, relatedWanted]);

  const loadValues = useCallback((key: string, search = "", more = false): Promise<FilterValuesState | undefined> => {
    const held = valuesRef.current[key];
    const pending = valuesRequests.current.get(key);
    if (held?.search === search && pending) return pending;
    if (!more && held?.search === search && held.loaded && !held.error) return Promise.resolve(held);
    if (more && (!held?.hasMore || held.pending)) return Promise.resolve(held);
    const definition = filterFields.find((candidate) => candidate.key === key) as RelatedFilterField | undefined;
    if (!definition) return Promise.resolve(undefined);
    const generation = valuesGeneration.current;
    const offset = more && held ? held.offset : 0;
    const state: FilterValuesState = { values: more && held ? held.values : [], pending: true,
      loaded: false, hasMore: more && held ? held.hasMore : false, offset, search };
    valuesRef.current = { ...valuesRef.current, [key]: state };
    setValuesState(valuesRef.current);
    const request = fetchDistinctValues(definition.related?.database ?? database,
      definition.related?.field ?? key, { offset, limit: 200, search }).then((got) => {
      if (generation !== valuesGeneration.current || valuesRef.current[key] !== state) return undefined;
      const next: FilterValuesState = got.ok ? {
        values: [...new Set([...state.values, ...got.value.values])], pending: false, loaded: true,
        hasMore: got.value.hasMore, offset: got.value.offset + got.value.limit, search,
      } : { ...state, pending: false, error: got.message };
      valuesRef.current = { ...valuesRef.current, [key]: next };
      setValuesState(valuesRef.current);
      valuesRequests.current.delete(key);
      return next;
    });
    valuesRequests.current.set(key, request);
    return request;
  }, [database, filterFields]);
  const wantValues = useCallback((key: string, search = "") => { void loadValues(key, search); }, [loadValues]);
  const moreValues = useCallback((key: string) => {
    void loadValues(key, valuesRef.current[key]?.search ?? "", true);
  }, [loadValues]);

  /** The binding names a view the fresh list does not have. Said in the panel, not after a save.
   *
   * β›” IT STOPS BEING SAID THE MOMENT THE PERSON ANSWERS IT. The sentence asks for one of two acts,
   * so it must clear when either is taken: choosing a live view fills `viewId`, and switching to
   * "A filter I build here" moves `scopeKind`. Keying it on the SAVED id alone left the panel still
   * demanding a fix after the fix had been made, which reads as a control that ignores you.
   */
  const savedViewMissing = viewsLoaded
    && Boolean(savedView.id)
    && savedView.database === database
    && scopeKind === "view"
    && !viewId
    && !views.some((v) => v.id === savedView.id);

  /** The same rule `Toolbar.tsx` computes for the grid (owner item 24): the declared list when a
   *  field has one, the values seen in the rows when it does not. `choiceVocabulary` is pure and
   *  already gated, so this is not a second definition of the rule, only a second caller of it. */
  const statusValues = useMemo(() => {
    const map: Record<string, string[]> = {};
    for (const f of filterFields) {
      if (f.type === "user") {
        map[f.key] = [...new Set([...userOptions, ...(valuesState[f.key]?.values ?? [])])];
        continue;
      }
      if (f.type === "select" || f.type === "multiselect" || f.type === "status") {
        const declared = choiceVocabulary(f, []);
        map[f.key] = declared.length ? declared : valuesState[f.key]?.values ?? [];
      } else map[f.key] = valuesState[f.key]?.values ?? [];
    }
    return map;
  }, [filterFields, valuesState, userOptions]);

  // Offer every numeric column this database can total, including Metrics created in the app.
  // `isNumericType` checks numeric behaviour and `canTotal` checks whether the database can
  // aggregate the column. Date Metrics stay excluded; the server still refuses by name if
  // these client checks ever disagree with it.
  const numericFields = useMemo(
    () => fields.filter((f) => {
      // β›” DATE METRICS ARE EXCLUDED BY TYPE, never by a mutable label or key naming convention.
      if (isMetricField(f) && (f.type === "date" || f.type === "created_time")) return false;
      return !isMetricField(f) && isNumericType(f.type) && canTotal(f);
    }),
    [fields],
  );

  // ⚠ W54-T31 - `offersMetric` MOVED, it was not dropped. The hint it gated belongs beside the
  // rows it describes, and those rows now live in `ColumnPickerDialog`, which derives the same
  // answer from the same list. A second copy here would have had no reader.

  /** The saved binding names a column this database will not total. Said in the panel, where the
   *  choice is made, rather than as a refusal after a save.
   *
   * β›” IT IS GATED ON THE FIELD LIST HAVING ARRIVED, not on emptiness. Before the workspace door
   * answers, every column is "missing" and a notice keyed on that would flash a sentence about a
   * column that is perfectly fine, which is the failure `savedViewMissing` already records.
   */
  const savedFieldUnavailable = fields.length > 0
    && fn !== "count"
    && Boolean(field)
    && !numericFields.some((f) => f.key === field);

  const stepFields = useMemo(() => fields.filter(isDragDownField), [fields]);
  const selectedView = scopeKind === "view" ? views.find((v) => v.id === viewId) : undefined;
  const driverTree: FilterTree = scopeKind === "filter" ? tree : {
    conj: selectedView?.config.filterConj ?? "and",
    nodes: selectedView?.config.filters ?? [],
  };
  const filterClauseOffers = stepFields.map((candidate) => ({
    field: candidate,
    values: valuesState[candidate.key]?.values ?? bindingStepValues(candidate, [], userOptions),
  }));
  const savedDragDriverMissing = optionsResolved && copySteps.some((step) => step.field
    && step.field !== BINDING_ENDING_STEP && step.field !== BINDING_PERIOD_STEP
    && !stepFields.some((candidate) => candidate.key === step.field));
  const chooseStepField = async (index: number, key: string) => {
    const serial = ++stepRequest.current;
    const replace = (step: BindingDragStep) => updateCopySteps(copySteps.map((held, i) => i === index ? step : held));
    if (key === BINDING_ENDING_STEP || key === BINDING_PERIOD_STEP) {
      replace({ field: key, axis: copySteps[index].axis,
        ...(key === BINDING_ENDING_STEP ? { size: endingStepDefault(windowSpec.kind) } : {}),
      });
      setLocked(false);
      return;
    }
    if (!key) { replace({ field: "", axis: copySteps[index].axis }); return; }
    const offer = filterClauseOffers.find((candidate) => candidate.field.key === key);
    if (!offer) return;
    setStepNotice("Loading values…");
    const loaded = await loadValues(key);
    if (serial !== stepRequest.current) return;
    // Reuse copy's declared choices, presence/member parsing and ordering on this one field page.
    const seedValues = loaded ? bindingStepValues(offer.field,
      loaded.values.map((value, pid) => ({ pid, [key]: value })), userOptions) : offer.values;
    const first = seedValues[0];
    setStepNotice(loaded?.error ?? (first === undefined ? "No values for this field." : ""));
    if (first === undefined || loaded?.error) return;
    setTree((current) => {
      const driver = scopeKind === "filter" ? current : driverTree;
      return bindingFilterClauses(driver).some((clause) => clause.colId === key)
        ? driver : seedBindingStep(driver, offer.field, first);
    });
    setScopeKind("filter");
    setViewId("");
    setCopySteps((current) => current.map((held, i) => i === index
      ? { field: key, axis: held.axis, mode: bindingStepMode(offer.field) } : held));
    setCopyStepsEdited(true);
  };

  /**
   * ⭐⭐ W50-T21 (owner instruction 24: *"Sheet column picker (sum/count) shows the Field icons."*)
   *
   * β›” A `<select>` CANNOT CARRY AN ICON PER OPTION, which is why this is a real listbox and not a
   * styled dropdown. An `<option>` renders as plain text in every browser; there is no markup that
   * puts an SVG inside one. So the picker adopts the DATA layer's own field list vocabulary
   * (`cg-type-search`, `cg-type-list`, `cg-type-row`, `cg-type-label`), every class of which is
   * declared at TOP LEVEL and UNSCOPED in `index.css` and therefore already applies here. Copying
   * those measures into `styles/wave50/sheet.css` would be a second definition of a shipped rule.
   *
   * β›” THE SEARCH BOX IS ALWAYS SHOWN (wave-50 R16), never gated on a field count. A control that
   * appears at eleven fields and not at ten is a control nobody learns is there, and the reader
   * who needs it most is the one whose database has just grown past the threshold.
   *
   * ⚠ THE LIST IS STILL NUMERIC ONLY. `FieldTypeIcon` takes every `FieldType`, which invites
   * listing all of them; the picker's contract is the column an aggregate can be taken OVER, and
   * widening it would let someone sum a text column and get a refusal instead of a number.
   */
  const [fieldQuery, setFieldQuery] = useState("");

  const shownFields = useMemo(() => {
    const q = fieldQuery.trim().toLowerCase();
    if (!q) return numericFields;
    return numericFields.filter((f) => (f.label ?? "").toLowerCase().includes(q)
      || String(f.key).toLowerCase().includes(q));
  }, [fieldQuery, numericFields]);

  /** The chosen column, resolved over the FULL field list rather than over the offer, so a saved
   *  column this database cannot total still shows its own name beside the notice that says so.
   *  That is the same three-state rule `customer-grid/FieldSelect.tsx` documents at its head. */
  const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]);
  const chosenIsMetric = shape === "value" && sourceKind === "number";
  const keepingAllTimeMetric = savedAllTimeMetric && chosenIsMetric
    && initial?.database === database && savedSource.kind === "number"
    && savedSource.metric_key === metricKey;
  const filterUsesMetric = usesMetric(driverTree, fields, measures);
  const showMetricPeriod = chosenIsMetric || filterUsesMetric;
  useEffect(() => {
    if (!showMetricPeriod || !periodOn || periodMode !== "window" || ending !== "cell") return;
    if (workbook) {
      // HOTFIX 2026-09-29: the tab names are already painted; no whole-workbook download for them.
      setEndingSheets(workbook.sheets.map(({ id, name }) => ({ id, name })));
      setEndingSheet((held) => held || homeTab?.name || workbook.sheets[0]?.name || "");
      return;
    }
    let cancelled = false;
    void readWorkbook(workbookId).then((got) => {
      if (cancelled) return;
      if (!got.ok) { setNotice(got.message); return; }
      setEndingSheets(got.value.sheets.map(({ id, name }) => ({ id, name })));
      setEndingSheet((held) => held || got.value.sheets[0]?.name || "");
    });
    return () => { cancelled = true; };
  }, [workbookId, showMetricPeriod, periodOn, periodMode, ending, workbook, homeTab?.name]);
  const canStepPeriod = chosenIsMetric || shape === "view";
  const periodClauseLabel = shape === "view" ? "Metric period"
    : `Metric period of ${measures.find((m) => m.key === metricKey)?.label || metricKey || "Metric"}`;
  const changeSource = (kind: BindingAggregate["kind"]) => {
    setSourceKind(kind);
    setMetricKey("");
    setField("");
    setFn("sum");
    setPeriodOn(kind === "number");
    setPreview("");
    setColPickerOpen(false);
  };
  const changeDatabase = (key: string) => {
    setDatabase(key);
    setMetricKey("");
    setField("");
    setViewId("");
    setTree({ conj: "and", nodes: [] });
    updateCopySteps([]);
    setPeriodOn(chosenIsMetric);
    setPreview("");
    setViewFields([]);
    setViewSort([]);
  };

  /** The database's own label, which the column list's heading names. Two databases can both
   *  carry a column called "Total", and the heading is where that ambiguity is answered. */
  const databaseLabel = databases.find((d) => d.key === database)?.label || database;

  const binding = useMemo(() => {
    const agg: BindingAggregate = sourceKind === "number"
      ? { kind: "number", metric_key: metricKey }
      : { kind: "column", fn: fn as "sum" | "count" | "avg" | "min" | "max",
          ...(fn !== "count" ? { field } : {}) };
    const scope: Record<string, unknown> = scopeKind === "view"
      ? { view_id: viewId, view_name: views.find((v) => v.id === viewId)?.name ?? "",
          ...(savedScope.kind === "view" && savedScope.viewId === viewId && tree.nodes.length
            ? { filter: tree } : {}) }
      : { filter: tree };
    // R11: a filter ADOPTED from a purged view keeps saying so. The sentence in the panel is the
    // only trace of where that filter came from, and re-saving the cell must not erase it.
    const adopted = (initial?.scope as Record<string, unknown> | undefined)?.adoptedFrom;
    if (scopeKind === "filter" && adopted) scope.adoptedFrom = adopted;
    const out: Record<string, unknown> = { database, aggregate: agg, scope };
    if (agg.kind === "column" && agg.field && chosenField) out.fieldType = chosenField.type;
    // W55-T07 / R6: re-saving what this cell points at must not reset how its View drawer opens.
    // The display bag belongs to this binding, not to the saved View and not to localStorage.
    const display = bindingDisplay(initial);
    if (display) out.display = display;
    // C2's period, spelled the contract's way. R14: a period SOURCE is a `$`-anchored cell
    // reference; the A1 resolver reads it BEFORE the query is built, so it is an INPUT to the
    // filter and never a post-filter. It rides ALONGSIDE the unit and the start rather than
    // replacing them, because the pair still names what the cell falls back to.
    // β›”β›” D-660 - ONLY WRITE `period` WHEN THE PERIOD SWITCH IS ON. See the state declaration
    // above: an all-time binding re-saved with the switch off must stay all-time, not get silently
    // stamped to this month's default, and turning the switch off drops the key rather than writing
    // an empty period the server would have to guess about.
    if (showMetricPeriod) {
      if (periodOn) {
        // β›” C5 - EMIT EXACTLY ONE DIALECT. `clean_period` prefers unit/start when both are present,
        // so combining these branches would silently discard the rolling window.
        if (periodMode === "window") {
          out.period = { window: windowSpec, ...(hasEnding ? {
            ending: { kind: ending, ...(ending === "fixed" ? { date: endingFixed } : {}),
              ...(ending === "n_before_today" ? { n: Number(endingN), unit: endingUnit } : {}) },
            endingStep, ...(endingOffset ? { endingOffset } : {}),
            locked: across === "none", ...(ending === "cell" ? { ref: endingRef } : {}),
          } : {}) };
        } else {
          const period: Record<string, unknown> = {
            unit, start, locked: canStepPeriod ? locked : true,
          };
          if (frozen) {
            period.frozen = true;
            period.from = frozenFrom;
            period.to = frozenTo;
          } else if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
          out.period = period;
        }
      }
    }
    // β›”β›” R8 REVOKED W51-T12'S ONE-AXIS-AT-A-TIME RULE. The wire keys keep C2's spelling
    // because `clean_on_drag` rebuilds anything else; emitting both slots independently lets one
    // Metric cell step its period and one filter clause without either choice erasing the other.
    const steps = copySteps.filter((step) => step.field && (step.field === BINDING_ENDING_STEP
      ? showMetricPeriod && periodOn && hasEnding && periodMode === "window" : step.field === BINDING_PERIOD_STEP
        ? showMetricPeriod && periodOn && canStepPeriod && !locked && periodMode === "calendar" : true));
    // An unchanged legacy editor keeps the old copy semantics on save as well as on read.
    out.onDrag = !copyStepsEdited && !Array.isArray((initial?.onDrag as BindingOnDrag | undefined)?.steps)
      ? { across: savedDrag.across, down: savedDrag.down }
      : bindingOnDrag({ onDrag: { steps } });
    if (shape === "view") {
      const viewBinding: ViewBinding = {
        database, mode: "view", viewType, fields: viewFields,
        // C2 stores the selected predicate itself, including a saved view's chosen filter.
        filter: scopeKind === "filter" ? tree : {
          conj: selectedView?.config.filterConj ?? "and",
          nodes: selectedView?.config.filters ?? [],
        },
        sort: viewSort, limit: viewLimit,
        ...(out.period ? { period: out.period as Record<string, unknown> } : {}),
        onDrag: out.onDrag as BindingOnDrag,
        ...(initial?.mode === "view" && initial.database === database && initial.block
          ? { block: initial.block as ViewBinding["block"] } : {}),
      };
      return viewBinding;
    }
    return out;
  }, [database, sourceKind, metricKey, fn, field, chosenField, scopeKind, viewId, views, tree, initial, savedScope,
      unit, start, locked, frozen, frozenFrom, frozenTo, refOpen, periodRef, periodOn, periodMode, windowSpec,
      across, copySteps, copyStepsEdited, savedDrag, chosenIsMetric, hasEnding, ending, endingFixed,
      endingN, endingUnit, endingStep, endingOffset, endingRef,
      shape, viewType, viewFields, viewSort, viewLimit, selectedView, canStepPeriod, showMetricPeriod]);

  // Read before either send; the server reads the stored source again independently.
  const prepareBinding = async (): Promise<Record<string, unknown> | null> => {
    let value = endingFixed;
    let prepared = binding;
    try {
      const filterRefs = bindingRefSlots(binding).filter((slot) => slot.kind === "filter");
      if (filterRefs.length) {
        const scope = binding.scope as { filter: FilterTree };
        let previewTree = scope.filter;
        const source = workbook ?? await (async () => {
          const got = await readWorkbook(workbookId);
          if (!got.ok) throw new Error(got.message);
          return got.value;
        })();
        for (const slot of filterRefs) {
          const read = readCell && (workbook || slot.text.startsWith("=")) ? readCell(slot.text) : null;
          if (read?.problem) throw new Error(read.problem);
          const operand = read ? read.value : resolveFilterCell(source, slot.text, homeTab?.name);
          previewTree = updateFilterValueLeaf(previewTree, slot.indices!, (node) => ({ ...node,
            value: operand, ...((MULTI_VALUE_OPS as ReadonlySet<string>).has(node.op) ? { values: [operand] } : {}),
          }));
        }
        prepared = { ...binding, scope: { ...scope, filter: previewTree } };
      }
      if (!showMetricPeriod || !periodOn || periodMode !== "window" || !hasEnding) return prepared;
      if (ending === "n_before_today") {
        if (!endingN.trim() || !Number.isInteger(Number(endingN)) || Number(endingN) < 1)
          throw new Error("Ending needs a number of 1 or more before today.");
        if (Number(endingN) > MAX_N)
          throw new Error(`Ending cannot be more than ${MAX_N} before today.`);
      }
      if (ending === "cell") {
        const source = workbook ?? await (async () => {
          const got = await readWorkbook(workbookId);
          if (!got.ok) throw new Error(got.message);
          return got.value;
        })();
        value = resolveEndingCell(source, endingRef, homeTab?.name);
      }
      const today = new Date();
      const day = `${today.getFullYear()}-${pad2(today.getMonth() + 1)}-${pad2(today.getDate())}`;
      if (!endingBounds(windowSpec.kind, ending, value, day, endingStep, endingOffset, Number(endingN), endingUnit))
        throw new Error("Ending cannot be used because its date is invalid or falls before the lookback starts. Choose a later ending date.");
      return ending === "cell" ? { ...prepared, period: {
        ...(binding.period as Record<string, unknown>), ending: { kind: "cell", date: value },
      } } : prepared;
    } catch (error) {
      setNotice(error instanceof Error ? error.message : "The Ending date could not be read. Choose a valid date.");
      return null;
    }
  };

  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
  // which is what lets someone see whether they picked the right thing while they can still change
  // their mind - and it is the same door the cell will use, so the number cannot differ.
  const runPreview = async () => {
    setNotice("");
    setPreview("");
    const prepared = await prepareBinding();
    if (!prepared) return;
    const got = await previewCell(workbookId, addr, prepared, homeTab?.id);
    if (!got.ok) {
      setNotice(got.message);
      return;
    }
    setPreview(got.value.display || String(got.value.value ?? ""));
  };

  // Preview and Save wait for the field list even while the editor body is already visible.
  // A cell bound to a live view satisfies every other clause the moment the panel mounts, and a
  // Save taken then would write back a binding assembled from a list nobody had seen yet.
  // The rail and Save share these terms; new Metrics require a period, while an unchanged
  // saved all-time Metric keeps its absent period. Source and reference checks still apply.
  const sourceComplete = databases.some((d) => d.key === database)
    && (shape === "view" ? viewFields.length > 0
      && viewFields.every((key) => fields.some((candidate) => candidate.key === key))
      && Number.isInteger(viewLimit) && viewLimit >= 1 && viewLimit <= VIEW_BINDING_LIMIT_MAX
      : chosenIsMetric ? Boolean(metricKey) && measures.some((m) => m.key === metricKey)
        : fn === "count" || numericFields.some((candidate) => candidate.key === field));
  const filterComplete = scopeKind === "filter" || Boolean(viewId);
  const frozenRangeComplete = !frozen || Boolean(range.from && range.to && range.from <= range.to);
  const periodComplete = (!chosenIsMetric || periodOn || keepingAllTimeMetric)
    && (!showMetricPeriod || !periodOn || periodMode !== "calendar" || frozenRangeComplete);
  const dataComplete = sourceComplete && (!chosenIsMetric || periodComplete);
  const copiedComplete = !savedDragDriverMissing;
  const relatedPending = relatedOffer.database !== database || !relatedOffer.loaded;
  const relatedKeys = bindingFilterClauses(tree).flatMap((leaf) => [leaf.colId,
    ...(leaf.rhs && "colId" in leaf.rhs ? [leaf.rhs.colId] : [])]).filter((key) =>
    key.startsWith("linked:") || key.startsWith("related:"));
  // The server validates this saved predicate again on Save. Pending discovery does not
  // require an unchanged predicate to be reconstructed from an offer it already names.
  const savedRelatedUnchanged = initial?.database === database && scopeKind === savedScope.kind
    && JSON.stringify(tree) === JSON.stringify(savedScope.tree) && !relatedNotice;
  const aliasesPending = relatedKeys.length > 0 && relatedPending && !savedRelatedUnchanged;
  const relatedUnavailable = !relatedPending && relatedKeys.some((key) =>
    !relatedOffer.fields.some((offer) => offer.key === key));
  const ready = optionsResolved && viewsLoaded && !aliasesPending && !relatedUnavailable
    && dataComplete && filterComplete && periodComplete && copiedComplete
    && (shape === "value" || activeSection === "place");

  const sectionComplete = {
    data: dataComplete, rows: filterComplete && periodComplete, copied: copiedComplete,
    place: ready,
  };
  const sectionGates = BINDING_SECTIONS.filter(({ key }) => shape === "view" || key !== "place")
    .map((section, index, sections) => {
      const blocker = sections.slice(0, index).find(({ key }) => !sectionComplete[key]);
      return {
        ...section,
        reachable: !blocker,
        // The body paints before the field list (S68-T24), so until it answers a saved source reads
        // as incomplete: say Loading rather than tell the reader to pick what they already picked.
        blockedHint: !optionsResolved ? "Loading"
          : blocker?.key === "data" ? (sourceComplete ? "Set a Metric period" : "Pick a source")
          : blocker?.key === "rows" ? (filterComplete ? "Set a Metric period" : "Pick rows")
            : blocker?.key === "copied" ? "Choose a step field" : undefined,
      };
    });
  const lastReachableIndex = sectionGates.reduce(
    (last, section, index) => section.reachable ? index : last, 0,
  );

  // Hotfix 2026-09-24 (owner): the per-step Next buttons are gone, and R44's "one shared Next"
  // with them. The step rail on the left is the one way between steps; it already refuses a step
  // that is not reachable yet and names what blocks it.
  useEffect(() => {
    setActiveSection((current) => {
      const currentIndex = BINDING_SECTIONS.findIndex(({ key }) => key === current);
      // Re-check the current selection so a backward click cannot be advanced by this effect.
      return currentIndex > lastReachableIndex ? BINDING_SECTIONS[lastReachableIndex].key : current;
    });
  }, [activeSection, lastReachableIndex]);

  const { y: startYear, m: startMonth } = splitYm(start);
  const thisYear = new Date().getFullYear();
  const years: number[] = [];
  for (let y = thisYear - 6; y <= thisYear + 1; y += 1) years.push(y);
  if (!years.includes(startYear)) years.push(startYear);
  years.sort((a, b) => a - b);

  // The filter conditions that read a cell. The cell is chosen inside the filter itself ("a cell");
  // When copied lists them because whether that reference moves is how this cell copies.
  const cellLeaves = filterValueLeaves(tree).flatMap(({ node, indices }, index) =>
    FILTER_REF_KEYS.flatMap((refKey) => node[refKey]?.ref
      ? [{ node, indices, index, refKey, ref: node[refKey]!.ref, locked: node[refKey]!.locked === true,
           title: filterFields.find((candidate) => candidate.key === node.colId)?.label || node.colId }] : []));
  // Every cell this panel names is outlined on the grid while the panel is open (refHighlight.ts).
  useCellRefHighlight([
    ...cellLeaves.map(({ ref }) => ref),
    showMetricPeriod && periodOn && (refOpen || ending === "cell") && periodRef
      ? (!parsedEndingRef?.sheet && ending === "cell" && endingSheet
        ? `'${endingSheet.replace(/'/g, "")}'!${periodRef.trim()}` : periodRef) : "",
  ]);

  // ⚠ W53-T16 - THESE NO LONGER RAISE A TOUCH FLAG, and that is the point of the switch: every
  // period control below is rendered only while `periodOn`, so reaching one of them is already the
  // decision the flag used to have to infer.
  const setYear = (y: number) => {
    resumeRollingPeriod();
    setStart(normalizePeriodStart(unit, joinYm(y, startMonth)));
  };
  const setMonthOfYear = (m: number) => {
    resumeRollingPeriod();
    setStart(normalizePeriodStart(unit, joinYm(startYear, m)));
  };

  const metricPeriodControls = (
    <fieldset className="sheet-scope sheet-period">
      <legend>Metric period</legend>

      {(!chosenIsMetric || (keepingAllTimeMetric && !periodOn)) && <div className="sheet-period-lock">
        <button type="button" role="switch" aria-checked={periodOn}
          className={"sheet-lock-toggle" + (periodOn ? " is-on" : "")}
          onClick={() => setPeriodOn((v) => !v)}>
          <span className="sheet-lock-dot" aria-hidden />
          <span>Use a Metric period</span>
        </button>
      </div>}

      {periodOn && (
        <>
          {/* ⭐ C5 - THE MODE LABELS SAY WHAT EACH CHOICE DOES. Internal dialect names
              would make the reader guess which one can step and which one follows today. */}
          <label className="sheet-field">
            <span>How to choose the period</span>
            <select
              value={periodMode}
              aria-label="How this period is chosen"
              onChange={(e) => setPeriodMode(e.target.value as "calendar" | "window")}
            >
              <option value="calendar">Calendar period</option>
              <option value="window">Lookback</option>
            </select>
          </label>

          {periodMode === "window" ? (
            <>
            <label className="sheet-field">
              <span>Lookback</span>
              <WindowPicker window={windowSpec} kinds={WINDOW_KINDS} onWindow={(next) => {
                setWindowSpec(next); setEndingStep(endingStepDefault(next.kind));
                setEndingOffset(0);
              }} />
            </label>
            {hasEnding && <>
              <label className="sheet-field">
                <span>Ending</span>
                <select aria-label="Ending" value={ending} onChange={(e) => {
                  setEnding(e.target.value as EndingKind); setEndingOffset(0);
                }}>
                  {ENDING_KINDS.map((kind) => <option key={kind} value={kind}>{ENDING_LABELS[kind]}</option>)}
                </select>
              </label>
              {ending === "n_before_today" && <>
                <label className="sheet-field">
                  <span>Number</span>
                  <input type="number" min={1} max={MAX_N} aria-label="Ending number" value={endingN}
                    onChange={(e) => { setEndingN(e.target.value); setEndingOffset(0); }} />
                </label>
                <label className="sheet-field">
                  <span>Unit</span>
                  <select aria-label="Ending unit" value={endingUnit}
                    onChange={(e) => { setEndingUnit(e.target.value as EndingStep); setEndingOffset(0); }}>
                    {ENDING_STEPS.map((size) => <option key={size} value={size}>
                      {size[0].toUpperCase() + size.slice(1) + "s"}
                    </option>)}
                  </select>
                </label>
                {relativeEndingBounds && <p className="sheet-period-note">
                  {dayText(relativeEndingBounds[0])} through {dayText(relativeEndingBounds[1])}
                </p>}
              </>}
              {ending === "fixed" && <label className="sheet-field">
                <span>Ending date</span>
                <input type="date" aria-label="Ending date" value={endingFixed}
                  onChange={(e) => { setEndingFixed(e.target.value); setEndingOffset(0); }} />
              </label>}
              {ending === "cell" && <>
              {!parsedEndingRef?.sheet && <label className="sheet-field">
                <span>Source sheet</span>
                <select aria-label="Ending source sheet" value={endingSheet}
                  disabled={!endingSheets.length} onChange={(e) => setEndingSheet(e.target.value)}>
                  {!endingSheets.length && <option value="">Loading sheets…</option>}
                  {endingSheets.map((sheet) => <option key={sheet.id} value={sheet.name}>{sheet.name}</option>)}
                </select>
              </label>}
              <label className="sheet-field">
                <span>Date cell</span>
                <input type="text" aria-label="Ending date cell" value={periodRef}
                  placeholder="A1" onChange={(e) => { setPeriodRef(e.target.value); setEndingOffset(0); }} />
              </label>
              </>}
              {endingOffset > 0 && <p className="sheet-period-note">
                {`Ending moved later by ${endingOffset} ${endingStep}${endingOffset === 1 ? "" : "s"} when copied.`}
              </p>}
            </>}
            </>
          ) : (
            <>
              <label className="sheet-field">
                <span>Unit</span>
                <select
                  value={unit}
                  aria-label="Period unit"
                  onChange={(e) => {
                    const next = e.target.value as PeriodUnit;
                    resumeRollingPeriod();
                    setUnit(next);
                    // Re-seat the start on the new unit's first month, or the pair stops naming one
                    // period: `2026-08` under `quarter` is not a quarter anybody can compile.
                    setStart(normalizePeriodStart(next, start));
                  }}
                >
                  {PERIOD_UNIT_OPTIONS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)}
                </select>
              </label>

              {unit === "day" || unit === "week" ? (
                <label className="sheet-field">
                  <span>{unit === "week" ? "Week starting" : "Day"}</span>
                  <input type="date" aria-label="Calendar period date" value={start}
                    onChange={(e) => {
                      resumeRollingPeriod();
                      setStart(normalizePeriodStart(unit, e.target.value));
                    }} />
                </label>
              ) : <div className="sheet-field-row">
                <label className="sheet-field">
                  <span>Year</span>
                  <select
                    value={String(startYear)}
                    aria-label="Period year"
                    onChange={(e) => setYear(Number(e.target.value))}
                  >
                    {years.map((y) => <option key={y} value={String(y)}>{y}</option>)}
                  </select>
                </label>
                {unit === "month" && (
                  <label className="sheet-field">
                    <span>Month</span>
                    <select
                      value={String(startMonth)}
                      aria-label="Period month"
                      onChange={(e) => setMonthOfYear(Number(e.target.value))}
                    >
                      {MONTH_NAMES.map((name, i) => (
                        <option key={name} value={String(i + 1)}>{name}</option>
                      ))}
                    </select>
                  </label>
                )}
                {unit === "quarter" && (
                  <label className="sheet-field">
                    <span>Quarter</span>
                    <select
                      value={String(Math.floor((startMonth - 1) / 3) + 1)}
                      aria-label="Period quarter"
                      onChange={(e) => setMonthOfYear(1 + 3 * (Number(e.target.value) - 1))}
                    >
                      {[1, 2, 3, 4].map((q) => <option key={q} value={String(q)}>{`Q${q}`}</option>)}
                    </select>
                  </label>
                )}
              </div>}

              <div className="sheet-field-row sheet-period-dates">
                <label className="sheet-field">
                  <span>Starts</span>
                  <input
                    className="cg-input cg-cond-win-date"
                    type="date"
                    aria-label="Period start"
                    value={range.from}
                    onChange={(e) => editPeriodDate("from", e.target.value)}
                  />
                </label>
                <label className="sheet-field">
                  <span>Ends</span>
                  <input
                    className="cg-input cg-cond-win-date"
                    type="date"
                    aria-label="Period end"
                    value={range.to}
                    onChange={(e) => editPeriodDate("to", e.target.value)}
                  />
                </label>
              </div>
              <p className="sheet-period-note" aria-live="polite">
                {dayText(range.from)} to {dayText(range.to)}
              </p>
              {frozen && (
                <>
                  <p className="sheet-period-note">Frozen to these dates until you choose a period.</p>
                  <button
                    type="button"
                    className="sheet-period-link"
                    onClick={resumeRollingPeriod}
                  >
                    Return to rolling period
                  </button>
                </>
              )}

              {/* W56-T21 (owner instruction 13) - THE QUICK PICKS ARE GONE. Unit, year and
                  month-or-quarter already reach every period the This and Last buttons
                  could, so a second control for the same value was a second way to say one
                  thing. `normalizePeriodStart` still normalises all three selects, and
                  `shiftPeriodStart` comes from the shared drag arithmetic. */}

              {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
                  sentence under it says what each one costs when the cell is copied. */}
              {canStepPeriod ? (
                <div className="sheet-period-lock">
                  <button
                    type="button"
                    role="switch"
                    aria-checked={locked}
                    className={"sheet-lock-toggle" + (locked ? " is-on" : "")}
                    onClick={() => {
                      const next = !locked;
                      setLocked(next);
                      setAcross(next ? "none" : "period");
                    }}
                  >
                    <span className="sheet-lock-dot" aria-hidden />
                    <span>Lock this period</span>
                  </button>
                  <p className="sheet-period-note">
                    {locked
                      ? "Locked, so any copy of this cell keeps this period."
                      : `Not locked, so a stepped copy moves by one ${UNIT_NOUN[unit]} per cell. `
                        + "Right and down move forward. Left and up move backward."}
                  </p>
                </div>
              ) : (
                <p className="sheet-period-note">
                  This Metric period stays fixed when copied.
                </p>
              )}

              {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the
                  picker, so the ordinary reader never meets a cell reference and the person who wants
                  one is one click away from it. */}
              {!refOpen && (
                <button
                  type="button"
                  className="sheet-period-link"
                  onClick={() => {
                    // A cell SUPPLIES the period, so it cannot also be frozen to two
                    // literal dates. Returning to rolling here is the same rule the
                    // unit, year and month pickers follow, and it keeps the payload's
                    // `frozen`-wins branch from silently dropping a typed reference.
                    resumeRollingPeriod();
                    setRefOpen(true);
                  }}
                >
                  Use a cell
                </button>
              )}
              {refOpen && (
                <label className="sheet-field">
                  <span>Period from a cell</span>
                  <input
                    type="text"
                    value={periodRef}
                    onChange={(e) => setPeriodRef(e.target.value)}
                    placeholder="$B$1"
                  />
                </label>
              )}
            </>
          )}
        </>
      )}
    </fieldset>
  );


  return (
    <section
      className="sheet-binding-panel"
      ref={panelRef}
      aria-label={`Insert database in ${addr}`}
    >
      <header className="sheet-binding-head">
        <h2 className="sheet-binding-title">{`Insert database in ${addr}`}</h2>
        <button
          type="button"
          className="sheet-binding-close"
          onClick={onCancel}
          aria-label={`Close database navigation for ${addr}`}
          title="Close"
        >
          <svg viewBox="0 0 16 16" aria-hidden="true" width="13" height="13" fill="none">
            <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.4"
                  strokeLinecap="round" />
          </svg>
        </button>
      </header>

      {/* β›” THE SCROLLER IS THIS WRAPPER, NOT THE PANEL. A 380px column holding the whole filter
          builder is taller than the page, and a panel that scrolls as a whole pushes Save below
          the fold with nothing on screen saying it is there. */}
      <div className="sheet-binding-scroll">
        {/* S68-T24: keep saved settings and navigation mounted while field controls fill in. */}
          <>
            <div className="sheet-binding-body">
              <nav className="sheet-binding-rail" aria-label="Cell database sections">
                {sectionGates.map(({ key, label, icon, reachable, blockedHint }) => (
                  <button
                    key={key}
                    type="button"
                    className={"sheet-binding-rail-item" + (activeSection === key ? " is-active" : "")}
                    aria-current={activeSection === key ? "page" : undefined}
                    disabled={!reachable}
                    title={blockedHint}
                    onClick={() => setActiveSection(key)}
                  >
                    <span className="sheet-binding-rail-icon">{icon}</span>
                    <span className="sheet-binding-rail-label">{label}</span>
                    <span className="sheet-binding-rail-hint" style={{ minHeight: "2lh" }}
                      aria-hidden={reachable}>{reachable ? "" : blockedHint}</span>
                  </button>
                ))}
              </nav>
              <div className="sheet-binding-section" data-section={activeSection}>
                {activeSection === "data" && (
                  <>
                    <fieldset className="sheet-source-path">
                      <legend>Result</legend>
                      <label className="sheet-radio">
                        <input type="radio" name="sheet-binding-shape" checked={shape === "value"}
                          onChange={() => { setShape("value"); setPreview(""); setNotice(""); }} />
                        <span>One value</span>
                      </label>
                      <label className="sheet-radio">
                        <input type="radio" name="sheet-binding-shape" checked={shape === "view"}
                          onChange={() => { setShape("view"); setPreview(""); setNotice(""); }} />
                        <span>A view</span>
                      </label>
                    </fieldset>
                    <label className="sheet-field">
                      <span>Database</span>
                      <select value={database} onChange={(e) => changeDatabase(e.target.value)}>
                        {databases.map((d) => <option key={d.key} value={d.key}>{d.label}</option>)}
                      </select>
                    </label>

                    {shape === "value" ? <>
                    <fieldset className="sheet-source-path">
                      <legend>Source</legend>
                      <label className="sheet-radio">
                        <input type="radio" name="sheet-binding-source" checked={sourceKind === "number"}
                               onChange={() => changeSource("number")} />
                        <span>Metric</span>
                      </label>
                      <label className="sheet-radio">
                        <input type="radio" name="sheet-binding-source" checked={sourceKind === "column"}
                               onChange={() => changeSource("column")} />
                        <span>Field</span>
                      </label>
                    </fieldset>
                    <div className="sheet-field-row">
                      {sourceKind === "number" ? (
                        <div className="sheet-field sheet-field--pick">
                          <span>Metric</span>
                          {!optionsResolved ? <BindingSkeleton addr={addr} /> : <FieldSelectButton
                            ariaLabel="Metric to summarise"
                            placeholder="Choose a Metric…"
                            value={metricKey}
                            onChange={(key) => {
                              setMetricKey(key); setField("");
                              if (key !== metricKey) setValuePeriodOn(true);
                            }}
                            fields={measures.filter((m) => isNumericType(m.type)).map((m) => ({
                              key: m.key, label: m.label, type: "measure" as const,
                            }))}
                          />}
                          {chosenIsMetric && metricPeriodControls}
                          <p className="sheet-notice" style={{ minHeight: "2lh" }}>{!optionsResolved ? "" : measures.length === 0
                            ? "No Metrics are available here. Choose another database."
                            : "Binding adds a Metric column to this database if one is not already there."}</p>
                        </div>
                      ) : (
                        <label className="sheet-field">
                          <span>Aggregate</span>
                          <select value={fn} onChange={(e) => {
                            setFn(e.target.value);
                            if (e.target.value === "count") setField("");
                          }}>
                            {AGGREGATES.map((a) => <option key={a.fn} value={a.fn}>{a.label}</option>)}
                          </select>
                        </label>
                      )}
                      {/* Count takes no column, and offering one would suggest count(column), which skips
                          blanks and answers a smaller number than the person meant. */}
                      {sourceKind === "column" && fn !== "count" && (
                        <div className="sheet-field sheet-field--pick">
                          <span id="sheet-col-pick-label">Column</span>
                          {/* ⭐⭐ W54-T31 (R8) β€” THE CONTROL SHOWS WHAT IS CHOSEN AND OPENS THE LIST; IT IS
                              NOT THE LIST. `cg-select cg-fsel` is the shipped footprint every replaced
                              `<select>` in this product already wears, so the Column line shares its height
                              and its baseline with the Aggregate select above it rather than introducing a
                              new control shape. The three states are `FieldSelect`'s own: unset reads as a
                              prompt, a resolved column shows its mark and its name, and a column this
                              database cannot offer shows its raw key in the amber `is-missing` slot instead
                              of a plausible substitute. */}
                          {!optionsResolved ? <BindingSkeleton addr={addr} /> : <button
                            type="button"
                            className={"cg-select cg-fsel sheet-col-open"
                              + (chosenField ? "" : field ? " is-missing" : " is-empty")}
                            aria-haspopup="dialog"
                            aria-expanded={colPickerOpen}
                            aria-labelledby="sheet-col-pick-label"
                            title={chosenField ? chosenField.key : undefined}
                            onClick={() => setColPickerOpen(true)}
                          >
                            {chosenField ? (
                              <FieldTypeIcon
                                type={isMetricField(chosenField) ? "measure" : chosenField.type}
                                title={isMetricField(chosenField) ? "Metric" : chosenField.type}
                              />
                            ) : (
                              // No mark, but the SLOT stays, so the name sits in the same column whether or
                              // not anything is chosen yet.
                              <span className="cg-fsel-nomark" aria-hidden />
                            )}
                            <span className="cg-fsel-label">
                              {chosenField?.label ?? (field || "Choose a column")}
                            </span>
                            <svg className="cg-fsel-caret" width="10" height="10" viewBox="0 0 16 16"
                                 fill="none" aria-hidden>
                              <path d="M4 6l4 4 4-4" stroke="currentColor" strokeWidth="1.6"
                                    strokeLinecap="round" strokeLinejoin="round" />
                            </svg>
                          </button>}
                          {/* β›”β›” MOUNTED ONLY WHILE OPEN, which is what orders Escape. See the block above
                              `ColumnPickerDialog`: the editor's own Escape claim was pushed at mount, this
                              one is pushed on open, and unmounting hands the key straight back. */}
                          {colPickerOpen && (
                            <SheetColumnPicker
                              addr={addr}
                              aggregateNoun={AGGREGATE_NOUN[fn] ?? "total"}
                              databaseLabel={databaseLabel}
                              shown={shownFields}
                              offered={numericFields}
                              all={fields}
                              chosen={field}
                              query={fieldQuery}
                              onQuery={setFieldQuery}
                              onPick={(key) => {
                                setField(key);
                                setMetricKey("");
                                setColPickerOpen(false);
                              }}
                              onClose={() => setColPickerOpen(false)}
                            />
                          )}
                          {/* ⭐⭐ THE BIND TIME REFUSAL, SURFACED WHERE THE PERSON CAN ACT ON IT. The server
                              refuses this column by name (`field_not_aggregable`), but only once a number is
                              asked for; saying it here means the choice is corrected before a save. */}
                          {savedFieldUnavailable && (
                            <p className="sheet-notice" role="alert">
                              {chosenField && isMetricField(chosenField) && !isNumericType(chosenField.type)
                                ? `The saved Metric column ${chosenField.label || field} has no numeric type. Choose Metric as the source.`
                                : `The saved column ${chosenField?.label || field} cannot be totalled on this database. `
                                  + "Pick a column from the list, or count the records instead."}
                            </p>
                          )}
                        </div>
                      )}
                    </div>
                    </> : <>
                      <label className="sheet-field">
                        <span>View type</span>
                        <select aria-label="View type" value={viewType}
                          onChange={(e) => setViewType(e.target.value as ViewBinding["viewType"])}>
                          {VIEW_BINDING_TYPES.map((type) => <option key={type} value={type}>
                            {type[0].toUpperCase() + type.slice(1)}
                          </option>)}
                        </select>
                      </label>
                      <label className="sheet-field">
                        <span>Fields to show</span>
                        <select multiple required disabled={!optionsResolved} aria-label="Fields to show" value={viewFields}
                          onChange={(e) => setViewFields(Array.from(e.target.selectedOptions, (option) => option.value))}>
                          {fields.map((candidate) => <option key={candidate.key} value={candidate.key}>
                            {candidate.label}
                          </option>)}
                        </select>
                      </label>
                      {!viewFields.length && <p className="sheet-period-note">Choose at least one field.</p>}
                      <label className="sheet-field">
                        <span>Row limit</span>
                        <input type="number" aria-label="Row limit" min={1} max={VIEW_BINDING_LIMIT_MAX}
                          step={1} value={viewLimit}
                          onChange={(e) => setViewLimit(clampViewLimit(e.target.valueAsNumber))} />
                      </label>
                    </>}
                  </>
                )}
                {activeSection === "rows" && (
                  <>
                    <fieldset className="sheet-scope">
                      <legend>Rows to include</legend>
                      <label className="sheet-radio">
                        <input type="radio" checked={scopeKind === "view"}
                               onChange={() => setScopeKind("view")} />
                        <span>A saved view</span>
                      </label>
                      {scopeKind === "view" && (
                        <select disabled={!optionsResolved} value={viewId} onChange={(e) => setViewId(e.target.value)}>
                          <option value="">Choose a view</option>
                          {views.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
                        </select>
                      )}
                      {/* ⭐ W53-T12 β€” SAID HERE, THE MOMENT THE LIST RESOLVES, rather than as a refusal after
                          a save or a refresh. `sheet-notice` with `role="alert"` is this panel's established
                          inline shape, so the sentence lands where the choice is made. */}
                      {savedViewMissing && (
                        <p className="sheet-notice" role="alert">
                          {`The saved view ${savedView.name || savedView.id} is not available any more. `
                            + "Pick a view that still exists, or build a filter here."}
                        </p>
                      )}
                      <label className="sheet-radio">
                        <input type="radio" checked={scopeKind === "filter"}
                               onChange={() => setScopeKind("filter")} />
                        <span>A filter I build here</span>
                      </label>
                      {/* ⭐⭐ W53-T15 (ruling R8) β€” A DOOR, NOT THE BUILDER. The same shared panel now opens
                          in a centred dialog: this column is `flex: 0 0 380px` and a condition row cannot fit
                          in it, so four conditions could only be reached by scrolling sideways. The button
                          says how many conditions the cell already carries, because the builder that used to
                          say so is now behind it. */}
                      {scopeKind === "filter" && (
                        <>
                          <button
                            type="button"
                            className="sheet-action"
                            style={{ alignSelf: "flex-start" }}
                            aria-haspopup="dialog"
                            aria-expanded={filterPopupOpen}
                            disabled={!optionsResolved}
                            onClick={() => setFilterPopupOpen(true)}
                          >
                            {conditionCount === 0
                              ? "Build a filter"
                              : `Edit filter (${conditionCount === 1
                                  ? "1 condition" : `${conditionCount} conditions`})`}
                          </button>
                          {/* β›”β›” MOUNTED ONLY WHILE OPEN, and that is what orders Escape correctly rather
                              than a flag inside the dialog. `useOverlayLayer` claims Escape as soon as it
                              runs and `ui/useEscapeClose` gives the key to the LAST entry pushed, so a
                              dialog mounted with the panel would have claimed Escape from the moment this
                              editor opened. Mounting it here, later in time, puts it ABOVE this panel's own
                              claim (pushed at mount, a few hundred lines up) and unmounting it hands Escape
                              straight back, so one press closes the filter and the next closes the panel. */}
                          {filterPopupOpen && (
                            <FilterFieldStatusContext.Provider value={{ relatedPending,
                              unavailable: relatedOffer.database === database ? relatedOffer.unavailable : [],
                              wantValues, moreValues, valuesState }}>
                              <SheetFilterPopup
                                addr={addr}
                                database={database}
                                fields={filterFields}
                                filters={showCellFilterValues(tree, readCell)}
                                onChange={(next) => setTree(keepCellFilterValues(next, readCell))}
                                statusValues={statusValues}
                                readCell={readCell}
                                onClose={() => setFilterPopupOpen(false)}
                              />
                            </FilterFieldStatusContext.Provider>
                          )}
                        </>
                      )}
                      {relatedOffer.database === database && relatedOffer.loaded && relatedOffer.databases.length === 0
                        && relatedOffer.unavailable.length === 0 &&
                        <p className="sheet-period-note" role="status">{databaseLabel} has no related database to filter by.</p>}
                      {relatedNotice && <p className="sheet-notice" role="alert">{relatedNotice}</p>}
                      {aliasesPending && !relatedNotice &&
                        <p className="sheet-period-note" role="status">Loading related fields…</p>}
                    </fieldset>
                    {!chosenIsMetric && showMetricPeriod && metricPeriodControls}
                  </>
                )}
                {activeSection === "copied" && (
                  <>
                    {/* ══ R10: THE DRAG RULES ═════════════════════════════════════════════════════════════ */}
                    <fieldset className="sheet-scope sheet-drag">
                      <legend>When copied</legend>

                      {/* Hotfix 2026-09-24 (owner: "the whole Filter section is so confusing, if we need
                          it for copy, it should always just fall under the When copied section"). A
                          condition that reads a cell is how this cell moves when copied, so the cell
                          lives here, as ONE input: filled means "read this cell", blank means the
                          value typed in the filter. There is no separate source switch. */}
                      {cellLeaves.map(({ node, indices, title, refKey, ref, locked }) => (
                        <div key={`${indices.join(".")}.${refKey}`} className="sheet-step-driver">
                          <span>{node.op === "within"
                            ? `${title}: ${windowLabel(node.dateWindow).toLowerCase()} up to the date in cell ${ref}`
                            : node.op === "between"
                              ? `${title} ${refKey === "valueRef" ? "from" : "to"} cell ${ref}`
                              : `${title} reads cell ${ref}`}</span>
                          <label className="sheet-radio">
                            <input type="checkbox" checked={locked}
                              onChange={(e) => setTree(updateFilterValueLeaf(tree, indices, (leaf) => ({ ...leaf,
                                [refKey]: { ...leaf[refKey]!, locked: e.target.checked } })))} />
                            <span>Keep this cell when copied</span>
                          </label>
                        </div>
                      ))}

                      {copySteps.map((step, index) => {
                        const isEnding = step.field === BINDING_ENDING_STEP;
                        const isPeriod = step.field === BINDING_PERIOD_STEP;
                        const driverField = fields.find((candidate) => candidate.key === step.field);
                        const localDriver = bindingFilterClauses(tree).find((clause) => clause.colId === step.field);
                        const driverValue = localDriver?.op === "isEmpty" ? "Empty"
                          : localDriver?.op === "isNotEmpty" ? "Filled"
                            : localDriver?.value || localDriver?.values?.[0] || "";
                        const missing = step.field && !isEnding && !isPeriod && optionsResolved && !driverField;
                        return <div key={index} className="sheet-step-driver">
                          <div className="sheet-field sheet-field--pick">
                            <span>Step field</span>
                            <FieldSelectButton
                              ariaLabel={index ? `Step field ${index + 1} when copied` : "Step field when copied"}
                              placeholder="Choose a step field"
                              value={step.field}
                              onChange={(key) => { void chooseStepField(index, key); }}
                              searchable
                              searchPlaceholder="Find a step field…"
                              emptyMessage="No step fields available."
                              fields={[
                                ...(showMetricPeriod && periodOn && hasEnding && periodMode === "window" ? [{
                                  key: BINDING_ENDING_STEP, label: "Ending",
                                  disabled: copySteps.some((held, i) => i !== index && held.field === BINDING_ENDING_STEP),
                                }] : []),
                                ...(showMetricPeriod && canStepPeriod && periodOn && periodMode === "calendar" ? [{
                                  key: BINDING_PERIOD_STEP, label: periodClauseLabel,
                                  disabled: copySteps.some((held, i) => i !== index && held.field === BINDING_PERIOD_STEP),
                                }] : []),
                                ...filterClauseOffers.map(({ field: candidate }) => ({
                                  key: candidate.key, label: `Step ${candidate.label}`, type: candidate.type,
                                  disabled: !optionsResolved
                                    || copySteps.some((held, i) => i !== index && held.field === candidate.key),
                                })),
                                ...(missing ? [{ key: step.field, label: `${step.field} (unavailable)`, disabled: true }] : []),
                              ]}
                            />
                          </div>
                          <label className="sheet-field">
                            <span>Direction</span>
                            <select aria-label={`Step ${index + 1} direction`} value={step.axis}
                              onChange={(e) => updateCopySteps(copySteps.map((held, i) => i === index
                                ? { ...held, axis: e.target.value as BindingDragStep["axis"] } : held))}>
                              <option value="across">Across</option>
                              <option value="down">Down</option>
                            </select>
                          </label>
                          {isEnding && <label className="sheet-field">
                            <span>Ending step size</span>
                            <select aria-label="Ending step size" value={step.size ?? endingStepDefault(windowSpec.kind)}
                              onChange={(e) => updateCopySteps(copySteps.map((held, i) => i === index
                                ? { ...held, size: e.target.value as EndingStep } : held))}>
                              {ENDING_STEPS.map((size) => <option key={size} value={size}>
                                {size[0].toUpperCase() + size.slice(1)}
                              </option>)}
                            </select>
                          </label>}
                          {localDriver && driverField && <span>{`${driverField.label}: ${driverValue}`}</span>}
                          <button type="button" className="lp-btn lp-btn-quiet"
                            aria-label={`Remove step field ${index + 1}`}
                            onClick={() => updateCopySteps(copySteps.filter((_, i) => i !== index))}>
                            <MenuIcon name="trash" />
                            Remove step field
                          </button>
                        </div>;
                      })}
                      <button type="button" className="lp-btn lp-btn-quiet"
                        disabled={copySteps.some((step) => !step.field)}
                        onClick={() => updateCopySteps([...copySteps, { field: "", axis: "across" }])}>
                        <MenuIcon name="addEnd" />
                        Add step field
                      </button>
                      <p className="sheet-period-note" role="status" style={{ minHeight: "1lh" }}>{stepNotice}</p>
                      {savedDragDriverMissing && <p className="sheet-notice" role="alert">The saved Step field is unavailable. Choose another field.</p>}
                    </fieldset>
                  </>
                )}
                {shape === "view" && activeSection === "place" && (
                  <>
                    {ready && <DrillModal workbookId={workbookId} addr={addr} label="Place"
                      previewBinding={binding as ViewBinding}
                      onClose={() => setActiveSection("copied")}
                      onPlace={() => { if (ready) onSave(binding); }} />}
                  </>
                )}
              </div>
            </div>

            {/* β›”β›” W53-T16 (owner instruction 13) - THE FOUR SENTENCE SUMMARY IS DELETED, NOT HIDDEN.
                It restated the period, the lock and the two drag rules that the controls immediately
                above already say, in a panel 380px wide where every line it took pushed Save further
                off screen. The one line kept is R11's, because it is the only sentence here that names
                something NO control shows: the filter in this cell was copied out of a view that has
                since been deleted, and nothing else remembers that. */}
            {adoptedFrom && (
              <p className="sheet-binding-line sheet-binding-adopted">
                {`Filter adopted from the deleted view ${adoptedFrom}`}
              </p>
            )}

            {preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>}
            {relatedUnavailable && <p className="sheet-notice" role="status">
              Some related fields in this filter are unavailable. Review the filter before saving.
            </p>}
            {notice && <p className="sheet-notice" role="alert">{notice}</p>}
          </>
      </div>

      {/* C7 and the owner's Apple principle: Save is this surface's ONE primary;
          Preview and Cancel are deliberately quiet. */}
      <div className="sheet-binding-actions">
        {shape === "value" && <>
        <button type="button" className="lp-btn lp-btn-quiet" onClick={runPreview} disabled={!ready}>
          Preview
        </button>
        <button type="button" className="lp-btn lp-btn-primary" onClick={async () => {
          setNotice(""); const prepared = await prepareBinding(); if (prepared) onSave(binding);
        }}
                disabled={!ready}>
          Save
        </button>
        </>}
        <button type="button" className="lp-btn lp-btn-quiet" onClick={onCancel}>
          Cancel
        </button>
      </div>
    </section>
  );
}