File size: 68,672 Bytes
4b54047
 
dcd43e2
e9a4c3e
 
dcd43e2
bdac669
e9a4c3e
4b54047
dcd43e2
e9a4c3e
 
a83fcff
4b54047
 
e9a4c3e
cfd4ac1
bdac669
e13472e
e9a4c3e
 
4b54047
 
 
 
a83fcff
dcd43e2
 
 
 
a83fcff
e13472e
dcd43e2
 
 
a83fcff
4b54047
a83fcff
e9a4c3e
 
4b54047
a83fcff
e9a4c3e
a83fcff
 
4b54047
a83fcff
 
 
 
 
 
 
 
 
 
 
 
4b54047
a83fcff
4b54047
a83fcff
 
 
4b54047
 
 
a83fcff
 
4b54047
 
 
 
 
 
 
a83fcff
 
4b54047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
4b54047
 
a83fcff
4b54047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
4b54047
 
 
bdac669
992a41f
bdac669
992a41f
 
 
 
 
 
 
 
4b54047
992a41f
 
 
4b54047
992a41f
4b54047
bdac669
 
 
 
 
 
 
 
 
4b54047
 
 
 
 
 
 
 
bdac669
 
 
 
 
 
 
4b54047
 
 
992a41f
4b54047
 
a83fcff
4b54047
 
 
 
a83fcff
4b54047
 
bdac669
 
4b54047
 
 
 
 
 
 
bdac669
4b54047
 
 
 
bdac669
4b54047
 
 
 
 
 
 
 
 
cfd4ac1
4b54047
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
4b54047
 
 
 
 
 
 
 
cfd4ac1
bdac669
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
 
 
 
 
 
cfd4ac1
4b54047
 
bdac669
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
 
 
 
 
 
cfd4ac1
 
dcd43e2
 
 
bdac669
dcd43e2
 
 
bdac669
 
dcd43e2
 
 
4b54047
 
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
dcd43e2
 
4b54047
 
 
dcd43e2
bdac669
 
 
dcd43e2
4b54047
bdac669
4b54047
 
 
 
 
bdac669
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
 
 
 
 
dcd43e2
4b54047
 
 
dcd43e2
 
4b54047
 
 
 
 
 
 
 
bdac669
4b54047
dcd43e2
 
 
 
 
 
 
 
4b54047
 
 
dcd43e2
4b54047
 
bdac669
4b54047
 
bdac669
4b54047
 
 
 
 
bdac669
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
 
 
 
 
 
9a6cb9a
4b54047
 
 
9a6cb9a
4b54047
 
 
 
9a6cb9a
4b54047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
4b54047
 
 
 
9a6cb9a
4b54047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
 
 
4b54047
 
 
 
 
 
 
9a6cb9a
 
4b54047
 
9a6cb9a
4b54047
9a6cb9a
4b54047
 
 
 
 
 
 
 
 
9a6cb9a
 
 
 
 
 
 
 
4b54047
 
 
 
 
 
 
 
dcd43e2
4b54047
 
 
 
 
 
dcd43e2
4b54047
 
bdac669
 
4b54047
 
dcd43e2
bdac669
4b54047
 
 
 
 
 
 
 
bdac669
4b54047
 
 
bdac669
4b54047
 
bdac669
 
 
 
 
 
4b54047
dcd43e2
4b54047
dcd43e2
4b54047
 
bdac669
 
 
 
 
 
 
 
 
4b54047
 
 
dcd43e2
 
cfd4ac1
dcd43e2
 
 
4b54047
bdac669
 
4b54047
9a6cb9a
4b54047
cfd4ac1
4b54047
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
cfd4ac1
4b54047
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b54047
 
bdac669
cfd4ac1
e13472e
cfd4ac1
 
4b54047
 
 
cfd4ac1
 
a83fcff
e13472e
dcd43e2
cfd4ac1
4b54047
 
 
a83fcff
e9a4c3e
4b54047
 
 
 
 
 
 
 
cfd4ac1
a83fcff
 
 
 
 
 
 
dcd43e2
a83fcff
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcd43e2
cfd4ac1
 
 
 
 
a83fcff
 
 
 
 
 
 
 
dcd43e2
a83fcff
cfd4ac1
dcd43e2
 
 
 
 
cfd4ac1
 
 
 
 
a83fcff
cfd4ac1
 
a83fcff
 
dcd43e2
 
 
 
 
 
cfd4ac1
 
 
a83fcff
cfd4ac1
 
 
 
a83fcff
 
dcd43e2
 
 
 
 
 
a83fcff
 
 
dcd43e2
 
cfd4ac1
a83fcff
 
 
 
 
 
 
 
 
 
cfd4ac1
dcd43e2
cfd4ac1
 
 
 
 
dcd43e2
cfd4ac1
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
dcd43e2
cfd4ac1
e13472e
cfd4ac1
 
 
 
 
e13472e
 
4b54047
e13472e
 
a83fcff
cfd4ac1
 
 
a83fcff
cfd4ac1
 
 
 
 
 
 
 
 
a83fcff
 
 
 
4b54047
a83fcff
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcd43e2
cfd4ac1
dcd43e2
cfd4ac1
dcd43e2
 
 
 
cfd4ac1
 
a83fcff
dcd43e2
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
e13472e
 
 
4b54047
e13472e
4b54047
e9a4c3e
 
 
e13472e
 
 
e9a4c3e
4b54047
cfd4ac1
e9a4c3e
 
 
 
 
 
 
cfd4ac1
 
e13472e
 
 
 
4b54047
bdac669
dcd43e2
4b54047
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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
// Sheet charts read cells only. Source, presentation and destination are persisted independently.
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import type { ReactNode, CSSProperties, MouseEvent } from "react";
import type { WireField } from "../viz/seriesData";
import type { Row } from "../viz/types";
import type { CellMap, SheetChartRange, SheetChartSpec, SheetChartPresentation, SheetChartColor, ChartAxisFormat } from "./types";
import { defaultChartPresentation, SHEET_CHART_STACKING_KINDS } from "./types";
import { addressOf } from "./sheetState";
import "../styles/wave58/sheet.css";
import "../styles/wave59/chart-dialog.css";

export interface SheetChartProps {
  range: SheetChartRange;
  source?: SheetChartSpec["source"];
  presentation?: SheetChartPresentation;
  cells: CellMap;
  kind?: SheetChartSpec["kind"];
  stacking?: SheetChartSpec["stacking"];
  selected?: boolean;
  width: number;
  height: number;
  /** R3: all frozen-pane projections share one gesture preview. */
  preview?: ChartPreview;
  onPreviewChange?: (preview: ChartPreview) => void;
  moveSteps?: { left: number; right: number; up: number; down: number };
  onMove?: (dx: number, dy: number) => ChartAnchorDelta;
  /** `ratio` is present ONLY when the gesture must keep the shape (Shift, or Lock aspect ratio).
   *  It has to travel with the delta because the anchor snaps to a cell boundary AFTER the delta is
   *  computed, and only the receiver knows how much the size had to absorb. */
  onResize?: (delta: ChartPreview, ratio?: number) => ChartAnchorDelta;
  onEdit?: () => void;
  onDelete?: () => void;
  /** Present only on the sheet. Absent in exports, thumbnails and the editor preview, which render
   *  the same component through `renderToStaticMarkup` where an input would be dead markup. */
  onRetitle?: (key: "title" | "xTitle" | "yTitle", value: string) => void;
}
export interface ChartAnchorDelta { dx: number; dy: number }

const textAt = (cells: CellMap, col: number, row: number): string => {
  const cell = cells[addressOf(col, row)];
  if (!cell || cell.state === "refused") return "";
  return cell.display ?? (cell.value == null ? (cell.text ?? "") : String(cell.value));
};
const numberAt = (cells: CellMap, col: number, row: number): number | null => {
  const cell = cells[addressOf(col, row)];
  if (!cell || cell.state === "refused" || cell.state === "stale") return null;
  const raw = cell.value ?? cell.text ?? cell.display;
  if (typeof raw === "number") return Number.isFinite(raw) ? raw : null;
  if (typeof raw !== "string") return null;
  let text = raw.trim();
  if (!text) return null;
  const negative = text.startsWith("(") && text.endsWith(")");
  if (negative) text = text.slice(1, -1).trim();
  const percent = text.endsWith("%");
  if (percent) text = text.slice(0, -1).trim();
  text = text.replace(/[,\s]/g, "").replace(/^([$€£])/, "");
  if (!/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(text)) return null;
  const value = Number(text);
  return Number.isFinite(value) ? (negative ? -value : value) / (percent ? 100 : 1) : null;
};
interface ChartCellValue { text: string; number: number | null; col: number; row: number }
export interface SheetChartData {
  fields: WireField[];
  rows: Row[];
  series: { y: string; label: string; color?: SheetChartColor; sourceKey?: string }[];
  error?: string;
  dateAxis?: boolean;
}

/** Date-formatted Sheet numbers use epoch milliseconds; a timeline uses Excel days. */
const timelineDate = (cell: CellMap[string] | undefined): number | null => {
  if (!cell || cell.state === "refused" || cell.state === "stale") return null;
  const raw = cell.value ?? cell.text;
  const ms = typeof raw === "number" && cell.style?.format?.kind === "date" ? raw
    : typeof raw === "string" && /^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(raw) ? Date.parse(raw) : NaN;
  return Number.isFinite(ms) ? ms / 86400000 + 25569 : null;
};

/** Fixed-role families refuse missing or impossible inputs instead of drawing a different chart. */
export function chartShapeError(kind: SheetChartSpec["kind"], data: SheetChartData, p: SheetChartPresentation = {}): string | undefined {
  if (kind !== "stock" && kind !== "gantt") return undefined;
  const count = data.series.length;
  if (kind === "stock" && count !== 3 && count !== 4)
    return "Stock needs High, Low, Close series, with optional Open first.";
  if (kind === "gantt" && count !== 2) return "Gantt needs a start series and a duration or end series.";
  if (!data.rows.length) return "Choose at least one complete data row.";
  for (const row of data.rows) {
    const values = data.series.map(s => readNumber(row, s.y));
    if (values.some(v => v === null)) return "Every chart row needs all of its numeric values.";
    const nums = values as number[];
    if (kind === "stock") {
      const [high, low, close] = nums.slice(count === 4 ? 1 : 0);
      const open = count === 4 ? nums[0] : close;
      if (low > high || Math.min(open, close) < low || Math.max(open, close) > high)
        return "Stock values must keep Open and Close between Low and High.";
    } else if (p.ganttMode === "end" ? nums[1] < nums[0] : nums[1] < 0) {
      return "A task must end on or after its start and have a nonnegative duration.";
    } else if (!Number.isFinite(p.ganttMode === "end" ? nums[1] : nums[0] + nums[1])) {
      return "Task dates must remain within the numeric range.";
    }
  }
  return undefined;
}

