File size: 55,921 Bytes
e9a4c3e
 
 
e13472e
 
e9a4c3e
 
 
f1ae536
 
 
e9a4c3e
 
 
 
 
cfd4ac1
 
 
 
 
e13472e
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5696cb
 
cfd4ac1
e13472e
 
 
 
 
cfd4ac1
e13472e
cfd4ac1
 
e13472e
 
e9a4c3e
a83fcff
95215b6
f1ae536
8145bee
e9a4c3e
f1ae536
a83fcff
b80130d
aa1490a
 
f5696cb
39a9177
f5696cb
e9a4c3e
 
b80130d
dcd43e2
b80130d
7f72224
e9a4c3e
 
 
 
 
 
 
 
 
 
 
e13472e
 
e9a4c3e
 
 
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
 
 
cfd4ac1
7f72224
 
cfd4ac1
 
 
7f72224
cfd4ac1
7f72224
 
cfd4ac1
7f72224
 
 
 
 
cfd4ac1
7f72224
 
 
 
 
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
dcd43e2
a83fcff
f5696cb
 
 
 
a83fcff
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
f5696cb
 
e13472e
cfd4ac1
 
a83fcff
cfd4ac1
 
e13472e
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
e13472e
 
cfd4ac1
 
 
f1ae536
 
 
9a6cb9a
 
 
 
e9a4c3e
1ad1eea
 
e9a4c3e
 
9a6cb9a
 
e9a4c3e
 
 
b80130d
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5696cb
cfd4ac1
 
 
 
 
 
 
a83fcff
dcd43e2
 
a83fcff
 
e9a4c3e
 
b80130d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e600b9
 
 
b80130d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
9a6cb9a
1ad1eea
a83fcff
cfd4ac1
e9a4c3e
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5696cb
cfd4ac1
 
 
 
f5696cb
cfd4ac1
e13472e
 
4b54047
 
 
 
 
e13472e
dcd43e2
 
 
 
 
 
 
cfd4ac1
 
f5696cb
cfd4ac1
a83fcff
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
e9a4c3e
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
cfd4ac1
 
aa1490a
 
 
 
 
 
cfd4ac1
 
 
 
 
 
 
 
e9a4c3e
 
aa1490a
4325491
e9a4c3e
9a6cb9a
e9a4c3e
cfd4ac1
aa1490a
 
 
e9a4c3e
 
 
 
4325491
e9a4c3e
 
 
 
 
9a6cb9a
cfd4ac1
 
f5696cb
cfd4ac1
 
 
 
 
 
 
 
 
dcd43e2
 
 
 
 
 
e13472e
 
 
4b54047
95215b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
 
 
cfd4ac1
aa1490a
 
740ecde
 
cfd4ac1
740ecde
cfd4ac1
a83fcff
 
 
 
cfd4ac1
4325491
a83fcff
aa1490a
 
a83fcff
 
 
 
aa1490a
a83fcff
cfd4ac1
 
740ecde
a83fcff
cfd4ac1
 
 
4b54047
cfd4ac1
 
 
e13472e
 
 
 
aa1490a
 
 
 
 
 
 
 
 
4325491
aa1490a
 
 
 
 
4325491
 
 
 
 
 
aa1490a
 
 
 
e13472e
 
 
aa1490a
4b54047
e13472e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa1490a
e13472e
 
 
 
 
 
aa1490a
 
 
e13472e
 
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5696cb
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4325491
aa1490a
 
8145bee
aa1490a
 
 
 
 
8145bee
f1ae536
 
aa1490a
 
 
 
a83fcff
f1ae536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
4b54047
a83fcff
 
 
f5696cb
4b54047
f5696cb
a83fcff
f5696cb
 
 
a83fcff
 
 
dcd43e2
a83fcff
 
 
 
 
 
 
 
 
 
 
aa1490a
a83fcff
aa1490a
a83fcff
 
 
1ad1eea
a83fcff
 
1ad1eea
 
 
 
a83fcff
 
 
 
 
 
aa1490a
a83fcff
 
aa1490a
a83fcff
aa1490a
f1ae536
 
 
 
 
 
 
 
 
aa1490a
 
f1ae536
aa1490a
f1ae536
 
 
 
 
 
 
 
 
 
aa1490a
f1ae536
aa1490a
f1ae536
a83fcff
aa1490a
 
 
a83fcff
 
 
aa1490a
a83fcff
cfd4ac1
 
 
 
 
95215b6
 
 
cfd4ac1
 
 
f5696cb
 
 
 
 
 
 
4ca2251
 
cfd4ac1
 
f5696cb
cfd4ac1
9a6cb9a
 
e9a4c3e
 
 
 
 
39a9177
e9a4c3e
 
 
 
 
 
 
 
cfd4ac1
 
 
7f72224
e9a4c3e
 
 
 
 
39a9177
e9a4c3e
 
 
 
 
 
 
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
f5696cb
 
 
 
 
 
 
 
 
 
cfd4ac1
 
f5696cb
 
 
cfd4ac1
 
7f72224
cfd4ac1
 
 
 
f1ae536
aa1490a
cfd4ac1
e13472e
f5696cb
dcd43e2
e13472e
 
 
 
 
b80130d
 
e13472e
 
 
 
 
 
a83fcff
e13472e
 
 
 
 
 
 
f1ae536
e13472e
 
 
 
 
 
 
a83fcff
 
f1ae536
9a6cb9a
f1ae536
aa1490a
 
 
9a6cb9a
 
 
 