/** Disjoint columns join by row; disjoint rows join by column. Ambiguous rectangles are refused. */
export function chartDataForRange(
  cells: CellMap, range: SheetChartRange, presentation: SheetChartPresentation = {},
  ranges: SheetChartRange[] = [range], kind: SheetChartSpec["kind"] = "column",
): SheetChartData {
  const empty = (error?: string): SheetChartData => ({ fields: [], rows: [], series: [], error });
  if (!ranges.length) return empty("Choose a data range.");
  if (ranges.reduce((n, r) => n + (Math.abs(r.col1-r.col0)+1)*(Math.abs(r.row1-r.row0)+1), 0) > 50000)
    return empty("Choose at most 50,000 source cells.");
  const blocks = ranges.map(r => {
    const block: ChartCellValue[][] = [];
    for (let row = Math.min(r.row0,r.row1); row <= Math.max(r.row0,r.row1); row++) {
      const line: ChartCellValue[] = [];
      for (let col = Math.min(r.col0,r.col1); col <= Math.max(r.col0,r.col1); col++)
        line.push({ col, row, text: textAt(cells,col,row), number: (kind === "gantt" ? timelineDate(cells[addressOf(col,row)]) : null) ?? numberAt(cells,col,row) });
      block.push(line);
    }
    return block;
  });
  let matrix = blocks[0];
  if (blocks.length > 1) {
    const sameRows = ranges.every(r => Math.min(r.row0,r.row1) === Math.min(ranges[0].row0,ranges[0].row1)
      && Math.max(r.row0,r.row1) === Math.max(ranges[0].row0,ranges[0].row1));
    const sameCols = ranges.every(r => Math.min(r.col0,r.col1) === Math.min(ranges[0].col0,ranges[0].col1)
      && Math.max(r.col0,r.col1) === Math.max(ranges[0].col0,ranges[0].col1));
    if (sameRows) matrix = matrix.map((_, i) => blocks.flatMap(b => b[i]));
    else if (sameCols) matrix = blocks.flat();
    else return empty("Separate ranges must share the same rows or columns.");
    const addresses = matrix.flat().map(v => addressOf(v.col,v.row));
    if (new Set(addresses).size !== addresses.length) return empty("Source ranges must not overlap.");
  }
  if (presentation.orientation === "rows") matrix = matrix[0].map((_, c) => matrix.map(r => r[c]));
  if (!matrix.length || !matrix[0].length) return empty();
  // A lone row is a numeric run, retaining the legacy one-row selection behavior.
  if (matrix.length === 1 && !["sunburst", "boxWhisker"].includes(kind)) matrix = matrix[0].map(v => [v]);
  // [W59-T06] Labels above one numeric run become categories; blanks retain missing values.
  const headerRowCategories = !["stock", "gantt", "scatter", "bubble", "sunburst", "boxWhisker"].includes(kind)
    && (presentation.headers ?? "auto") !== "none"
    && (presentation.categoryLabels ?? "auto") === "auto"
    && (presentation.orientation ?? "columns") === "columns"
    && matrix.length === 2 && matrix[0].length > 1
    && matrix[0].every(v => v.text.trim() && v.number === null)
    && matrix[1].some(v => v.number !== null)
    && matrix[1].every(v => v.number !== null || !v.text.trim());
  if (headerRowCategories) matrix = matrix[0].map((_, c) => matrix.map(r => r[c]));
  const first = matrix[0];
  const numericHeaderCols = first.map((_, c) => c).filter(c => matrix.slice(1).some(r => r[c].number !== null));
  // [W59-T06] Auto headers have no numbers in value columns; a rotated header is already categories.
  const header = !headerRowCategories && (presentation.headers === "firstRow" || (presentation.headers !== "none"
    && first.some(v => v.text.trim() && v.number === null)
    && numericHeaderCols.length > 0 && numericHeaderCols.every(c => first[c].number === null)));
  const body = matrix.slice(header ? 1 : 0);
  // W61-T07: after the optional header and orientation, Sunburst takes exactly three
  // columns: parent text, child text, numeric value. Both levels are derived from cells,
  // never stored on the chart spec. Trailing blank rows are harmless; partial rows refuse.
  if (kind === "sunburst") {
    while (body.length && body[body.length-1].every(v => !v.text.trim() && v.number === null)) body.pop();
    if (first.length !== 3 || !body.length || body.some(line =>
      line[0].number !== null || !line[0].text.trim() || line[1].number !== null || !line[1].text.trim() || line[2].number === null))
      return empty("Sunburst needs two text category columns followed by one numeric value column.");
  }
  if (!body.length) return empty();
  const numericCols = first.map((_, c) => c).filter(c => body.some(r => r[c].number !== null));
  const xy = kind === "scatter" || kind === "bubble";
  const categoryCol = presentation.categoryLabels === "firstColumn" ? 0
    : presentation.categoryLabels === "none" ? null
    : (kind === "stock" && first.length >= 4) || (kind === "gantt" && first.length >= 3) ? 0
    : xy && numericCols.length >= 2 ? numericCols[0]
    : first.length > 1 && !numericCols.includes(0) ? 0 : null;
  // Box and whisker takes one sample per numeric column (or row after Switch row/column),
  // with an optional leading category column. Blanks are missing samples, never zeros;
  // text in a value column refuses. Keep every series separate: folding into Other would
  // invent a different distribution. The renderer requires five values in each visible series.
  const valueCols = (kind === "boxWhisker" ? first.map((_, c) => c) : numericCols).filter(c => c !== categoryCol);
  if (kind === "boxWhisker" && body.some(line => valueCols.some(c => line[c].number === null && line[c].text.trim())))
    return empty("Box and whisker needs numeric value columns; blanks are allowed.");
  if (!valueCols.length) return empty(["stock", "gantt"].includes(kind) ? "Choose numeric chart values." : undefined);
  let series = valueCols.map(c => ({
    y: `value${c}`,
    sourceKey: presentation.orientation === "rows" || headerRowCategories ? `row:${first[c].row+1}` : `column:${addressOf(first[c].col,0).replace(/[0-9]+$/, "")}`,
    label: header ? first[c].text || addressOf(first[c].col,first[c].row) : addressOf(first[c].col,first[c].row).replace(/[0-9]+$/, ""),
    color: undefined as SheetChartColor | undefined,
  }));
  const configured = presentation.series ?? [];
  const ordered = configured.flatMap(setting => {
    const found = series.find(s => s.sourceKey === setting.key || s.y === setting.key);
    return found && !setting.hidden ? [{ ...found, label: setting.label || found.label, color: setting.color }] : [];
  });
  series = [...ordered, ...series.filter(s => !configured.some(c => c.key === s.sourceKey || c.key === s.y))];
  const rawSeries = series;
  const folded = kind === "boxWhisker" ? [] : rawSeries.slice(8);
  series = kind === "boxWhisker" ? rawSeries : rawSeries.slice(0,8);
  if (folded.length) series.push({ y: "other", sourceKey: "other", label: "Other", color: undefined });
  const lastFilled = body.reduce((last, line, i) => line.some(value => value.text.trim() !== "" || value.number !== null) ? i : last, -1);
  const rows = body.slice(0, lastFilled + 1).map((line, i) => {
    const result: Record<string, unknown> = { pid: i+1,
      category: categoryCol === null ? addressOf(line[0].col,line[0].row)
        : xy ? line[categoryCol].number : line[categoryCol].text || addressOf(line[categoryCol].col,line[categoryCol].row) };
    valueCols.forEach(c => { result[`value${c}`] = line[c].number; });
    if (kind === "sunburst") { result.category = line[0].text.trim(); result.child = line[1].text.trim(); }
    if (folded.length) result.other = folded.reduce((sum,s) => sum + Number(result[s.y] ?? 0),0);
    return result as unknown as Row;
  });
  const fields: WireField[] = [{ key: "category", label: presentation.categoryTitle || (categoryCol !== null && header ? first[categoryCol].text : "Cell"), type: xy ? "int" : "text" },
    ...(kind === "sunburst" ? [{ key: "child", label: header ? first[1].text : "Child", type: "text" as const }] : []),
    ...series.map(s => ({ key: s.y, label: s.label, type: "int" as const }))];
  if (xy && categoryCol === null) return empty("Choose a numeric X column and a numeric Y column.");
  const dateAxis = kind === "gantt" && body.some(line => valueCols.some(c => timelineDate(cells[addressOf(line[c].col,line[c].row)]) !== null));
  const result = { fields, rows, series, ...(dateAxis ? { dateAxis: true } : {}) };
  return { ...result, error: chartShapeError(kind, result, presentation) };
}
const readNumber = (row: Row, key: string): number | null => {
  const value = (row as unknown as Record<string, unknown>)[key];
  return typeof value === "number" && Number.isFinite(value) ? value : null;
};
const readText = (row: Row, key: string): string => String((row as unknown as Record<string,unknown>)[key] ?? "");
/** Percent display units and axis format scale once; other units compose with the format. */
const axisText = (v: number, units: SheetChartPresentation["displayUnits"] = "none",
                  axis: ChartAxisFormat = {}): string => {
  const percent = axis.format === "percent" || units === "percent";
  const scale = percent ? 100 : units === "thousands" ? 1e-3 : units === "millions" ? 1e-6 : 1;
  const suffix = percent ? "%" : units === "thousands" ? "k" : units === "millions" ? "M" : "";
  const n = v * scale;
  const decimals = typeof axis.decimals === "number"
    ? Math.max(0, Math.min(6, Math.round(axis.decimals))) : null;
  const currency = axis.format === "currency";
  const options: Intl.NumberFormatOptions = {
    useGrouping: axis.thousands !== false,
    ...(currency ? { style: "currency", currency: "USD" } : {}),
    // ⛔ CURRENCY WITH AUTO DECIMALS IS PINNED TO TWO, and it is pinned here because Excel cannot
    // say "up to two, trimmed": a format code either always shows the cents or never does. Two on
    // both sides is the only setting where the tick on the sheet and the tick in the exported
    // workbook read the same. An explicit decimal count still wins.
    ...(decimals === null
      ? (currency
        ? { minimumFractionDigits: 2, maximumFractionDigits: 2 }
        : { maximumFractionDigits: 2, notation: Math.abs(n) >= 10000 ? "compact" as const : "standard" as const })
      : { minimumFractionDigits: decimals, maximumFractionDigits: decimals }),
  };
  return new Intl.NumberFormat("en", options).format(n) + suffix;
};
export function histogramBins(values: number[], count: number) {
  if (!values.length) return [];
  const low = Math.min(...values), high = Math.max(...values);
  const n = low === high ? 1 : Math.max(1, Math.min(50, Math.round(count) || 10));
  const step = low === high ? 1 : (high-low)/n;
  const bins = Array.from({length:n}, (_, i) => ({ low:low+i*step, high:low+(i+1)*step, count:0 }));
  values.forEach(v => { bins[Math.min(n-1,Math.max(0,Math.floor((v-low)/step)))].count++; });
  return bins;
}
/** W61-T07: linear interpolation at (n - 1) * p, Excel QUARTILE.INC.
 * Whiskers end at observed samples within 1.5 * IQR, not at the fences themselves. */
export function boxWhiskerStats(values: number[]) {
  const sorted = values.filter(Number.isFinite).sort((a,b) => a-b);
  if (sorted.length < 5) return null;
  const quartile = (p: number) => {
    const index = (sorted.length - 1) * p, lo = Math.floor(index), fraction = index-lo;
    return sorted[lo] * (1-fraction) + sorted[Math.min(lo+1,sorted.length-1)] * fraction;
  };
  const q1 = quartile(.25), median = quartile(.5), q3 = quartile(.75), iqr = q3-q1;
  const inside = sorted.filter(value => value >= q1-1.5*iqr && value <= q3+1.5*iqr);
  return { q1, median, q3, low: inside[0], high: inside[inside.length-1],
    outliers: sorted.filter(value => value < q1-1.5*iqr || value > q3+1.5*iqr) };
}
export function chartYDomain(values: number[], p: SheetChartPresentation): [number,number] {
  let low = p.yMin ?? Math.min(0,...values), high = p.yMax ?? Math.max(0,...values);
  if (low >= high) {
    if (p.yMin !== undefined && p.yMax === undefined) high = low + Math.max(1, Math.abs(low)*.1);
    else if (p.yMax !== undefined && p.yMin === undefined) low = high - Math.max(1, Math.abs(high)*.1);
    else if (low === high) high = low+1;
  }
  return [low,high];
}
const PURPLE = ["purple"] as const;
// ⭐ THE ORDER IS MEASURED, NOT CHOSEN. The dataviz validator scores ADJACENT pairs, and
// pink beside red answered deltaE 8.5 under normal vision, below the 15 floor. This order is
// the best of all 40,320 permutations of the same eight hexes: deltaE 15.4 normal and 9.7
// deuteranopia, both PASS, with no hue re-stepped. Re-ordering it needs a re-run, not a view.
export const CATEGORICAL = ["purple","green","blue","yellow","pink","orange","teal","red"] as const;
export type ChartSeriesHue = SheetChartColor | typeof CATEGORICAL[number];
// Keep explicit saved Purple presentations intact while the shared types seam is integrated.
export const chartPresentationDefaults = (): SheetChartPresentation => ({...defaultChartPresentation(), palette: "categorical"});
export const colorStyle = (slot: number, p: SheetChartPresentation, color?: ChartSeriesHue): CSSProperties => {
  const hue = color || (p.palette === "blue" ? "blue" : p.palette === "purple"
    ? PURPLE[slot % PURPLE.length] : CATEGORICAL[slot % CATEGORICAL.length]);
  return {
    "--chart-color": `var(--lp-${hue}${hue === "muted" ? "" : "-deep"})`,
    "--chart-fill": `var(--lp-${hue}${p.style === "soft" && hue !== "muted" ? "-tint" : ""})`,
    "--chart-opacity": !p.palette || p.palette === "categorical" || color ? 1 : Math.max(.42,1-slot*.07),
  } as CSSProperties;
};
const short = (value: string, max=20) => value.length > max ? `${value.slice(0,Math.max(1,max-1))}…` : value;
const slicePath = (cx:number,cy:number,r:number,inner:number,from:number,sweep:number):string => {
  const to=from+Math.min(sweep,Math.PI*2-1e-7), big=sweep>Math.PI?1:0;
  const pt=(radius:number,angle:number)=>`${cx+radius*Math.cos(angle)} ${cy+radius*Math.sin(angle)}`;
  if (!inner) return `M ${cx} ${cy} L ${pt(r,from)} A ${r} ${r} 0 ${big} 1 ${pt(r,to)} Z`;
  return `M ${pt(r,from)} A ${r} ${r} 0 ${big} 1 ${pt(r,to)} L ${pt(inner,to)} A ${inner} ${inner} 0 ${big} 0 ${pt(inner,from)} Z`;
};

/** How many entries a chart's legend carries: categories for the round kinds, one for the kinds
 *  whose legend is a single curated entry, series otherwise. One entry is not a legend. */
export const chartLegendEntries = (kind: SheetChartSpec["kind"], seriesCount: number, rowCount: number): number =>
  kind==="pie"||kind==="donut"||kind==="polar"||kind==="treemap"||kind==="sunburst" ? rowCount
  : kind==="gantt"||kind==="bubble" ? 1
  : seriesCount;