e13472e
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
e9a4c3e
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
// sheet/DrillModal.tsx β€” a bound cell's rows, in the Link field's own popup (W49-T07, R6/R13/R17).
//
// ⭐⭐ R6 SAYS "EXACTLY THE LINK FIELD TYPE'S POPUP UI", SO THIS REUSES THE COMPONENT RATHER THAN
// ITS APPEARANCE. `LinkGridModal` is imported from `customer-grid/CustomerGrid.tsx`. Rebuilding a
// lookalike would give the product two
// popups that behave almost the same, and "almost" is where a focus trap or an escape key goes
// missing on one of them.
//
// R13 requires live rows and counts. The drill returns an exact count and page IDs.
// Its caller-owned row source replays structured queries under current permissions.
// Page IDs identify rows already read and never restrict the remaining population.
//
// ⭐ R13 ALSO FORBIDS DISCLOSING STALENESS HERE. A stale cell opens the same popup with the same
// chrome and NO comparison text: no "was 24,920", no badge, nothing. The staleness is a property of
// the CELL and it is marked on the grid; repeating it here would be answering a question the person
// did not ask, at the moment they asked a different one.
//
// ⭐⭐ W54-T34 (owner instruction 10) β€” NINE SECONDS OF NOTHING WAS THE DEFECT.
// Owner, verbatim: *"Clicking View rows still takes a long time; if it must, we need a loading
// button so the user knows their click worked."* This component used to render `null` for the whole
// of that wait, so a drill that was working and a click that never landed looked identical. Measured
// on tenant #0 (`AutoWiki/waves/wave54/lanes/E/T36-baseline.md`): `drill_cell` costs 55 to 90 ms
// against a `ut_*` table but 9,248 to 9,448 ms against `customer_data`, which goes through the
// registry-module mirror rather than a DuckDB query. So the wait is real and it is long.
//
// β›” BOTH `null`S WERE THE DEFECT, NOT ONE. The request had no loading state and neither did the
// LAZY CHUNK behind it, so a warm answer could still be followed by a second blank window while
// 1,850 kB of `CustomerGrid` downloaded. The Suspense fallback's old note argued that "a skeleton
// behind a modal that is about to cover it would be a flash of furniture nobody asked for" - which
// was right when there was no skeleton at all and the two states were nothing and everything. Now
// the skeleton is ALREADY on screen when the answer lands, so keeping it up for the chunk is
// CONTINUITY rather than new furniture: the surface never blinks back to nothing.
//
// ⭐⭐ W54-T35 (owner instruction 8, ruling R8) β€” THE ROWS ARE HERE, SO THE REASON FOR THEM
// SHOULD BE TOO. Owner, verbatim: *"the Filter module itself will show exactly what the filter is
// when we click 'View row' so its easy for user also to know what this filter is. In fact, they
// should be able to change the filter there too. And if they make a mistake etc, they can just
// CTRL + Z to return the Cell to its original filter."* Three clauses, and each one is a decision
// recorded beside the code that answers it: the BAND (`DrillFilterBand`) states it, the grid's
// Filter control edits it, and one cell-scoped step of undo takes it back.
//
// ⭐⭐ W56-T24 / R4 / C4 β€” THE LINK MODAL NOW OWNS ORDINARY SLOTS FOR THE SHEET'S CHROME.
// The toolbar and filter statement are children of the modal's header and footer, so they remain
// inside its focus trap and dismissal boundary without querying the DOM or waiting for a frame.
// The body is the default `CustomerGrid` export itself, with `cellView` relaxing only its embedded
// mode-switcher withholding. The embedded write and workspace guards remain untouched.
//
// β›” THE REAL FOOTER MAY WEAR `.cg-link-grid-foot`, WHICH THE SKELETON ABOVE MAY NOT. The rule that
// stops `DrillSkeleton` borrowing `customer-grid/RecordDetail.css` is that the skeleton stands in
// for a chunk that has not arrived, so on a cold cache its class names would exist and its rules
// would not. `LinkGridModal` renders that footer only after the same chunk is in hand, so its
// stylesheet is guaranteed present. Same file, opposite verdict, for one reason: WHEN it paints.

import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { API_V1, CREDENTIALS } from "../apiContract";
import { aggregatePageProgress, aggregatePayload, fetchWorkspace } from "../customer-grid/apiBridge";
import { dropAppliedFilterLimits } from "../customer-grid/drillLimits";
import type { SurfaceScope } from "../customer-grid/apiBridge";
import type { CellDisplayChoice, EmbeddedRowSource } from "../customer-grid/CustomerGrid";
import { dataPathHash } from "../customer-grid/dataPath";
import { AnchoredOverlay, BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
import type { CustomersPayload, Field, FilterTree, GridWorkspace, Row } from "../customer-grid/types";
import { mayEditField } from "../customer-grid/types";
import { conditionCountLabel, filterSentence } from "../filter-kit/SheetFilterPopup";
import { useEscapeClose } from "../ui/useEscapeClose";
import { cellForcedFieldKeys, cellViewVisibleKeys } from "./bindingRefs";
import { drillCell } from "./sheetApi";
import type { CellDrill } from "./sheetApi";
import type { BindingDisplay, ViewBinding, ViewRowsAnswer } from "./types";
import { bindingDisplay } from "./types";
import { fetchViewRows, showingLine } from "./viewPlacement";
import "../styles/sdlc80/drill.css";

/**
 * β›”β›” LAZY, AND THE BUILD IS WHAT SAID SO. A plain `import { LinkGridModal } from
 * "../customer-grid/CustomerGrid"` compiles and typechecks perfectly, and it quietly defeats the
 * code-splitting of a 1,850 kB chunk. Rollup reported it as
 * `INEFFECTIVE_DYNAMIC_IMPORT: CustomerGrid.tsx is dynamically imported by App.tsx,
 * RecordDetail.tsx, QueryPage.tsx and Shell.tsx but also statically imported by DrillModal.tsx,
 * dynamic import will not move module into another chunk` - which in practice means opening the
 * Sheet page downloads the whole customer grid before anyone has drilled into anything.
 *
 * ⚠ `React.lazy` wants a DEFAULT export and `LinkGridModal` is a named one, so the promise is
 * mapped. That is the whole trick: the export stays named and the split remains intact while
 * W56-T24 extends the modal through optional props.
 */
const LinkGridModal = lazy(() =>
  import("../customer-grid/CustomerGrid").then((m) => ({ default: m.LinkGridModal })),
);

/**
 * ⭐⭐ W54-T34 β€” THE CHUNK IS ASKED FOR WHEN THE READER ASKS FOR THE ROWS, NOT AFTER THEY ARRIVE.
 *
 * `React.lazy` starts its import on the first render that actually reaches `<LinkGridModal>`, which
 * on the success path is AFTER the drill has answered. On `customer_data` that is nine seconds, and
 * the 1,850 kB download then begins from zero: two waits, back to back, for one click. Warming the
 * module the moment this component mounts runs them together instead. Nothing is imported twice -
 * the two dynamic imports name the same module, so the second one resolves off the registry.
 *
 * β›” AND THE BOOLEAN IT FEEDS IS NOT A CONVENIENCE, IT IS THE ESCAPE CLAIM. `LinkGridModal` joins
 * the base kit's stack from inside itself, through `useOverlayLayer`, so it claims Escape only once
 * it has MOUNTED. The window while its chunk is still in flight belongs to nobody. Knowing when the
 * module is in hand is what lets the skeleton hold the claim for exactly that window and hand it
 * over, rather than overlap it - the double-push the W51-T12 note below is careful to avoid.
 */
const warmLinkChunk = () => import("../customer-grid/CustomerGrid");

/**
 * A Sheet binding names a DATABASE KEY; `LinkGridModal` wants a `SurfaceScope`. The two are not
 * the same vocabulary and the difference is only visible for the two compiled modules.
 *
 * ⚠ The same mapping already exists in the Time-series panel, which is ANOTHER LANE'S FILE in this
 * wave. It is re-stated here rather than imported so lane A touches nothing of lane C's; the pair
 * is small, total, and the right place to unify them is after both lanes merge.
 */
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;
};

/**
 * ⭐⭐ W54-T34 β€” WHAT VIEW ROWS OPENS INTO WHILE ITS ROWS ARE FETCHED.
 *
 * β›” THE SKELETON LANGUAGE IS INHERITED, NOT INVENTED. `sheet/SheetRail.tsx::RailSkeleton` set it
 * and `sheet/BindingEditor.tsx::BindingSkeleton` followed it one ticket ago: ONE flat
 * `--lp-surface-2` tone, no shimmer (an animated sweep is a second thing moving on a surface whose
 * whole job is to sit still, and `prefers-reduced-motion` would then need a third state), bars
 * `aria-hidden` under ONE `role="status"` so a screen reader hears "loading" once, and 150 ms
 * ease-out on opacity alone. A second skeleton dialect in the same stylesheet would be the cost.
 *
 * β›”β›” AND IT CANNOT BORROW `.cg-record-backdrop` / `.cg-link-grid-modal`, WHICH IS THE OBVIOUS
 * SHORTCUT AND IS EXACTLY BACKWARDS. Those rules live in `customer-grid/RecordDetail.css`, imported
 * by `RecordDetail.tsx` - inside the very chunk this skeleton is standing in for. On a cold cache
 * the class names would be there and the rules would not, so the stand-in for a slow chunk would
 * paint in native chrome, precisely when it is needed most.
 * ([[portalling-drops-descendant-scoped-css]], same failure through a different door.)
 *
 * ⭐ THE GEOMETRY IS THE SETTLED MODAL'S, measured off `.cg-link-grid-modal`: the same
 * `min(1320px, 100vw - 48px)` by `min(840px, 100vh - 48px)` card on the same centred scrim, a 54px
 * head, then rows. That is what makes it a skeleton rather than a placeholder - the real grid lands
 * where the bars were instead of resizing the surface under the reader's eyes.
 */