export function DrawnChart({ kind, stacking, rows, series, error: dataError, dateAxis, presentation = {}, width = 640, height = 320, onRetitle }: SheetChartData & {
  kind: SheetChartSpec["kind"]; stacking?: SheetChartSpec["stacking"]; presentation?: SheetChartPresentation; width?:number; height?:number;
  /** Present only on the sheet. Absent in exports, thumbnails and the editor preview, which render
   *  the same component through `renderToStaticMarkup` where an input would be dead markup. */
  onRetitle?: (key: "title" | "xTitle" | "yTitle", value: string) => void;
}) {
  const id=useId().replace(/:/g,"");
  const drawingRef = useRef<HTMLDivElement>(null);
  const [renaming, setRenaming] = useState<{ key: "title" | "xTitle" | "yTitle"; value: string;
    left: number; top: number; width: number; height: number } | null>(null);
  /** Measure, do not convert. The axis titles live in the SVG's own viewBox units, so hand written
   *  viewBox-to-pixel maths breaks when the chart is resized. Both rects below are real screen
   *  pixels and the browser has already applied every transform. */
  const beginRename = (key: "title" | "xTitle" | "yTitle", value: string) => (event: { currentTarget: Element; stopPropagation: () => void; preventDefault: () => void }) => {
    if (!onRetitle) return;
    event.stopPropagation(); event.preventDefault();
    const host = drawingRef.current?.getBoundingClientRect();
    const box = event.currentTarget.getBoundingClientRect();
    if (!host) return;
    setRenaming({ key, value, left: box.left - host.left, top: box.top - host.top,
      width: Math.max(96, box.width), height: Math.max(20, box.height) });
  };
  const p={...chartPresentationDefaults(),...presentation};
  const W=Math.max(240,width-24), H=Math.max(120,height-24-(p.title?32:0)-((chartLegendEntries(kind,series.length,rows.length)>=2)?44:0));
  const direct = series.length>=2 && series.length<=4 && ["bar","column","line","area","combo"].includes(kind);
  const L=p.layout==="compact"?48:72, R=kind==="gantt"&&p.showDataLabels?96:20, T=16+(direct?series.length*18:0), B=(p.showAxisTitles&&(p.xTitle||p.categoryTitle)?52:36)+(p.layout==="labels"?16:0);
  const right=W-R, bottom=H-B, pw=right-L, ph=bottom-T;
  const names=rows.map(r=>readText(r,"category"));
  const valueAxis = p.valueAxis ?? {}, categoryAxis = p.categoryAxis ?? {};
  const stacked = SHEET_CHART_STACKING_KINDS.includes(kind) && (stacking === "stacked" || stacking === "percent");
  const percentStack = stacked && stacking === "percent";
  const fmt=(n:number)=>percentStack ? axisText(n,"percent",{...valueAxis,format:"percent"}) : axisText(n,p.displayUnits,valueAxis);
  const catFmt=(n:number)=>axisText(n,p.displayUnits,categoryAxis);
  const nodes: ReactNode[]=[];
  let legend: (SheetChartData["series"][number] & { slot?: number })[]=series.map(s=>({...s}));
  let error="";
  const one=series[0];
  const vals=rows.map(r=>readNumber(r,one?.y??""));
  const valid=vals.filter((v):v is number=>v!==null);
  const all=series.flatMap(s=>rows.map(r=>readNumber(r,s.y)).filter((v):v is number=>v!==null));
  const stacks = stacked ? rows.map(row => {
    const values = series.map(s => readNumber(row,s.y));
    const total = values.reduce<number>((sum,v) => sum+(v??0),0);
    // A zero-total category in percent mode draws nothing, never NaN geometry. Mixed signs
    // use the sum of magnitudes so each share retains its sign and absolute shares sum to 100%.
    const divisor = percentStack ? values.reduce<number>((sum,v) => sum+Math.abs(v??0),0) : 1;
    let positive = 0, negative = 0;
    return values.map(raw => {
      if (raw === null || (percentStack && total === 0)) return null;
      const value = raw/divisor;
      const from = value < 0 ? negative : positive;
      const to = from+value;
      if (value < 0) negative = to; else positive = to;
      return { from, to, value };
    });
  }) : null;
  const domainValues = stacks ? stacks.flatMap(row => row.flatMap(s => s ? [s.from,s.to] : [])) : all;
  const [low,high]=chartYDomain(percentStack
    ? [domainValues.some(v=>v<0)?-1:0,domainValues.some(v=>v>0)||!domainValues.some(v=>v<0)?1:0]
    : domainValues,p);
  const inValueBounds=(v:number)=>v>=low&&v<=high;
  const y=(v:number)=>bottom-(v-low)/(high-low)*ph;
  const x=(i:number)=>L+(i+.5)*pw/Math.max(1,rows.length);
  const clamp=(v:number,a:number,b:number)=>Math.max(a,Math.min(b,v));
  const mark=(slot:number,color?:SheetChartColor)=>({className:`sheet-chart-mark style-${p.style}`,style:colorStyle(slot,p,color)});
  const title=(label:string,value:number)=><title>{`${label}: ${fmt(value)}`}</title>;
  const label=(key:string,text:string,px:number,py:number,anchor:"start"|"middle"|"end"="middle",role?:string,onPick?: (event: MouseEvent<SVGTextElement>) => void,angle?:number)=> {
    const shown=short(text,Math.min(24,Math.floor((W-8)/10))), span=shown.length*(p.axisFont==="large"?10:8);
    const low=anchor==="start"?4:anchor==="middle"?4+span/2:4+span;
    const high=anchor==="end"?W-4:anchor==="middle"?W-4-span/2:W-4-span;
    const labelX=clamp(px,low,high), labelY=clamp(py,16,H-6);
    return <text key={key} data-label={role} className="sheet-chart-label-svg" x={labelX} y={labelY} transform={typeof angle === "number" && angle !== 0 ? `rotate(${angle} ${labelX} ${labelY})` : undefined} textAnchor={anchor} onClick={onPick} style={onPick ? { cursor: "text" } : undefined}>{shown}<title>{text}</title></text>;
  };
  const ticks=(a:number,b:number,major?:number)=>{
    const step=major&&major>0?major:(b-a)/4;
    const start=Math.ceil(a/step)*step;
    return Array.from({length:Math.min(100,Math.max(0,Math.floor((b-start)/step)+1))},(_,i)=>start+i*step);
  };
  const axes=(domain:[number,number]=[low,high], horizontal=false, tickText=fmt)=>{
    const [a,b]=domain, yy=(v:number)=>bottom-(v-a)/(b-a)*ph, xx=(v:number)=>L+(v-a)/(b-a)*pw;
    const major=p.yMajor??(percentStack ? .25 : horizontal&&dateAxis?(b-a)/Math.max(1,Math.floor(pw/110)):undefined);
    return <g className="sheet-chart-axes" clipPath={`url(#${id}-frame)`}>
      {valueAxis.gridlines !== false ? ticks(a,b,p.yMinor).filter(v=>p.yMinor&&v>a&&v<b).map((v,i)=><line key={`m${i}`} className="sheet-chart-grid minor" x1={horizontal?xx(v):L} x2={horizontal?xx(v):right} y1={horizontal?T:yy(v)} y2={horizontal?bottom:yy(v)}/>) : null}
      {ticks(a,b,major).map((v,i)=><g key={i}>{valueAxis.gridlines !== false ? <line className="sheet-chart-grid" x1={horizontal?xx(v):L} x2={horizontal?xx(v):right} y1={horizontal?T:yy(v)} y2={horizontal?bottom:yy(v)}/> : null}
        {label(`v${i}`,tickText(v),horizontal?xx(v):L-8,horizontal?bottom+20:yy(v)+4,horizontal?"middle":"end",undefined,undefined,valueAxis.labelAngle)}</g>)}
      {categoryAxis.gridlines === true && !horizontal
        ? rows.map((_,i)=><line key={`cg${i}`} className="sheet-chart-grid" x1={x(i)} x2={x(i)} y1={T} y2={bottom}/>)
        : null}
      {p.showAxisTitles&&(p.xTitle||p.categoryTitle)?label("xt",p.xTitle||p.categoryTitle||"",(L+right)/2,H-6,"middle","axis-title",onRetitle ? beginRename("xTitle", p.xTitle || p.categoryTitle || "") : undefined):null}
      {p.showAxisTitles&&p.yTitle?<text className="sheet-chart-label-svg" transform={`translate(14 ${(T+bottom)/2}) rotate(-90)`} textAnchor="middle" onClick={onRetitle ? beginRename("yTitle", p.yTitle ?? "") : undefined} style={onRetitle ? { cursor: "text" } : undefined}>{short(p.yTitle,24)}</text>:null}
    </g>;
  };
  const categoryLabels=(horizontal=false)=>names.map((name,i)=>i%Math.max(1,Math.ceil(names.length/(horizontal?8:Math.max(2,Math.floor(pw/72)))))===0
    ?label(`c${i}`,short(name,horizontal?9:Math.max(5,Math.floor(pw/Math.min(names.length,6)/8))),horizontal?L-8:x(i),horizontal?T+(i+.5)*ph/names.length+4:bottom+20,horizontal?"end":"middle",undefined,undefined,categoryAxis.labelAngle):null);
  const shapeError = chartShapeError(kind, { rows, series, fields: [] }, p);
  if (dataError || shapeError) error=dataError || shapeError || "";
  else if (!["bar","column","line","area","pie","donut","scatter","combo","waterfall","histogram","bubble","bullet","funnel","gauge","polar","radar","treemap","stock","gantt","sunburst","boxWhisker"].includes(kind)) error="That chart kind is not supported.";
  else if (p.yMin!==undefined&&p.yMax!==undefined&&p.yMin>=p.yMax) error="The Y maximum must exceed the minimum.";
  else if (!series.length||!rows.length) error="This range has no numeric values to chart.";
  else if (["pie","donut","funnel","treemap","polar","waterfall","histogram","gauge","sunburst"].includes(kind)&&series.length!==1)
    error="Select one visible series for this chart type.";
  else if (["pie","donut","funnel","treemap","polar","radar"].includes(kind)&&all.some(v=>v<0))
    error="This chart type needs nonnegative values.";
  else if (["pie","donut","funnel","treemap","polar"].includes(kind)&&valid.reduce((a,b)=>a+b,0)<=0)
    error="This chart type needs a positive total.";
  else if (kind === "sunburst" && rows.some(row => typeof row.category !== "string"
    || typeof (row as unknown as Record<string,unknown>).child !== "string"
    || !readText(row,"category").trim() || !readText(row,"child").trim() || readNumber(row,one.y) === null))
    error="Sunburst needs two text category columns followed by one numeric value column.";
  else if (kind === "sunburst" && !valid.some(value => value > 0))
    error="Sunburst excludes zero and negative values; choose at least one positive value.";
  else if (kind === "sunburst" && !Number.isFinite(valid.reduce((sum,value) => sum+Math.max(0,value),0)))
    error="Sunburst needs a finite positive total.";
  else if (kind === "boxWhisker") {
    const shortSeries = series.find(s => rows.filter(row => readNumber(row,s.y) !== null).length < 5);
    if (shortSeries) error=`Box and whisker needs at least five numeric values in ${shortSeries.label}.`;
  }
  if (!error && kind === "sunburst") {
    const parents = new Map<string, Map<string, number>>();
    rows.forEach(row => {
      const value = readNumber(row,one.y)!;
      if (value <= 0) return;
      const parent = readText(row,"category"), child = readText(row,"child");
      if (!parents.has(parent)) parents.set(parent,new Map());
      const children = parents.get(parent)!;
      children.set(child,(children.get(child) ?? 0)+value);
    });
    // Scale before summing so very large finite source values still produce finite angles.
    const weightScale = Math.max(...valid);
    const groups = [...parents].map(([name,children]) => ({ name, children: [...children],
      weight: [...children.values()].reduce((sum,value) => sum+value/weightScale,0) }));
    const total = groups.reduce((sum,group) => sum+group.weight,0);
    const radius = Math.max(16,Math.min(pw,ph)/2-8), cx=(L+right)/2, cy=(T+bottom)/2;
    let angle=-Math.PI/2;
    legend=[];
    const arc = (key:string,name:string,value:number,slot:number,level:number,from:number,sweep:number) => {
      const inner=radius*(level===1?.18:.58), outer=radius*(level===1?.58:1), middle=(inner+outer)/2;
      nodes.push(<path key={key} {...mark(slot,one.color)} style={{...colorStyle(slot,{...p,style:"soft"},one.color),fill:"var(--chart-fill)",stroke:"var(--chart-color)"}}
        data-mark="sunburst" data-level={level} data-name={name} data-start={from} data-sweep={sweep}
        d={slicePath(cx,cy,outer,inner,from,sweep)}>{title(name,value)}</path>);
      // A tangent label must fit both the annular width and the angular span. Never truncate
      // into an ambiguous category or let the glyph corners cross a neighbouring arc.
      const textWidth=name.length*(p.axisFont==="large"?10:8), textHeight=p.axisFont==="large"?20:16;
      const fits=Math.hypot(middle+textHeight/2,textWidth/2)<outer-3
        && middle-textHeight/2>inner+3 && 2*Math.atan2(textWidth/2+4,middle-textHeight/2)<sweep;
      if (p.showDataLabels && fits) {
        const mid=from+sweep/2, px=cx+Math.cos(mid)*middle, py=cy+Math.sin(mid)*middle;
        let rotation=mid*180/Math.PI+90;
        if (rotation>90 && rotation<270) rotation+=180;
        nodes.push(<text key={`${key}-label`} data-label="sunburst" data-level={level} className="sheet-chart-label-svg"
          x={px} y={py} textAnchor="middle" dominantBaseline="central" transform={`rotate(${rotation} ${px} ${py})`}>{name}</text>);
      }
    };
    groups.forEach((group,slot) => {
      const sweep=group.weight/total*Math.PI*2, end=angle+sweep;
      arc(`parent${slot}`,group.name,group.children.reduce((sum,[,value])=>sum+value,0),slot,1,angle,sweep);
      group.children.forEach(([child,value],i) => {
        const childSweep=i===group.children.length-1 ? end-angle : (value/weightScale)/total*Math.PI*2;
        arc(`child${slot}-${i}`,child,value,slot,2,angle,childSweep);
        legend.push({y:`child${slot}-${i}`,label:`${group.name} / ${child}`,color:one.color,slot});
        angle+=childSweep;
      });
      angle=end;
    });
    // A single yellow category has no multi-entry legend, so retain a visible key even
    // when its arc is too narrow for text or data labels have been switched off.
    if (legend.length===1 && one.color==="yellow") nodes.push(label("sunburst-key",legend[0].label,cx,bottom+20));
  } else if (!error && kind === "boxWhisker") {
    nodes.push(axes());
    const step=pw/series.length, half=Math.min(28,step*.3);
    series.forEach((s,si) => {
      const stats=boxWhiskerStats(rows.map(row=>readNumber(row,s.y)).filter((v):v is number=>v!==null))!;
      const cx=L+(si+.5)*step;
      nodes.push(<g key={s.y} data-mark="boxWhisker" data-series={s.y} clipPath={`url(#${id}-plot)`}>
        <line {...mark(si,s.color)} className="sheet-chart-mark sheet-chart-path" data-part="whisker" x1={cx} x2={cx} y1={y(stats.low)} y2={y(stats.high)}/>
        {[stats.low,stats.high].map((value,i)=><line key={i} {...mark(si,s.color)} className="sheet-chart-mark sheet-chart-path" data-part="cap" x1={cx-half/2} x2={cx+half/2} y1={y(value)} y2={y(value)}/>)}
        <rect {...mark(si,s.color)} data-part="box" data-q1={stats.q1} data-q3={stats.q3} x={cx-half} y={y(stats.q3)} width={half*2} height={Math.max(0,y(stats.q1)-y(stats.q3))}/>
        <line {...mark(si,s.color)} className="sheet-chart-mark sheet-chart-path" data-part="median" data-value={stats.median} x1={cx-half} x2={cx+half} y1={y(stats.median)} y2={y(stats.median)} strokeWidth={2}/>
        {stats.outliers.map((value,i)=><circle key={`out${i}`} {...mark(si,s.color)} data-part="outlier" data-value={value} cx={cx} cy={y(value)} r={3}>{title(s.label,value)}</circle>)}
        <title>{`${s.label}: Q1 ${fmt(stats.q1)}, median ${fmt(stats.median)}, Q3 ${fmt(stats.q3)}, whiskers ${fmt(stats.low)} to ${fmt(stats.high)}`}</title>
      </g>);
      nodes.push(label(`box-series${si}`,short(s.label,Math.max(3,Math.floor(step/8))),cx,bottom+20));
    });
  } else if (!error && kind === "stock") {
    nodes.push(axes(), ...categoryLabels());
    const half = Math.min(12, pw / rows.length * .25);
    rows.forEach((row,i) => {
      const values = series.map(s => readNumber(row,s.y)!);
      const [highValue,lowValue,close] = values.slice(series.length === 4 ? 1 : 0);
      const open = series.length === 4 ? values[0] : null;
      if (highValue<low||lowValue>high) return;
      nodes.push(<g key={`stock${i}`} {...mark(0,one.color)} data-mark="stock" data-high={highValue} data-low={lowValue} data-close={close} data-open={open ?? undefined} clipPath={`url(#${id}-plot)`}>
        <line x1={x(i)} x2={x(i)} y1={y(highValue)} y2={y(lowValue)} stroke="var(--chart-color)"/>
        {open !== null ? <line style={colorStyle(0,p,series[0].color)} x1={x(i)-half} x2={x(i)} y1={y(open)} y2={y(open)} stroke="var(--chart-color)"/> : null}
        {inValueBounds(close) ? <line data-part="close" style={colorStyle(series.length-1,p,series[series.length-1].color)} x1={x(i)} x2={x(i)+half} y1={y(close)} y2={y(close)} stroke="var(--chart-color)"/> : null}
        <line style={colorStyle(series.length-3,p,series[series.length-3].color)} x1={x(i)-half*.4} x2={x(i)+half*.4} y1={y(highValue)} y2={y(highValue)} stroke="var(--chart-color)"/>
        <line style={colorStyle(series.length-2,p,series[series.length-2].color)} x1={x(i)-half*.4} x2={x(i)+half*.4} y1={y(lowValue)} y2={y(lowValue)} stroke="var(--chart-color)"/>
        <title>{`${names[i]}: ${series.map((s,j)=>`${s.label} ${fmt(values[j])}`).join(", ")}`}</title>
      </g>);
      if (p.showDataLabels&&inValueBounds(close)) nodes.push(label(`stock-close${i}`,`${series[series.length-1].label} ${fmt(close)}`,x(i),y(highValue)-8,"middle","data"));
    });
  } else if (!error && kind === "gantt") {
    const tasks = rows.map(row => {
      const start = readNumber(row,series[0].y)!, value = readNumber(row,series[1].y)!;
      return { start, end: p.ganttMode === "end" ? value : start + value };
    });
    const a = p.yMin ?? Math.min((p.yMax ?? Infinity)-1,...tasks.map(t=>t.start));
    const b = p.yMax ?? Math.max(a+1,...tasks.map(t=>t.end));
    const xx = (v:number) => L+(v-a)/(b-a)*pw, step=ph/rows.length;
    const dateText = (v:number) => {
      const ms=(v-25569)*86400000;
      return Math.abs(ms)<=8.64e15 ? new Date(ms).toISOString().slice(0,10) : fmt(v);
    };
    nodes.push(axes([a,b],true,dateAxis?dateText:fmt),...categoryLabels(true));
    legend=[{...series[1], label: p.ganttMode === "end" ? "Task duration" : series[1].label}];
    tasks.forEach((task,i)=> {
      if (task.end<a||task.start>b) return;
      const top=T+i*step+step*.2;
      nodes.push(<rect key={`task${i}`} {...mark(0,series[1].color)} data-mark="gantt" data-start={task.start} data-end={task.end} x={xx(task.start)} y={top} width={Math.max(1,xx(task.end)-xx(task.start))} height={step*.6}>
        <title>{`${names[i]}: ${dateAxis?dateText(task.start):fmt(task.start)} to ${dateAxis?dateText(task.end):fmt(task.end)} (${fmt(task.end-task.start)}${dateAxis?" days":""})`}</title>
      </rect>);
      if(p.showDataLabels)nodes.push(label(`duration${i}`,`${fmt(task.end-task.start)}${dateAxis?" days":""}`,xx(task.end)+4,top+step*.3+4,"start","data"));
    });
  } else if (!error && (kind==="pie"||kind==="donut"||kind==="polar")) {
    const total=valid.reduce((a,b)=>a+b,0), radius=Math.max(16,Math.min(pw,ph)/2-12), cx=(L+right)/2,cy=(T+bottom)/2;
    let angle=-Math.PI/2;
    legend=rows.map((_,i)=>({y:`slice${i}`,label:names[i]}));
    vals.forEach((v,i)=>{
      if (v===null||v<=0) return;
      const sweep=kind==="polar"?Math.PI*2/rows.length:v/total*Math.PI*2;
      const r=kind==="polar"?radius*Math.sqrt(v/Math.max(...valid)):radius;
      const mid=angle+sweep/2;
      nodes.push(<path key={i} {...mark(i)} data-mark={kind} d={slicePath(cx,cy,r,kind==="donut"?radius*.55:0,angle,sweep)}>{title(names[i],v)}</path>);
      if (p.showDataLabels&&rows.length<=8&&sweep>.14) nodes.push(label(`slice${i}`,`${short(names[i],10)} ${fmt(v)}`,cx+Math.cos(mid)*r*.66,cy+Math.sin(mid)*r*.66));
      angle+=sweep;
    });
  } else if (!error&&kind==="treemap") {
    let pos=L; const total=valid.reduce((a,b)=>a+b,0);
    legend=rows.map((_,i)=>({y:`tile${i}`,label:names[i]}));
    vals.forEach((v,i)=>{ if(v===null||v<=0)return; const w=pw*v/total;
      nodes.push(<rect key={i} {...mark(i)} data-mark="treemap" x={pos} y={T} width={Math.max(0,w-2)} height={ph}>{title(names[i],v)}</rect>);
      if(p.showDataLabels&&w>40)nodes.push(label(`tile${i}`,`${short(names[i],Math.floor(w/9))} ${fmt(v)}`,pos+w/2,T+ph/2));
      pos+=w;
    });
  } else if(!error&&kind==="funnel") {
    const max=Math.max(...valid); const step=ph/rows.length,cx=(L+right)/2;
    vals.forEach((v,i)=>{if(v===null)return; const w=pw*v/max, next=pw*(vals[i+1]??v*.65)/max, top=T+i*step;
      nodes.push(<path key={i} {...mark(i)} data-mark="funnel" d={`M ${cx-w/2} ${top} H ${cx+w/2} L ${cx+next/2} ${top+step-2} H ${cx-next/2} Z`}>{title(names[i],v)}</path>);
      if(p.showDataLabels)nodes.push(label(`f${i}`,`${names[i]} ${fmt(v)}`,cx,top+step/2+4));
    });
  } else if(!error&&kind==="gauge") {
    if(valid.length!==1)error="A gauge needs one numeric value.";
    else {
      const [a,b]=chartYDomain([0,100],p),value=valid[0],fraction=clamp((value-a)/(b-a),0,1);
      const cx=(L+right)/2,cy=bottom-8,radius=Math.max(20,Math.min(pw/2,ph)-12);
      nodes.push(<path key="track" className="sheet-chart-track" d={slicePath(cx,cy,radius,radius*.7,Math.PI,Math.PI)}/>);
      if(fraction>0)nodes.push(<path key="gauge" {...mark(0,one?.color)} data-mark="gauge" d={slicePath(cx,cy,radius,radius*.7,Math.PI,Math.PI*fraction)}>{title(one.label,value)}</path>);
      const angle=Math.PI+fraction*Math.PI;
      nodes.push(<line key="needle" className="sheet-chart-needle" x1={cx} y1={cy} x2={cx+Math.cos(angle)*radius*.9} y2={cy+Math.sin(angle)*radius*.9}/>);
      nodes.push(label("value",fmt(value),cx,cy-20),label("min",fmt(a),cx-radius,cy+20),label("max",fmt(b),cx+radius,cy+20));
      if(value<a||value>b)nodes.push(label("outside","Outside gauge bounds",cx,T+14));
    }
  } else if(!error&&kind==="radar") {
    if(rows.length<3)error="A radar chart needs at least three categories.";
    else {
      const radius=Math.max(16,Math.min(pw,ph)/2-20),cx=(L+right)/2,cy=(T+bottom)/2;
      const [min,max]=chartYDomain(all,p);
      const point=(i:number,value:number)=>({x:cx+Math.cos(-Math.PI/2+i/rows.length*Math.PI*2)*radius*clamp((value-min)/(max-min),0,1),y:cy+Math.sin(-Math.PI/2+i/rows.length*Math.PI*2)*radius*clamp((value-min)/(max-min),0,1)});
      rows.forEach((_,i)=>{const pt=point(i,max);nodes.push(<line key={`axis${i}`} className="sheet-chart-grid" x1={cx} y1={cy} x2={pt.x} y2={pt.y}/>);nodes.push(label(`rad${i}`,names[i],pt.x,pt.y));});
      series.forEach((s,si)=>{const pts=rows.map((row,i)=>point(i,readNumber(row,s.y)??0));nodes.push(<polygon key={s.y} {...mark(si,s.color)} data-mark="radar" fillOpacity=".18" points={pts.map(pt=>`${pt.x},${pt.y}`).join(" ")}><title>{s.label}</title></polygon>);});
    }
  } else if(!error&&kind==="histogram") {
    const bins=histogramBins(valid,p.bins??10), domain=chartYDomain(bins.map(b=>b.count),p);
    nodes.push(axes(domain)); const bw=pw/bins.length;
    bins.forEach((b,i)=>{const top=bottom-(b.count-domain[0])/(domain[1]-domain[0])*ph;
      if(i%Math.max(1,Math.ceil(bins.length/6))===0)nodes.push(label(`bin${i}`,fmt(b.low),L+i*bw,bottom+20));
      if(b.count<domain[0]||b.count>domain[1])return;
      nodes.push(<rect key={i} {...mark(0,one?.color)} data-mark="histogram" data-count={b.count} x={L+i*bw} y={top} width={Math.max(0,bw-1)} height={Math.max(0,bottom-top)}><title>{`${fmt(b.low)} to ${fmt(b.high)}: ${b.count}`}</title></rect>);
      if(p.showDataLabels&&bins.length<=12)nodes.push(label(`n${i}`,String(b.count),L+(i+.5)*bw,top-6,"middle","data"));
    });
  } else if(!error&&kind==="waterfall") {
    let total=0; const steps=vals.map(v=>{const from=total;total+=v??0;return {from,to:total};});
    const domain=chartYDomain([0,...steps.flatMap(s=>[s.from,s.to])],p);
    const yy=(v:number)=>bottom-(v-domain[0])/(domain[1]-domain[0])*ph, bw=pw/(rows.length+1);
    nodes.push(axes(domain));
    [...steps,{from:0,to:total}].forEach((s,i)=>{
      nodes.push(label(`wc${i}`,short(i===rows.length?"Total":names[i],Math.max(4,Math.floor(bw/8))),L+(i+.5)*bw,bottom+20));
      if(Math.max(s.from,s.to)<domain[0]||Math.min(s.from,s.to)>domain[1])return;
      const delta=s.to-s.from,top=Math.min(yy(s.from),yy(s.to));
      nodes.push(<rect key={i} {...mark(i===rows.length?0:i,delta<0?"red":one?.color)} data-mark="waterfall" data-from={s.from} data-to={s.to} x={L+(i+.15)*bw} y={top} width={bw*.7} height={Math.max(1,Math.abs(yy(s.from)-yy(s.to)))}>{title(i===rows.length?"Total":names[i],delta)}</rect>);
      if(s.to<domain[0]||s.to>domain[1])return;
      if(i<rows.length-1)nodes.push(<line key={`join${i}`} className="sheet-chart-grid" x1={L+(i+.85)*bw} x2={L+(i+1.15)*bw} y1={yy(s.to)} y2={yy(s.to)}/>);
      if(p.showDataLabels)nodes.push(label(`wv${i}`,fmt(delta),L+(i+.5)*bw,top-6,"middle","data"));
    });
  } else if(!error&&kind==="bullet") {
    if(series.length<2)error="A bullet chart needs actual and target series.";
    else {
      const [a,b]=chartYDomain(all,p),xx=(v:number)=>L+(v-a)/(b-a)*pw,step=ph/rows.length;
      nodes.push(axes([a,b],true),...categoryLabels(true));
      rows.forEach((row,i)=>{const actual=readNumber(row,series[0].y),target=readNumber(row,series[1].y),top=T+i*step;
        if(actual===null||target===null)return;
        series.slice(2).map(s=>readNumber(row,s.y)).filter((v):v is number=>v!==null).sort((a,b)=>b-a).forEach((v,ri)=>nodes.push(<rect key={`range${i}-${ri}`} className="sheet-chart-track" opacity={.35+ri*.15} x={xx(0)} y={top+step*.15} width={Math.max(0,xx(v)-xx(0))} height={step*.7}/>));
        const actualVisible=inValueBounds(actual),targetVisible=inValueBounds(target);
        if(actualVisible)nodes.push(<rect key={i} {...mark(0,series[0].color)} data-mark="bullet" x={Math.min(xx(actual),xx(0))} y={top+step*.35} width={Math.abs(xx(actual)-xx(0))} height={step*.3}>{title(names[i],actual)}</rect>);
        if(targetVisible)nodes.push(<line key={`target${i}`} className="sheet-chart-needle" data-mark="bullet-target" x1={xx(target)} x2={xx(target)} y1={top+step*.2} y2={top+step*.8}/>);
        if(p.showDataLabels&&(actualVisible||targetVisible)) {
          const text=actualVisible&&targetVisible ? `${fmt(actual)} / ${fmt(target)}`
            : actualVisible ? `${series[0].label} ${fmt(actual)}` : `${series[1].label} ${fmt(target)}`;
          nodes.push(label(`b${i}`,text,right-4,top+step*.25,"end","data"));
        }
      });
    }
  } else if(!error&&(kind==="scatter"||kind==="bubble")) {
    if(kind==="bubble"&&series.length<2)error="A bubble chart needs X, Y and size columns.";
    else if(kind==="bubble"&&rows.some(r=>(readNumber(r,series[1].y)??0)<0))error="Bubble sizes must be nonnegative.";
    else if(rows.some(r=>readNumber(r,"category")===null))error="The X column must contain numeric values.";
    else {
      const markerPad=kind==="bubble"?Math.min(24,ph/6)+2:6;
      const xs=rows.map(r=>readNumber(r,"category")!),xmin=p.xMin??Math.min(...xs),xmax=p.xMax??Math.max(...xs),xx=(v:number)=>L+markerPad+(v-xmin)/(xmax-xmin||1)*(pw-2*markerPad);
      const plotted=kind==="bubble"?series.slice(0,1):series; legend=plotted;
      const [ya,yb]=chartYDomain(plotted.flatMap(s=>rows.map(r=>readNumber(r,s.y)).filter((v):v is number=>v!==null)),p);
      const padTop=p.yMax===undefined?markerPad:0,padBottom=p.yMin===undefined?markerPad:0;
      const yy=(v:number)=>bottom-padBottom-(v-ya)/(yb-ya)*(ph-padTop-padBottom);
      const spanPerPixel=(yb-ya)/(ph-padTop-padBottom);
      nodes.push(axes([ya-padBottom*spanPerPixel,yb+padTop*spanPerPixel]));
      ticks(xmin,xmax===xmin?xmin+1:xmax).forEach((v,i)=>nodes.push(label(`x${i}`,catFmt(v),xx(v),bottom+20,"middle",undefined,undefined,categoryAxis.labelAngle)));
      const maxSize=kind==="bubble"?Math.max(1,...rows.map(r=>readNumber(r,series[1].y)??0)):1;
      plotted.forEach((s,si)=>rows.forEach((row,i)=>{const v=readNumber(row,s.y);if(v===null)return;
        // D-736: test the data coordinates before creating either a marker or its label.
        if (xs[i]<xmin||xs[i]>xmax||v<ya||v>yb) return;
        const radius=kind==="bubble"?Math.sqrt((readNumber(row,series[1].y)??0)/maxSize)*Math.min(24,ph/6):4;
        if(radius<=0)return;
        nodes.push(<circle key={`${s.y}-${i}`} {...mark(si,s.color)} data-mark={kind} data-x={xs[i]} cx={xx(xs[i])} cy={yy(v)} r={radius}>{title(`${catFmt(xs[i])}, ${s.label}`,v)}</circle>);
        if(p.showDataLabels&&rows.length<=8)nodes.push(label(`xy${i}-${si}`,fmt(v),xx(xs[i])+6,yy(v)-radius-4,"start","data"));
      }));
    }
  } else if(!error) {
    const horizontal=kind==="bar",xx=(v:number)=>L+(v-low)/(high-low)*pw;
    nodes.push(axes([low,high],horizontal),...categoryLabels(horizontal));
    series.forEach((s,si)=>{
      const line=kind==="line"||kind==="area"||(kind==="combo"&&si>0);
      if(line) {
        let segment: {x:number;y:number;base:number}[]=[];
        const flush=(index:number)=>{
          if(!segment.length)return;
          const points=segment.map(pt=>`${pt.x},${pt.y}`).join(" ");
          if(kind==="area")nodes.push(<polygon key={`a${s.y}-${index}`} {...mark(si,s.color)} data-mark="area" fillOpacity=".2" points={`${points} ${[...segment].reverse().map(pt=>`${pt.x},${pt.base}`).join(" ")}`}/>);
          nodes.push(<polyline key={`l${s.y}-${index}`} {...mark(si,s.color)} className="sheet-chart-mark sheet-chart-path" data-mark={kind==="combo"?"combo-line":"line"} points={points}><title>{s.label}</title></polyline>); segment=[];
        };
        rows.forEach((row,i)=>{const v=readNumber(row,s.y), stack=stacks?.[i][si];if(v===null||(stacks&&!stack)){flush(i);return;}
          const end=stack?.to??v, start=stack?.from??0, value=stack?.value??v;
          segment.push({x:x(i),y:y(end),base:y(start)});
          if(!inValueBounds(end))return;
          nodes.push(<circle key={`d${s.y}-${i}`} {...mark(si,s.color)} data-from={start} data-to={end} cx={x(i)} cy={y(end)} r={3}>{title(`${names[i]}, ${s.label}`,value)}</circle>);
          if(p.showDataLabels&&rows.length<=8)nodes.push(label(`v${s.y}-${i}`,fmt(value),x(i),y(end)-8,"middle","data"));
        });flush(rows.length);
        if(direct) {
          const last=rows.map((row,i)=>({v:readNumber(row,s.y),i})).filter(pt=>pt.v!==null).slice(-1)[0];
          if(last)nodes.push(label(`direct${s.y}`,s.label,right-4,16+si*18,"end","direct"));
        }
      } else {
        const slots=stacked||kind==="combo"?1:series.length,step=(horizontal?ph:pw)/Math.max(1,rows.length),bar=step*.72/slots;
        rows.forEach((row,i)=>{const v=readNumber(row,s.y), stack=stacks?.[i][si];if(v===null||(stacks&&!stack))return;
          const start=stack?.from??0,end=stack?.to??v,value=stack?.value??v;
          // D-736: a clustered value outside the requested bounds has no mark or data label.
          // A stack segment may cross a bound, so preserve its visible intersection.
          if (stack ? Math.max(start,end)<low||Math.min(start,end)>high : !inValueBounds(end)) return;
          const group=(horizontal?T:L)+i*step+step*.14+(stacked?0:si*bar);
          nodes.push(<rect key={`${s.y}-${i}`} {...mark(si,s.color)} data-mark={kind==="combo"?"combo-column":kind} data-category={i} data-series={si} data-from={start} data-to={end} x={horizontal?Math.min(xx(start),xx(end)):group} y={horizontal?group:Math.min(y(start),y(end))} width={horizontal?Math.abs(xx(end)-xx(start)):Math.max(1,bar-2)} height={horizontal?Math.max(1,bar-2):stacked?Math.abs(y(end)-y(start)):Math.max(1,Math.abs(y(end)-y(start)))}>{title(`${names[i]}, ${s.label}`,value)}</rect>);
          if(p.showDataLabels&&rows.length*series.length<=24&&inValueBounds(end))nodes.push(label(`val${s.y}-${i}`,fmt(value),horizontal?xx(end)+4:group+bar/2,horizontal?group+bar/2+4:y(end)-6,horizontal?"start":"middle","data"));
        });
      }
    });
    if(direct&&!["line","area","combo"].includes(kind))
      series.forEach((s,i)=>nodes.push(label(`direct${s.y}`,s.label,right-4,16+i*18,"end","direct")));
  }
  const showLegend=legend.length>=2;
  return <div ref={drawingRef} className={`sheet-chart-drawing legend-${p.legendPosition} axis-${p.axisFont} legend-font-${p.legendFont}${onRetitle ? " sheet-chart-renamable" : ""}`} data-chart-kind={kind}>
    {p.title?<div className="sheet-chart-title" title={p.title} onClick={onRetitle ? beginRename("title", p.title ?? "") : undefined} style={onRetitle ? { cursor: "text" } : undefined}>{p.title}</div>:null}
    {error?<p className="sheet-chart-empty" role="status">{error}</p>:<>
      {showLegend?<div className="sheet-chart-legend" aria-label="Chart legend">{legend.map((s,i)=><span key={s.y} title={s.label}><i style={colorStyle(s.slot??i,p,s.color)}/>{s.label}</span>)}</div>:null}
      <svg className="sheet-chart-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label={kind==="boxWhisker"?"Box and whisker chart":`${kind[0].toUpperCase()+kind.slice(1)} chart`}>
        <defs><clipPath id={`${id}-frame`}><rect width={W} height={H}/></clipPath><clipPath id={`${id}-plot`}><rect x={L} y={T} width={pw} height={ph}/></clipPath></defs>
        {/* D-736: plot clips trim shapes; data labels are suppressed with excluded values above. */}
        <g clipPath={`url(#${id}-frame)`}>{nodes.map((node,i)=><g key={i} clipPath={typeof node==="object"&&node&&"type" in node&&["rect","circle","path","polyline","polygon"].includes(String(node.type))?`url(#${id}-plot)`:undefined}>{node}</g>)}</g>
      </svg>
    </>}
    {renaming && onRetitle ? (
      <input
        className="sheet-chart-rename"
        aria-label="Rename this label"
        autoFocus
        defaultValue={renaming.value}
        maxLength={160}
        style={{ left: renaming.left, top: renaming.top, width: renaming.width, height: renaming.height }}
        onFocus={event => event.currentTarget.select()}
        onPointerDown={event => event.stopPropagation()}
        onMouseDown={event => event.stopPropagation()}
        onKeyDown={event => {
          event.stopPropagation();
          if (event.key === "Enter") { onRetitle(renaming.key, event.currentTarget.value.trim()); setRenaming(null); }
          if (event.key === "Escape") setRenaming(null);
        }}
        onBlur={event => { onRetitle(renaming.key, event.currentTarget.value.trim()); setRenaming(null); }}
      />
    ) : null}
  </div>;
}
export type ChartPreview = { dx: number; dy: number; dw: number; dh: number };
export type ChartHandle = "n" | "s" | "e" | "w" | "ne" | "nw" | "se" | "sw";
/** Which edges a handle drags. -1 is the top or left edge, so the anchor moves too. */
const HANDLE_AXES: Record<ChartHandle, { x: -1 | 0 | 1; y: -1 | 0 | 1 }> = {
  n: { x: 0, y: -1 }, s: { x: 0, y: 1 }, e: { x: 1, y: 0 }, w: { x: -1, y: 0 },
  ne: { x: 1, y: -1 }, nw: { x: -1, y: -1 }, se: { x: 1, y: 1 }, sw: { x: -1, y: 1 },
};
const HANDLE_NAMES: Record<ChartHandle, string> = {
  nw: "Top left", n: "Top", ne: "Top right", w: "Left", e: "Right",
  sw: "Bottom left", s: "Bottom", se: "Bottom right",
};