function DrillSkeleton(
  { label, nodeRef, onClose }: {
    label: string; nodeRef: { current: HTMLDivElement | null }; onClose: () => void;
  },
) {
  useOverlayLayer({ panelRef: nodeRef, onDismiss: onClose, dismissOnOutside: false,
    initialFocus: "first", restoreFocus: true, trapFocus: true });
  return (
    <div
      className="sheet-drill-skeleton-backdrop"
      onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}
    >
      <div className="sheet-drill-skeleton" role="dialog" aria-modal="true"
        aria-label={`Loading the rows behind ${label}`} ref={nodeRef}>
        <div className="sheet-drill-skeleton-head">
          <div className="sheet-drill-skeleton-labels" aria-hidden="true">
            <span className="sheet-drill-skeleton-title" />
            <span className="sheet-drill-skeleton-sub" />
          </div>
          <button type="button" className="sheet-action" onClick={onClose}>Close</button>
        </div>
        <div className="sheet-drill-skeleton-rows" role="status" aria-label="Loading rows">
          <div className="sheet-drill-skeleton-bars" aria-hidden="true">
            <span className="sheet-drill-skeleton-row is-head" />
            {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((i) => (
              <span className="sheet-drill-skeleton-row" key={i} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/**
 * ⭐⭐ W54-T35 / R8 β€” WHICH ROWS THE CELL ASKED FOR, IN THE TWO SHAPES A BINDING CAN SAY IT.
 *
 * β›” THE `view` ARM EXISTS SO THE EDITOR CAN BE WITHHELD, AND THAT IS R8 VERBATIM: *"The Fields
 * list … is hidden everywhere else, including under 'A saved view', where the view already fixes
 * the rows."* A saved view's rows are the VIEW's business; editing a filter here would either
 * silently fork the cell off its view or edit the view for everybody who uses it. So a view-bound
 * cell gets the sentence and no Edit door.
 */
export type DrillCellScope = (
    | { kind: "filter"; tree: FilterTree }
    | { kind: "view"; name: string }
  )
  & {
    /** C4: the cell's persisted column choices, independent of any shared View. */
    display?: BindingDisplay;
    /** The host supplies these from the current binding alongside its filter or saved view. */
    aggregateField?: string;
    /** The Option step's binding.onDrag.down.field, when down is a field rule. */
    stepField?: string;
  };

/** What the drill's own answer says about the scope, for a caller that passed none. */
function scopeFromDrill(drill: CellDrill | null): DrillCellScope | null {
  if (!drill) return null;
  if (drill.view_id) return { kind: "view", name: "" };
  const tree = drill.filter as FilterTree | null | undefined;
  return { kind: "filter", tree: tree ?? { conj: "and", nodes: [] } };
}

/**
 * ⚠ TREE EQUALITY BY SERIALISATION, deliberately, and the shape is what makes it safe. A
 * `FilterTree` is plain JSON with no cycles and no undefined-versus-absent subtleties that matter
 * here: both sides of every comparison this file makes came out of the SAME builder, so their key
 * order is the builder's own. A hand-written deep-equal over `FilterRule`'s eleven optional
 * members is the thing that would quietly stop noticing a member somebody added later.
 */
const sameTree = (a: FilterTree | null, b: FilterTree | null): boolean =>
  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);

/**
 * ⭐⭐ W54-T35 β€” THE BAND THAT STATES THE FILTER, at the foot of the rows it produced.
 *
 * The sentence is the whole of the owner's first clause, so it takes the width and truncates with
 * an ellipsis rather than being shortened into a count; the full text stays reachable as the
 * element's `title`. The grid's Filter control owns editing; this band states the cell's scope
 * and any editing limit. W56-T24 seats it inside `LinkGridModal`'s footer slot, so that shell now
 * supplies the `cg-link-grid-foot` paint instead of this child impersonating the footer itself.
 */
function DrillFilterBand(
  { text }: { text: string },
) {
  return (
    <span
      // The modal's real `cg-link-grid-foot` wrapper supplies the paint. These classes name the
      // statement itself for a gate, a screenshot or a person in the inspector.
      className="sheet-drill-filter sheet-drill-filter-text"
      style={{
        minWidth: 0,
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
        color: "var(--lp-muted)",
      }}
      title={text}
    >
      {text}
    </span>
  );
}

/** Explain a legacy server's ID cap while page-based responses use their ordinary pager. */
function drillCapText(drill: Pick<CellDrill, "record_ids" | "count" | "record_ids_scope"> | null): string {
  if (!drill || drill.record_ids_scope === "page" || drill.record_ids.length >= drill.count) return "";
  return `Showing ${drill.record_ids.length.toLocaleString()} of ${drill.count.toLocaleString()} `
    + "matching records. Narrow the cell's filter to list the rest.";
}

export interface DrillModalProps {
  embedded?: boolean;
  onNavigate?: (address: { database: string; view?: string }) => void;
  workbookId: string;
  addr: string;
  /** S66-T48: the tab the cell is on, so the drill reads THIS tab's cell at `addr`. */
  tab?: string;
  /** The label the popup wears. The cell's own address is the honest one: it is what was clicked. */
  label: string;
  onClose: () => void;
  previewBinding?: ViewBinding;
  onPlace?: () => void;
  /**
   * W54-T34: the drill has stopped waiting - it answered, or it was refused. The page uses this to
   * take the busy state back off the control that was clicked. It is NOT "the rows are on screen":
   * a refusal settles too, and a control left spinning over a refusal is the worse failure.
   */
  onSettled?: () => void;
  /**
   * W54-T35: the cell's OWN rows-to-include, read off its binding by the page.
   *
   * ⚠ NOT THE SAME THING AS THE DRILL ANSWER'S `filter`, and the difference is worth a prop. The
   * answer describes what the SERVER used for the rows on screen; this describes what the cell
   * holds NOW, which is what an edit changes and what an undo restores. On a healthy save the two
   * agree within one round trip. Absent, the answer is used instead, so a caller that passes
   * nothing still gets a drill that states its filter.
   */
  cellScope?: DrillCellScope | null;
  /**
   * W54-T35: persist a new filter for this cell and recompute it.
   *
   * β›” IT RESOLVES WHEN THE WRITE HAS SETTLED, which is what lets the rows be re-read afterwards
   * rather than immediately: `GET …/drill` reads the STORED binding, so a re-read fired before
   * the save landed would answer with the filter that is being replaced and paint the old rows
   * over the new filter.
   */
  onFilterChange?: (addr: string, tree: FilterTree) => void | Promise<void>;
  /**
   * C4: persist column choices for this cell. The grid reports ordered visibility; this modal
   * settles the edits before calling the Sheet host's binding writer.
   */
  onDisplayChange?: (addr: string, display: BindingDisplay) => void | Promise<void>;
}

export default function DrillModalEntry(props: DrillModalProps) {
  return props.previewBinding
    ? <OverlayProvider><ViewRowsPreview {...props} previewBinding={props.previewBinding} /></OverlayProvider>
    : <DrillModal {...props} />;
}

// R35 deliberately previews the resolver's own projection, not LinkGridModal's record list.
// LinkGridModal needs recordIds from a stored-cell drill, but this binding is not stored yet.
// Adding ids would change routes_sheet.py outside this ticket's fence, and a record list would
// show every field instead of the chosen fields at the chosen limit in the chosen order.
function ViewRowsPreview({ workbookId, label, previewBinding, onClose, onPlace, onSettled }:
  DrillModalProps & { previewBinding: ViewBinding }) {
  const requestKey = JSON.stringify([workbookId, previewBinding]);
  const [viewRows, setViewRows] = useState<{
    key: string; answer?: ViewRowsAnswer; error?: string;
  } | null>(null);
  const settledRef = useRef(onSettled);
  settledRef.current = onSettled;
  const panelRef = useRef<HTMLDivElement>(null);
  useOverlayLayer({ panelRef, onDismiss: onClose, dismissOnOutside: false,
    initialFocus: "first", restoreFocus: true, trapFocus: true });

  useEffect(() => {
    let live = true;
    const [id, binding] = JSON.parse(requestKey) as [string, ViewBinding];
    void fetchViewRows(id, binding).then((got) => {
      if (!live) return;
      setViewRows(got.ok ? { key: requestKey, answer: got.answer }
        : { key: requestKey, error: got.message });
      settledRef.current?.();
    });
    return () => { live = false; };
  }, [requestKey]);

  const current = viewRows?.key === requestKey ? viewRows : null;
  const answer = current?.answer;
  const headerActions = onPlace ? (
    <div className="sheet-cell-view-toolbar" role="toolbar" aria-label="View controls">
      <button type="button" className="lp-btn lp-btn-primary" disabled={!answer}
        onClick={onPlace}>Place in sheet</button>
    </div>
  ) : null;
  const cellText = (value: unknown) => value == null ? ""
    : typeof value === "object" ? JSON.stringify(value) : String(value);

  return <BodyPortal>
    <div className="sheet-drill-skeleton-backdrop">
      <div className="sheet-drill-skeleton" role="dialog" aria-modal="true"
        aria-label={label} ref={panelRef}>
        <header className="sheet-drill-skeleton-head" style={{ flexDirection: "row", alignItems: "center" }}>
          <h2 className="sheet-binding-title" style={{ flex: 1 }}>{label}</h2>
          {headerActions}
          <button type="button" className="lp-btn lp-btn-quiet" onClick={onClose}>Close</button>
        </header>
        <div style={{ overflow: "auto", padding: 16, minHeight: 0,
          ...(!current ? { flex: 1, display: "grid", placeItems: "center" } : {}) }} aria-busy={!current}>
          {!current && <p className="sheet-chart-empty" role="status" style={{ margin: 0 }}>Loading view…</p>}
          {current?.error && <p className="sheet-notice" role="alert">{current.error}</p>}
          {answer && <>
            <p className="sheet-period-note" role="status">{showingLine(answer.rows.length, answer.total)}</p>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "var(--lp-fs-xs)" }}>
              <thead><tr>{answer.fields.map((field) => <th key={field.key} scope="col"
                style={{ textAlign: "left", padding: 8, borderBottom: "1px solid var(--lp-line)" }}>
                {field.label}
              </th>)}</tr></thead>
              <tbody>{answer.rows.map((row, index) => <tr key={index}>
                {answer.fields.map((field) => <td key={field.key} style={{ padding: 8,
                  borderBottom: "1px solid var(--lp-line)", fontVariantNumeric: "tabular-nums",
                  textAlign: typeof row[field.key] === "number" ? "right" : "left" }}>
                  {cellText(row[field.key])}
                </td>)}
              </tr>)}</tbody>
            </table>
          </>}
        </div>
      </div>
    </div>
  </BodyPortal>;
}

function DrillModal(
  {
    workbookId, addr, tab, label, onClose, onSettled, cellScope, onFilterChange, onDisplayChange,
    onPlace, embedded = false, onNavigate,
  }: DrillModalProps,
) {
  const [drill, setDrill] = useState<CellDrill | null>(null);
  const [error, setError] = useState("");
  /** Is `LinkGridModal`'s module in hand? See `warmLinkChunk` for why this is a state and not a
   *  detail of Suspense. */
  const [linkReady, setLinkReady] = useState(false);

  /** ⚠ A REF, so a page that hands this an inline arrow does not re-run the fetch effect below on
   *  every one of its own renders. */
  const settledRef = useRef(onSettled);
  settledRef.current = onSettled;
  /** Same reason, one ticket later: the page hands this an inline arrow too. */
  const filterChangeRef = useRef(onFilterChange);
  filterChangeRef.current = onFilterChange;

  // ── W54-T35 state ─────────────────────────────────────────────────────────────────────────
  /**
   * ⭐⭐ THE UNDO, AND IT IS ONE STEP SCOPED TO THIS CELL. Owner: *"if they make a mistake etc,
   * they can just CTRL + Z to return the Cell to its original filter."*
   *
   * β›”β›” IT IS DELIBERATELY NOT `SheetPage`'s `historyRef`. That stack snapshots the WHOLE `sheets`
   * array on every commit, so pushing a filter edit onto it would make one Ctrl+Z walk back
   * whatever else the reader had typed since - an undo that reaches past the surface it was
   * pressed on, into cells nobody was looking at. This holds ONE tree: the cell's filter as it
   * stood before the latest grid filter edit. A second Ctrl+Z therefore has nothing to pop and does not
   * go further back, which is the done-when clause spelled as a data structure rather than as a
   * guard somebody has to remember to write.
   */
  const [undoTree, setUndoTree] = useState<FilterTree | null>(null);
  /** The tree before the current grid filter edit burst, retained for its undo step. */
  const preEditRef = useRef<FilterTree | null>(null);
  /** Latest grid-owned filter edit waiting for 800 ms of quiet before it reaches the cell. */
  const pendingCellFilterRef = useRef<FilterTree | null>(null);
  // Columns respond to the current edit while its binding write is still debounced. The base
  // prevents an old draft from overriding a later host update (including undo or a refusal).
  const [cellFilterDraft, setCellFilterDraft] = useState<{
    base: string; tree: FilterTree;
  } | null>(null);
  const cellFilterTimerRef = useRef<number | null>(null);
  const [cellDisplayDraft, setCellDisplayDraft] = useState<{
    base: string; display: BindingDisplay;
  } | null>(null);
  const cellDisplayTimerRef = useRef<number | null>(null);
  const pendingCellDisplayRef = useRef<{
    addr: string; display: BindingDisplay; report: DrillModalProps["onDisplayChange"];
  } | null>(null);
  /** Bumped when a filter change has landed, so the rows are read again. */
  const [reloadSeq, setReloadSeq] = useState(0);
  /** Fields for the filter sentence and export, fetched once the drill has answered. */
  const [fields, setFields] = useState<Field[]>([]);
  const [workspace, setWorkspace] = useState<GridWorkspace | null>(null);
  const [rowsResolved, setRowsResolved] = useState(false);
  const [rowsError, setRowsError] = useState("");

  useEffect(() => {
    let live = true;
    // ⚠ BOTH OUTCOMES SET IT. A chunk that fails to load is React's own error path once
    // `<LinkGridModal>` renders, exactly as it was before this ticket; holding the skeleton up
    // forever instead would turn a loud failure into a silent one that looks like a slow server.
    void warmLinkChunk().then(
      () => { if (live) setLinkReady(true); },
      () => { if (live) setLinkReady(true); },
    );
    return () => { live = false; };
  }, []);

  /**
   * ⭐⭐ W51-T12 - THE REFUSAL CARDS CLOSE ON ESCAPE TOO, AND THAT WAS THE HOLE.
   *
   * The SUCCESS path already closes on Escape and needs nothing from this component:
   * `CustomerGrid.tsx::LinkGridModal` calls `useOverlayLayer`, which calls
   * `useEscapeClose(true, onEscape, ...)` (`customer-grid/OverlaySurface.tsx`), so the popup joined
   * the base kit's topmost-wins stack in W51-T01. Verified on this branch rather than assumed.
   *
   * β›” BUT THE TWO ERROR BRANCHES BELOW RENDER OUTSIDE `LinkGridModal` - a bare `.sheet-drill-error`
   * card with its own Close button and nothing else. The overlay stack never hears about them, so
   * before this a reader who drilled into a database the popup cannot address got a card that
   * Escape did nothing to. The claim is registered only while such a card is on screen, so the
   * success path keeps exactly one claimant and the stack is never double-pushed.
   */
  const cardRef = useRef<HTMLDivElement | null>(null);
  const scope = drill ? scopeOf(drill.database) : null;
  const showingCard = Boolean(error) || Boolean(drill && !scope);
  const onEscape = useCallback(() => onClose(), [onClose]);
  const escapeContainer = useCallback(() => cardRef.current as HTMLElement | null, []);
  useEscapeClose(showingCard, onEscape, { container: escapeContainer });

  // The mounted skeleton owns its focus trap and Escape claim until LinkGridModal replaces it.
  const skeletonRef = useRef<HTMLDivElement | null>(null);

  /** Every drill answer carries its request's number and only the newest lands (S68-T23 finding). */
  const drillSeqRef = useRef(0);
  const draftTimerRef = useRef<number | null>(null);
  /** From a grid filter edit until the ids for it land: the grid's rows for the OLD ids are not an answer. */
  const [idsPending, setIdsPending] = useState(false);

  /**
   * β›”β›” W54-T35 β€” `reloadSeq` IS A DEPENDENCY AND `setDrill(null)` IS STILL NOT CALLED. A filter
   * that has just been changed has to be answered again, because the ids on screen were narrowed
   * by the OLD one. But clearing the answer first would unmount `LinkGridModal`, put the skeleton
   * back over a card the reader is already reading, and then remount the whole grid: a blink, in
   * exactly the place W54-T34 spent a ticket removing one. The previous answer stays up and is
   * REPLACED when the new one lands, so only the row list changes.
   */
  useEffect(() => {
    let live = true;
    const seq = ++drillSeqRef.current;
    setIdsPending(true);
    (async () => {
      const got = await drillCell(workbookId, addr, tab);
      if (!live) return;
      settledRef.current?.();
      // A newer draft drill has already answered for the grid's current filter.
      if (seq !== drillSeqRef.current) return;
      setIdsPending(false);
      if (!got.ok) {
        setError(got.message);
        return;
      }
      setError("");
      setDrill(got.value);
    })();
    return () => {
      live = false;
    };
  }, [workbookId, addr, tab, reloadSeq]);

  /**
   * W54-T35: what the band says, and what the grid's Filter control edits.
   *
   * The page's own reading of the cell wins, because it is the one that MOVES: it is rebuilt from
   * the workbook after every commit, so the sentence changes the moment a filter is applied. The
   * drill answer is the fallback for a caller that passed none, and it is a real one rather than a
   * courtesy: the server sends the scope on every drill.
   */
  const shown = cellScope ?? scopeFromDrill(drill);
  const shownKind = shown?.kind ?? "";
  const shownTree = shown?.kind === "filter" ? shown.tree : null;
  const shownDisplayKey = JSON.stringify([workbookId, addr, shown?.display ?? null]);
  const cellDisplay = cellDisplayDraft?.base === shownDisplayKey
    ? cellDisplayDraft.display : shown?.display;
  useEffect(() => {
    setCellDisplayDraft((draft) => draft?.base === shownDisplayKey ? draft : null);
  }, [shownDisplayKey]);
  /** The cell's current tree at the instant a delayed grid edit settles. */
  const shownTreeRef = useRef<FilterTree | null>(shownTree);
  shownTreeRef.current = shownTree;
  const shownTreeKey = JSON.stringify(shownTree);
  const [relatedLabels, setRelatedLabels] = useState<{ database: string; fields: Field[] } | null>(null);
  const relatedDatabase = shownTreeKey.includes('"related:') ? drill?.database : undefined;
  useEffect(() => {
    if (!relatedDatabase) return;
    const controller = new AbortController();
    void fetch(`${API_V1}/sheets/filter-fields/${encodeURIComponent(relatedDatabase)}`, {
      credentials: CREDENTIALS, signal: controller.signal,
    }).then(async response => {
      if (!response.ok) return;
      const body = await response.json();
      if (!controller.signal.aborted && Array.isArray(body?.fields)) {
        const labels = body.fields.flatMap((field: Field & { related?: { legacyKeys?: string[] } }) =>
          [field, ...(field.related?.legacyKeys ?? []).map(key => ({ ...field, key }))]);
        setRelatedLabels({ database: relatedDatabase, fields: labels });
      }
    }).catch(() => { /* The footer keeps its unnamed-field fallback if metadata is unavailable. */ });
    return () => controller.abort();
  }, [relatedDatabase]);
  useEffect(() => {
    setCellFilterDraft((draft) => draft?.base === shownTreeKey ? draft : null);
  }, [shownTreeKey]);

  // C2: read the field catalogue through the existing workspace client. Export asks for rows
  // only on click; this surface owns no workspace cache or whole-table row book.
  const [rowsGo, setRowsGo] = useState(false);
  useEffect(() => { if (drill && linkReady) setRowsGo(true); }, [drill, linkReady]);
  useEffect(() => {
    if (!scope || !rowsGo) return;
    let live = true;
    setRowsResolved(false);
    setRowsError("");
    setFields([]);
    setWorkspace(null);
    (async () => {
      const ws = await fetchWorkspace(scope, { allowCached: true, fieldsOnly: true });
      if (!live) return;
      if (!ws?.fields) {
        setRowsError("The fields for these records could not be loaded. Reopen View data to try again.");
        setRowsResolved(true);
        return;
      }
      setWorkspace(ws);
      setFields(ws.fields);
      setRowsResolved(true);
    })();
    return () => { live = false; };
  }, [scope, rowsGo]);

  /** Persist a tree through the page's one binding writer, then read the rows again. */
  const applyTree = useCallback(async (tree: FilterTree) => {
    await Promise.resolve(filterChangeRef.current?.(addr, tree));
    setCellFilterDraft((draft) => draft && sameTree(draft.tree, tree) ? null : draft);
    setReloadSeq((n) => n + 1);
  }, [addr]);

  /**
   * The grid filter panel reports every change. The cell commits only after the edit has been
   * quiet for 800 ms, so typing one condition produces one write and one re-drill.
   */
  /**
   * S68-T23 finding: the grid re-queries the OLD drilled ids with the NEW filter at once, so until
   * the cell write lets the re-drill land it painted those ids narrowed (often empty). The draft
   * tree is drilled after a short pause instead; its ids reach the grid, whose window hook drops
   * the stale answer for the old ids. Nothing is written here; the 800 ms write below still is.
   */
  const drillDraft = useCallback((tree: FilterTree) => {
    setIdsPending(true);
    if (draftTimerRef.current !== null) window.clearTimeout(draftTimerRef.current);
    const seq = ++drillSeqRef.current;
    draftTimerRef.current = window.setTimeout(() => {
      draftTimerRef.current = null;
      void drillCell(workbookId, addr, tab, { filter: tree }).then((got) => {
        if (seq !== drillSeqRef.current) return;
        setIdsPending(false);
        if (got.ok) {
          setError("");
          setDrill(got.value);
        } else {
          setError(got.message);
        }
      });
    }, 150);
  }, [workbookId, addr, tab]);

  const settleCellFilter = useCallback((tree: FilterTree) => {
    const current = shownTreeRef.current;
    if (!current) return;
    if (!sameTree(tree, current)) drillDraft(tree);
    setCellFilterDraft({ base: JSON.stringify(current), tree });
    if (cellFilterTimerRef.current === null) {
      // One burst gets one undo step: the tree held before its first reported change.
      preEditRef.current = current;
    } else {
      window.clearTimeout(cellFilterTimerRef.current);
    }
    pendingCellFilterRef.current = tree;
    cellFilterTimerRef.current = window.setTimeout(() => {
      cellFilterTimerRef.current = null;
      const next = pendingCellFilterRef.current;
      pendingCellFilterRef.current = null;
      const currentTree = shownTreeRef.current;
      if (!next || !currentTree || sameTree(next, currentTree)) return;
      setUndoTree(preEditRef.current);
      void applyTree(next);
    }, 800);
  }, [applyTree, drillDraft]);

  useEffect(() => () => {
    if (cellFilterTimerRef.current !== null)
      window.clearTimeout(cellFilterTimerRef.current);
    cellFilterTimerRef.current = null;
    pendingCellFilterRef.current = null;
    if (draftTimerRef.current !== null) window.clearTimeout(draftTimerRef.current);
    draftTimerRef.current = null;
    drillSeqRef.current += 1;
  }, []);

  const flushCellDisplay = useCallback(() => {
    if (cellDisplayTimerRef.current !== null)
      window.clearTimeout(cellDisplayTimerRef.current);
    cellDisplayTimerRef.current = null;
    const pending = pendingCellDisplayRef.current;
    pendingCellDisplayRef.current = null;
    if (pending) void pending.report?.(pending.addr, pending.display);
  }, []);

  // Mirror the filter's quiet period, but keep presentation edits when the reader closes early.
  // Capture the address and writer together so a later cell cannot receive an earlier edit.
  const settleCellDisplay = useCallback((display: CellDisplayChoice) => {
    const next = bindingDisplay({ display });
    if (!next) return;
    setCellDisplayDraft({ base: shownDisplayKey, display: next });
    pendingCellDisplayRef.current = { addr, display: next, report: onDisplayChange };
    if (cellDisplayTimerRef.current !== null)
      window.clearTimeout(cellDisplayTimerRef.current);
    cellDisplayTimerRef.current = window.setTimeout(flushCellDisplay, 800);
  }, [addr, shownDisplayKey, onDisplayChange, flushCellDisplay]);

  useEffect(() => () => flushCellDisplay(), [workbookId, addr, flushCellDisplay]);

  /**
   * ⭐⭐ WHERE THE KEYSTROKE ACTUALLY ARRIVES, WHICH IS NOT WHERE THE SHEET'S UNDO LIVES.
   *
   * Ctrl+Z on the Sheet belongs to `SheetGrid.tsx::onKeyDown` (through `shortcuts.ts`), a REACT
   * handler on the grid's own wrapper. While this modal is open the grid canvas does not have
   * focus - focus is trapped inside a body-level portal that is a SIBLING of the grid in the
   * React tree, not a descendant - so that handler is not on the propagation path at all and
   * cannot be reached from here. Nothing in lane D's file has to change, and nothing in it does.
   *
   * β›”β›” WHAT IS ON THE PATH IS `CustomerGrid.tsx`'s OWN Ctrl+Z, and it is the reason this is a
   * capture-phase WINDOW listener rather than a React handler. That component installs
   * `window.addEventListener("keydown", onKey, true)` for its per-database undo, and the drill
   * mounts a CustomerGrid inside the linked-record popup. Capture listeners on one target run in
   * registration order, and this component mounts BEFORE the lazy chunk that mounts that grid, so
   * this one runs first and `stopImmediatePropagation` is what keeps a filter undo from also
   * popping the data grid's stack. A React handler could not have got in front of it.
   *
   * β›” THE KEY IS CLAIMED FOR AS LONG AS THE DRILL IS OPEN, INCLUDING WHEN THERE IS NOTHING TO
   * UNDO. That is the second half of the done-when: a second press must not go further back, and
   * the only way to guarantee that is to consume it rather than to let it fall through to
   * whichever stack is next in line.
   *
   * ⚠ AN INPUT KEEPS ITS OWN UNDO. The same guard `CustomerGrid` uses, for the same reason: a
   * caret in a condition's value box is the browser's text undo, and stealing it would be worse
   * than not having ours. Ctrl+Shift+Z and Ctrl+Y are not claimed; redo is not in this ticket.
   */
  const undoRef = useRef<() => void>(() => {});
  undoRef.current = () => {
    if (!undoTree) return;
    setUndoTree(null);
    void applyTree(undoTree);
  };
  useEffect(() => {
    const onKey = (event: KeyboardEvent) => {
      if (!(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey) return;
      if (event.key.toLowerCase() !== "z") return;
      const el = document.activeElement as HTMLElement | null;
      if (el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable))
        return;
      event.preventDefault();
      event.stopImmediatePropagation();
      undoRef.current();
    };
    window.addEventListener("keydown", onKey, true);
    return () => window.removeEventListener("keydown", onKey, true);
  }, []);

  // The shared ID-window hook consumes the server page without a second row request.
  const initialPage = useMemo(() => {
    if (!drill?.page) return undefined;
    const source = scopeFromDrill(drill);
    const payload: CustomersPayload = {
      fields: drill.page.fields?.length ? drill.page.fields : fields,
      rows: drill.page.rows,
      today: drill.page.today,
      recordsMutable: drill.page.recordsMutable,
      limits: dropAppliedFilterLimits(drill.page.limits, source?.kind === "filter" ? source.tree : undefined),
      counts: { shown: drill.page.rows.length, matched: drill.count,
        total: drill.page.totalUnfiltered ?? drill.count, windowed: true },
    };
    return { offset: drill.page.offset, limit: drill.page.limit, token: drill.token, payload,
      filter: source?.kind === "filter" ? source.tree : undefined };
  }, [drill, fields]);

  const rowSource = useMemo<EmbeddedRowSource | undefined>(() => {
    if (!drill || drill.record_ids_scope !== "page") return undefined;
    const source = scopeFromDrill(drill);
    const filter = source?.kind === "filter" ? source.tree : undefined;
    const read = async (query: import("./sheetApi").CellDrillQuery, offset = 0, limit = 100) => {
      const got = await drillCell(workbookId, addr, tab, { query, offset, limit, filter });
      if (!got.ok) { setRowsError(got.message); return null; }
      return got.value;
    };
    return {
      key: JSON.stringify([workbookId, addr, tab, drill.population, drill.filter, drill.view_id, reloadSeq]),
      readGroups: async (request, by, aggs, offset, size) => {
        const value = await read({ filters: request.filters, filterConj: request.filterConj,
          search: request.search, groupBy: by, aggs, groupOffset: offset, groupLimit: size });
        const summary = value?.summary;
        if (!summary || !Array.isArray(summary.groups) || typeof summary.total_groups !== "number")
          throw new Error("Groups could not be read for this window.");
        if (summary.limits.length)
          throw new Error(summary.limits.map(limit => limit.cause).filter(Boolean).join(". "));
        return { groups: summary.groups as { key: string | number | null; label: string; count: number;
          aggregates: Record<string, number | null> }[], totalGroups: summary.total_groups,
          totalRows: summary.total_rows, aggregates: summary.aggregates };
      },
      readWindow: async (request) => {
        const value = await read({ filters: request.filters, filterConj: request.filterConj,
          sorts: request.sorts, search: request.search, group: request.group }, request.offset, request.limit);
        if (!value?.page) return null;
        const page = value.page;
        return { ...initialPage?.payload, fields: page.fields?.length ? page.fields : fields,
          rows: page.rows, today: page.today, recordsMutable: page.recordsMutable,
          limits: dropAppliedFilterLimits(page.limits, filter),
          counts: { shown: page.rows.length, matched: value.count,
            total: page.totalUnfiltered ?? value.count, windowed: true } };
      },
      readAggregates: async (request) => {
        let offset = 0;
        let answer: ReturnType<typeof aggregatePayload> = null;
        let total: number | undefined;
        let population: string | null | undefined;
        do {
          const value = await read({ filters: request.filters, filterConj: request.filterConj,
            search: request.search, aggs: request.aggs, groupBy: request.groupBy,
            groupOffset: offset, groupLimit: 1000 });
          const summary = value?.summary;
          const page = summary ? aggregatePayload(summary) : null;
          if (!page || !summary) return null;
          if (!request.groupBy) return page;
          const progress = aggregatePageProgress(summary, offset, page.groups?.length, total);
          if (!progress) return null;
          if (!progress.done && !value?.population) return null;
          if (!answer) { answer = page; total = summary.total_groups; population = value?.population; }
          else {
            if (value?.population !== population || total !== summary.total_groups
                || page.totalRows !== answer.totalRows
                || JSON.stringify(page.aggregates) !== JSON.stringify(answer.aggregates)) return null;
            answer.groups = [...(answer.groups ?? []), ...(page.groups ?? [])];
          }
          offset += page.groups?.length ?? 0;
          if (progress.done) return answer;
        } while (true);
      },
    };
  }, [drill, workbookId, addr, tab, reloadSeq, initialPage, fields]);

  const identityField = fields.find((field) => field.pinned) ?? fields[0] ?? null;
  const savedView = drill?.view_id
    ? workspace?.views?.find((view) => view.id === drill.view_id) ?? null
    : null;
  const fieldFilter: FilterTree | null = shown?.kind === "filter"
    ? (cellFilterDraft?.base === shownTreeKey ? cellFilterDraft.tree : shown.tree)
    : savedView
      ? { conj: savedView.config.filterConj, nodes: savedView.config.filters }
      : null;
  const forcedFieldKeys = cellForcedFieldKeys(
    fieldFilter, shown?.aggregateField, shown?.stepField, fields,
  );
  const defaultFieldKeys = fields
    .filter((field) => field.default !== false
      && (field.custom !== true || Boolean(field.measure))
      && field.shared !== true)
    .map((field) => field.key);
  const visibleKeys = cellViewVisibleKeys(
    defaultFieldKeys,
    cellDisplay?.visible ?? [],
    forcedFieldKeys,
    fields.map((field) => field.key),
    identityField?.key ?? "",
  );
  const visibleFields = visibleKeys
    .map((key) => fields.find((field) => field.key === key))
    .filter((field): field is Field => Boolean(field));

  // CustomerGrid's own value-edit predicate. It distinguishes source-locked values, machine-
  // written pre-set fields and viewer grants field by field instead of inventing one read-only flag.
  const canEditRows = Boolean(
    workspace?.fields && fields.some((field) => mayEditField(field, workspace?.viewer)),
  );
  const exportReady = rowsResolved && Boolean(workspace?.fields);
  const editInData = useCallback(() => {
    if (!drill || !canEditRows) return;
    onClose();
    const address = {
      database: drill.database,
      ...(drill.view_id ? { view: drill.view_id } : {}),
    };
    if (embedded) onNavigate?.(address);
    else window.location.hash = dataPathHash(address);
  }, [canEditRows, drill, embedded, onClose, onNavigate]);

  const exportButtonRef = useRef<HTMLButtonElement>(null);
  const [exportOpen, setExportOpen] = useState(false);
  const [exporting, setExporting] = useState(false);

  const exportCell = useCallback(async (format: "csv" | "xlsx" | "pdf" | "json") => {
    if (!drill || !exportReady || exporting) return;
    setExportOpen(false);
    setExporting(true);
    setRowsError("");
    try {
      const first = drill.page?.offset === 0 ? drill.page : undefined;
      const recordRows: Row[] = [];
      const recordIds = new Set<number>();
      let offset = 0;
      if (!drill.population) throw new Error("These records have no freshness stamp. Reopen View data and try Export again.");
      if (!Number.isSafeInteger(drill.count) || drill.count < 0)
        throw new Error("These records have no complete count. Reopen View data and try Export again.");
      while (offset < drill.count) {
        const got = await drillCell(workbookId, addr, tab, { offset, limit: 1000,
          filter: drill.view_id ? undefined : drill.filter, query: drill.query });
        if (!got.ok) throw new Error(got.message);
        if (!got.value.page) throw new Error("The records for Export did not include a page. Try again.");
        if (got.value.population !== drill.population || got.value.count !== drill.count)
          throw new Error("These records changed while Export was preparing. Try again.");
        if (got.value.page.offset !== offset || got.value.page.total !== drill.count
            || got.value.page.rows.length > drill.count - offset)
          throw new Error("Some records could not be read. Try Export again.");
        if (!got.value.page.rows.length)
          throw new Error("These records changed while Export was preparing. Try again.");
        for (const row of got.value.page.rows) {
          if (!Number.isSafeInteger(row.pid) || recordIds.has(row.pid))
            throw new Error("Some records could not be read. Try Export again.");
          recordIds.add(row.pid);
        }
        recordRows.push(...got.value.page.rows);
        offset += got.value.page.rows.length;
      }
      if (recordRows.length !== drill.count) throw new Error("Some records could not be read. Try Export again.");
      const exporter = await import("../customer-grid/export");
      exporter.runExport(format, `${label} records`, first?.today, visibleFields, recordRows);
    } catch (cause) {
      setRowsError(cause instanceof Error ? cause.message : "These records could not be prepared for Export.");
    } finally {
      setExporting(false);
    }
  }, [drill, exportReady, exporting, workbookId, addr, tab, label, visibleFields]);

  /**
   * The sentence. ⚠ NOT MEMOISED, and that is measured rather than lazy: `filterSentence` walks
   * at most three live leaves and stops, so a memo keyed on a `shown` the page rebuilds every
   * render would recompute exactly as often while costing an extra comparison.
   */
  const sentenceFields = relatedLabels && relatedLabels.database === drill?.database
    ? [...fields, ...relatedLabels.fields] : fields;
  const said = shown?.kind === "filter" ? filterSentence(shown.tree, sentenceFields) : "";
  const bandText = !shown
    ? ""
    : shown.kind === "view"
      // β›”β›” W57-T21 - THE BAND CARRIES THE EDITING LIMIT NOW, because the control that used to
      // carry it is gone. The deleted Edit filter button was DISABLED on this branch with a title
      // saying where the filter is changed instead; without a replacement the grid's own Filter
      // control would sit there looking editable and quietly write nothing back, which is standing
      // rule 1's second sentence exactly: a limit that cannot be removed is REPORTED, never
      // silently enforced.
      ? (shown.name
        ? `Rows come from the saved view ${shown.name}, so this cell's filter is changed in Table`
        : "Rows come from a saved view, so this cell's filter is changed in Table")
      // β›” THE FALLBACK IS THE COUNT, NOT A SECOND SENTENCE. `filterSentence` answers "" when the
      // filter narrows nothing, which covers both an empty tree and one whose conditions are all
      // still half typed; `conditionCountLabel` keeps the wording shared with the filter kit.
      : said ? `Rows where ${said}` : conditionCountLabel(shown.tree);
  // S66-T48: stated beside the rows, never enforced silently (standing rule 1).
  const capText = drillCapText(drill);

  if (error) {
    // A refusal is a plain sentence naming the cause and the subject, per the design contract.
    // It is NOT rendered inside the popup: the popup is a grid of rows, and an error is not a row.
    return (
      <div className="sheet-drill-error" role="alert" ref={cardRef}>
        <p>{error}</p>
        <button type="button" className="sheet-action" onClick={onClose}>
          Close
        </button>
      </div>
    );
  }

  // β›”β›” W54-T34 β€” THIS WAS `return null`, AND IT IS THE OWNER'S REPORT IN ONE LINE. For as long as
  // the drill is in flight the reader got a blank screen, which is what a dead control also looks
  // like. The surface opens immediately and fills in.
  if (!drill) return <DrillSkeleton label={label} nodeRef={skeletonRef} onClose={onClose} />;

  if (!scope) {
    // Named rather than swallowed: a database the popup cannot address is a real gap, and a blank
    // popup would look like "no rows" - the wrong answer, delivered convincingly.
    return (
      <div className="sheet-drill-error" role="alert" ref={cardRef}>
        <p>{`Rows for ${drill.database} cannot be opened from a cell yet.`}</p>
        <button type="button" className="sheet-action" onClick={onClose}>
          Close
        </button>
      </div>
    );
  }

  return (
    // β›”β›” W54-T34 REVERSED THIS FALLBACK, DELIBERATELY. It read `fallback={null}` under the note
    // "the popup either opens or it does not, and a skeleton behind a modal that is about to cover
    // it would be a flash of furniture nobody asked for". That was a true statement about a tree
    // with no skeleton in it: the choice then was between nothing and a brand new surface appearing
    // for one frame. The same skeleton is now ALREADY on screen when the answer lands, so passing
    // it here does not add a surface, it declines to REMOVE one - the chunk loads under the same
    // card the reader has been looking at, and the popup replaces it in place. Handing `null` here
    // now would blink the screen back to empty at the last moment, which is the defect this ticket
    // exists to remove, arriving one step later.
    /**
     * ⭐⭐ ONE `OverlayProvider` OVER EVERY LAYER THIS CARD OPENS, AND IT IS STILL LOAD-BEARING
     * AFTER W57-T21 DELETED THE EDIT DOOR. `useOverlayLayer` defers to a higher layer only when it
     * can SEE one: `if (!dismissOnOutside || (stack && !stack.isTop(id))) return;`, where `stack`
     * is `useContext(OverlayStackContext)`. The Sheet route mounts no provider of its own, so
     * `LinkGridModal` would run with `stack === null` and read a pointerdown ANYWHERE outside its
     * own card as a dismissal, including one inside a layer opened on top of it. The Export menu
     * below is exactly such a layer, and so is every filter, field and sort popover the grid's own
     * chrome opens now that the chrome is the only filter door. Both register here instead, the
     * later one is topmost, and the card stands down while it is up. `filter-kit/SheetFilterPopup.tsx`
     * documents the same trap one layer further out.
     *
     * β›” ESCAPE IS UNAFFECTED AND STILL RESOLVES TO EXACTLY ONE SURFACE. That is the module-level
     * stack in `ui/useEscapeClose`, not this one: the card claims when it mounts, a popover claims
     * when it opens and is therefore topmost, so one press closes the popover and the next closes
     * the drill. The band claims nothing: it is a statement inside the card, not an overlay.
     */
    <OverlayProvider>
      <Suspense fallback={<DrillSkeleton label={label} nodeRef={skeletonRef} onClose={onClose} />}>
        <LinkGridModal
          label={label}
          table={scope}
          recordIds={drill.record_ids}
          rowSource={rowSource}
          {...{ initialPage, idsPending }}
          editable={false}
          cellView
          cellFields={visibleKeys}
          onCellDisplayChange={settleCellDisplay}
          // A view-bound cell passes neither prop: its rows remain the saved view's business.
          cellFilter={shownTree ?? undefined}
          onCellFilterChange={shownKind === "filter" ? settleCellFilter : undefined}
          headerActions={(
            <div className="sheet-cell-view-toolbar" role="toolbar" aria-label="Cell View controls">
              {onPlace && <button type="button" className="lp-btn lp-btn-primary"
                onClick={onPlace}>Place in sheet</button>}
              {canEditRows && (
                <button type="button" className="sheet-cell-view-action" onClick={editInData}>
                  <svg viewBox="0 0 16 16" aria-hidden="true">
                    <path d="m3 11.8-.3 2.1 2.1-.3 7.9-7.9-1.8-1.8zM9.9 4.9l1.8 1.8" />
                  </svg>
                  <span>Edit rows</span>
                </button>
              )}
              <button
                ref={exportButtonRef}
                type="button"
                className="sheet-cell-view-action"
                aria-haspopup="menu"
                aria-expanded={exportOpen}
                disabled={!exportReady || exporting || idsPending}
                onClick={() => setExportOpen((open) => !open)}
              >
                <svg viewBox="0 0 16 16" aria-hidden="true">
                  <path d="M8 2v8M5 7l3 3 3-3M3 12.5h10" />
                </svg>
                <span>{exporting ? "Preparing" : "Export"}</span>
              </button>
            </div>
          )}
          footer={bandText || capText || rowsError || drill.count === 0
            ? <>
              {drill.count === 0 && (
                <DrillFilterBand text="No records match this cell's filter." />
              )}
              {rowsError && <DrillFilterBand text={rowsError} />}
              {capText && <DrillFilterBand text={capText} />}
              {bandText && <DrillFilterBand text={bandText} />}
            </>
            : undefined}
          onClose={onClose}
        />
      </Suspense>
      {exportOpen && exportButtonRef.current && (
        <AnchoredOverlay
          anchor={exportButtonRef.current}
          className="sheet-cell-export-pop"
          placement="bottom-end"
          onDismiss={() => setExportOpen(false)}
          role="menu"
          ariaLabel="Export matching records"
          dataKind="sheet-cell-export"
        >
          {(["csv", "xlsx", "pdf", "json"] as const).map((format) => (
            <button
              type="button"
              role="menuitem"
              className="sheet-cell-export-choice"
              onClick={() => { void exportCell(format); }}
              key={format}
            >
              {format === "xlsx" ? "Excel" : format === "pdf" ? "PDF" : format.toUpperCase()}
            </button>
          ))}
        </AnchoredOverlay>
      )}
    </OverlayProvider>
  );
}