/** Top and left handles move the anchor by the inverse of the size change to keep the opposite
 * edge fixed. Ratio is height divided by width; Shift or the aspect lock couples both dimensions. */
export const resizeDelta = (handle: ChartHandle, dx: number, dy: number,
                            ratio: number, keepRatio: boolean): ChartPreview => {
  const axis = HANDLE_AXES[handle];
  let dw = axis.x === 0 ? 0 : axis.x * dx;
  let dh = axis.y === 0 ? 0 : axis.y * dy;
  if (keepRatio && ratio > 0) {
    if (axis.x === 0) dw = dh / ratio;
    else if (axis.y === 0) dh = dw * ratio;
    else if (Math.abs(dw) >= Math.abs(dh / ratio)) dh = dw * ratio;
    else dw = dh / ratio;
  }
  return { dx: axis.x === -1 ? -dw : 0, dy: axis.y === -1 ? -dh : 0, dw, dh };
};

type Nudge = ChartPreview;
const ZERO: Nudge = { dx: 0, dy: 0, dw: 0, dh: 0 };
const NUDGE_KEYS: (keyof Nudge)[] = ["dx", "dy", "dw", "dh"];
/** rad/s. Higher is a shorter settle; at zeta = 1 there is no overshoot at any speed. */
const OMEGA = 22;
/** Below half a pixel and half a pixel per second, the spring has arrived. */
const AT_REST = 0.5;

const prefersReducedMotion = (): boolean =>
  typeof window !== "undefined"
  && typeof window.matchMedia === "function"
  && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

export default function SheetChart({
  range,
  cells,
  source,
  presentation,
  stacking,
  kind = "bar",
  selected = false,
  width,
  height,
  preview,
  onPreviewChange,
  moveSteps,
  onMove,
  onResize,
  onEdit,
  onDelete,
  onRetitle,
}: SheetChartProps) {
  const { fields, rows, series, error, dateAxis } = useMemo(
    () => chartDataForRange(cells, range, presentation, source?.ranges ?? [range], kind),
    [cells, range, presentation, source, kind],
  );

  const [localNudge, setLocalNudge] = useState<Nudge>(ZERO);
  const nudge = preview ?? localNudge;
  const previewWriter = useRef(onPreviewChange);
  previewWriter.current = onPreviewChange;
  const setNudge = useCallback((value: Nudge) => {
    setLocalNudge(value);
    previewWriter.current?.(value);
  }, []);
  const [flash, setFlash] = useState(false);
  const grab = useRef<{
    pointerId: number;
    originLeft: number;
    originTop: number;
    offsetX: number;
    offsetY: number;
    mode: "move" | "resize";
    handle: ChartHandle;
  } | null>(null);
  const frame = useRef<number | null>(null);

  const stopSettle = useCallback(() => {
    if (frame.current !== null && typeof cancelAnimationFrame === "function") {
      cancelAnimationFrame(frame.current);
    }
    frame.current = null;
  }, []);

  useEffect(() => stopSettle, [stopSettle]);

  /** The critically damped return, integrated from the value the finger let go at. */
  const settle = useCallback((from: Nudge) => {
    if (prefersReducedMotion() || typeof requestAnimationFrame !== "function") {
      // ⛔ Reduced motion replaces the spring with a short opacity change, never with a slide
      // taken faster: the whole point is that nothing travels across the screen.
      setNudge(ZERO);
      setFlash(true);
      window.setTimeout(() => setFlash(false), 140);
      return;
    }
    let value: Nudge = { ...from };
    let velocity: Nudge = { ...ZERO };
    let last = performance.now();
    const step = (now: number) => {
      const dt = Math.min(0.032, Math.max(0.001, (now - last) / 1000));
      last = now;
      let moving = false;
      const nextValue: Nudge = { ...ZERO };
      const nextVelocity: Nudge = { ...ZERO };
      for (const key of NUDGE_KEYS) {
        const accel = -2 * OMEGA * velocity[key] - OMEGA * OMEGA * value[key];
        nextVelocity[key] = velocity[key] + accel * dt;
        nextValue[key] = value[key] + nextVelocity[key] * dt;
        if (Math.abs(nextValue[key]) > AT_REST || Math.abs(nextVelocity[key]) > AT_REST) {
          moving = true;
        }
      }
      value = nextValue;
      velocity = nextVelocity;
      if (!moving) {
        setNudge(ZERO);
        frame.current = null;
        return;
      }
      setNudge(value);
      frame.current = requestAnimationFrame(step);
    };
    frame.current = requestAnimationFrame(step);
  }, []);

  const beginDrag = useCallback((mode: "move" | "resize", handle: ChartHandle = "se") =>
    (event: React.PointerEvent<HTMLButtonElement>) => {
      if (event.button !== 0) return;
      event.preventDefault();
      event.stopPropagation();
      stopSettle();
      const rect = event.currentTarget.getBoundingClientRect();
      grab.current = {
        pointerId: event.pointerId,
        originLeft: rect.left,
        originTop: rect.top,
        offsetX: event.clientX - rect.left,
        offsetY: event.clientY - rect.top,
        mode,
        handle,
      };
      event.currentTarget.setPointerCapture(event.pointerId);
      // ⛔ FOCUS IT BY HAND, because the `preventDefault` two lines up is what stops a pointer from
      // focusing a button. Every one of these handles promises "or use the arrow keys" in its own
      // label, and without this the promise is only reachable by tabbing: measured in the browser,
      // a click on a handle followed by ArrowRight resized the chart by exactly nothing.
      event.currentTarget.focus();
      setNudge(ZERO);
    }, [stopSettle]);

  const duringDrag = useCallback((event: React.PointerEvent<HTMLButtonElement>) => {
    const held = grab.current;
    if (!held || held.pointerId !== event.pointerId) return;
    // 1:1 with the pointer, from the offset it was grabbed at, so pushing back the way it came
    // undoes the drag exactly rather than starting a new one.
    const dx = event.clientX - held.offsetX - held.originLeft;
    const dy = event.clientY - held.offsetY - held.originTop;
    const ratio = height > 0 && width > 0 ? height / width : 0;
    const keepRatio = event.shiftKey || presentation?.lockAspect === true;
    const delta = held.mode === "move" ? { dx, dy, dw: 0, dh: 0 }
      : resizeDelta(held.handle, dx, dy, ratio, keepRatio);
    setNudge(delta);
  }, [height, width, presentation?.lockAspect, setNudge]);

  const endDrag = useCallback((event: React.PointerEvent<HTMLButtonElement>) => {
    const held = grab.current;
    if (!held || held.pointerId !== event.pointerId) return;
    grab.current = null;
    if (event.currentTarget.hasPointerCapture(event.pointerId)) {
      event.currentTarget.releasePointerCapture(event.pointerId);
    }
    const dx = event.clientX - held.offsetX - held.originLeft;
    const dy = event.clientY - held.offsetY - held.originTop;
    const ratio = height > 0 && width > 0 ? height / width : 0;
    const keepRatio = event.shiftKey || presentation?.lockAspect === true;
    const delta = held.mode === "move" ? { dx, dy, dw: 0, dh: 0 }
      : resizeDelta(held.handle, dx, dy, ratio, keepRatio);
    const snapped = held.mode === "move" ? onMove?.(delta.dx, delta.dy)
      : onResize?.(delta, keepRatio && ratio > 0 ? ratio : undefined);
    // The persisted anchor changes in the same release. Keep only the UNSNAPPED residual in the
    // presentation value, so old anchor + pointer travel equals new anchor + residual and there is
    // no release-frame jump or double movement.
    settle({ dx: delta.dx - (snapped?.dx ?? 0), dy: delta.dy - (snapped?.dy ?? 0), dw: 0, dh: 0 });
  }, [onMove, onResize, settle, height, width, presentation?.lockAspect]);

  const cancelDrag = useCallback((event: React.PointerEvent<HTMLButtonElement>) => {
    const held = grab.current;
    if (!held || held.pointerId !== event.pointerId) return;
    grab.current = null;
    if (event.currentTarget.hasPointerCapture(event.pointerId)) {
      event.currentTarget.releasePointerCapture(event.pointerId);
    }
    settle(nudge);
  }, [nudge, settle]);

  // ⭐ THE DRAG IS NOT THE ONLY WAY, which DESIGN.md requires: the arrow keys walk the anchor one
  // cell at a time from the move grip, and each resize handle also accepts arrows. The dialog sets a range
  // outright. A step is this chart's own width over the columns it spans, which IS one column on
  // the grid it is sitting on.
  const stepX = Math.max(8, width / Math.max(1, Math.abs(range.col1 - range.col0) + 1));
  const stepY = Math.max(8, height / Math.max(1, Math.abs(range.row1 - range.row0) + 1));

  const arrowKeys = useCallback((mode: "move" | "resize", handle: ChartHandle = "se") =>
    (event: React.KeyboardEvent<HTMLButtonElement>) => {
      if (mode === "move") {
        const send = onMove;
        if (!send) return;
        const steps = mode === "move" ? moveSteps : undefined;
        if (event.key === "ArrowLeft") send(steps?.left ?? -stepX, 0);
        else if (event.key === "ArrowRight") send(steps?.right ?? stepX, 0);
        else if (event.key === "ArrowUp") send(0, steps?.up ?? -stepY);
        else if (event.key === "ArrowDown") send(0, steps?.down ?? stepY);
        else return;
      } else {
        if (!onResize) return;
        const steps: Record<string, [number, number]> = {
          ArrowLeft: [-stepX, 0], ArrowRight: [stepX, 0], ArrowUp: [0, -stepY], ArrowDown: [0, stepY],
        };
        const step = steps[event.key];
        if (!step) return;
        const ratio = height > 0 && width > 0 ? height / width : 0;
        const keepRatio = event.shiftKey || presentation?.lockAspect === true;
        onResize(resizeDelta(handle, step[0], step[1], ratio, keepRatio), keepRatio && ratio > 0 ? ratio : undefined);
      }
      event.preventDefault();
    }, [onMove, onResize, stepX, stepY, moveSteps, height, width, presentation?.lockAspect]);

  const tools = (onMove || onResize || onEdit || onDelete) ? (
    <div className="sheet-chart-tools">
      {onMove ? (
        <button
          type="button"
          className="sheet-chart-tool sheet-chart-grip"
          style={{
            left: 3,
            right: preview ? 75 : onDelete ? (onEdit ? 75 : 51) : (onEdit ? 27 : 3),
            width: "auto",
          }}
          aria-label="Move chart. Drag this top area, or use the arrow keys."
          onPointerDown={beginDrag("move")}
          onPointerMove={duringDrag}
          onPointerUp={endDrag}
          onPointerCancel={cancelDrag}
          onKeyDown={arrowKeys("move")}
        >
          {/* Four arrows from one centre: the existing set's stroke weight and round caps. */}
          <svg className="sheet-chart-tool-icon" viewBox="0 0 16 16" aria-hidden="true">
            <path d="M8 2.5v11M2.5 8h11M8 2.5 6 4.5M8 2.5l2 2M8 13.5l-2-2M8 13.5l2-2
                     M2.5 8l2-2M2.5 8l2 2M13.5 8l-2-2M13.5 8l-2 2" />
          </svg>
        </button>
      ) : null}
      {onEdit ? (
        <button
          type="button"
          className="sheet-chart-tool"
          style={{ top: 3, right: preview || onDelete ? 51 : 3 }}
          aria-label="Open chart settings"
          onPointerDown={(event) => event.stopPropagation()}
          onClick={(event) => {
            event.stopPropagation();
            onEdit();
          }}
        >
          <svg className="sheet-chart-tool-icon" viewBox="0 0 16 16" aria-hidden="true">
            <path d="M3 4.5h10M3 8h10M3 11.5h10M6 3v3M10 6.5v3M7 10v3" />
          </svg>
        </button>
      ) : null}
      {onDelete ? (
        <button
          type="button"
          className="sheet-chart-tool"
          style={{ top: 3, right: 27 }}
          aria-label="Delete this chart"
          onPointerDown={(event) => event.stopPropagation()}
          onClick={(event) => {
            event.stopPropagation();
            onDelete();
          }}
        >
          <svg className="sheet-chart-tool-icon" viewBox="0 0 16 16" aria-hidden="true">
            <path d="M3 4.5h10M6 2.5h4" />
            <path d="M4.5 4.5l.7 9h5.6l.7-9" />
            <path d="M7 7v4M9 7v4" />
          </svg>
        </button>
      ) : null}
      {onResize ? (["nw", "n", "ne", "w", "e", "sw", "s", "se"] as const).map(handle => (
        <button
          key={handle}
          type="button"
          className={`sheet-chart-tool sheet-chart-handle${handle === "se" ? " sheet-chart-corner" : ""}`}
          data-handle={handle}
          aria-label={`${HANDLE_NAMES[handle]} resize handle. Drag it, or use the arrow keys.`}
          onPointerDown={beginDrag("resize", handle)}
          onPointerMove={duringDrag}
          onPointerUp={endDrag}
          onPointerCancel={cancelDrag}
          onKeyDown={arrowKeys("resize", handle)}
        />
      )) : null}
    </div>
  ) : null;

  const shell: React.CSSProperties = {
    width: Math.max(24, width + nudge.dw),
    height: Math.max(24, height + nudge.dh),
    transform: nudge.dx || nudge.dy ? `translate(${nudge.dx}px, ${nudge.dy}px)` : undefined,
    opacity: flash ? 0.72 : undefined,
  };

  // ⭐ W56-T12, R6 and instruction 9: font-size inside a scaled viewBox is measured in user
  // units, so a constant token changes size on screen with the person's chart box. Dividing by
  // this scale keeps axis labels at one legible screen size whatever box they choose.
  const drawScale = 1;

  if (!series.length || error) {
    // Named rather than drawn empty: a chart frame with no series reads as "the data is zero",
    // which is a different and wrong statement.
    return (
      <div className={`sheet-chart is-empty${selected ? " is-selected" : ""}`}
           style={{ ...shell, "--sheet-chart-scale": String(drawScale) } as React.CSSProperties}
           role="img"
           aria-label="This range has no numeric column to chart">
        <p>{error || "This range has no numeric values to chart."}</p>
        {tools}
      </div>
    );
  }

  return (
    // ⭐ THE WRAPPER IS THE SIZING MECHANISM. `SeriesChart` draws into a fixed 720x230 viewBox, so
    // scaling it to an arbitrary cell rectangle is the wrapper's job and the renderer stays
    // untouched. `viz/**` belongs to no lane in this wave, and the own-drawn kinds use the same
    // viewBox for the same reason.
    <div
      className={`sheet-chart${selected ? " is-selected" : ""}`}
      style={{ ...shell, "--sheet-chart-scale": String(drawScale) } as React.CSSProperties}
    >
      <div className="sheet-chart-plot">
        <DrawnChart kind={kind} stacking={stacking} fields={fields} rows={rows} series={series}
          presentation={presentation} dateAxis={dateAxis} width={width+nudge.dw} height={height+nudge.dh-20} onRetitle={onRetitle} />
      </div>
      {tools}
    </div>
  );
}