File size: 39,157 Bytes
56e1f2f
016c754
56e1f2f
 
 
 
 
 
 
 
 
 
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e1f2f
 
 
 
 
 
 
 
 
016c754
56e1f2f
016c754
7127075
56e1f2f
7127075
56e1f2f
 
016c754
 
 
7127075
 
56e1f2f
 
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7127075
56e1f2f
 
 
 
 
 
 
 
 
 
 
 
 
016c754
 
 
 
7127075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e1f2f
 
 
 
7127075
56e1f2f
7127075
 
 
 
 
 
 
 
 
 
56e1f2f
 
 
 
 
 
0c7b86d
 
 
 
 
56e1f2f
 
 
7127075
 
 
 
 
 
56e1f2f
7127075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e1f2f
 
016c754
 
 
 
 
 
 
 
56e1f2f
 
 
 
7127075
56e1f2f
 
 
0c7b86d
56e1f2f
7127075
 
 
 
 
 
 
 
 
 
 
56e1f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7127075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
016c754
 
 
 
 
 
 
 
56e1f2f
 
 
 
 
 
 
 
 
 
 
 
7127075
56e1f2f
 
 
 
 
 
7127075
56e1f2f
 
 
 
 
 
 
 
 
 
 
7127075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
016c754
7127075
 
 
 
 
 
 
 
016c754
56e1f2f
0c7b86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e1f2f
 
 
 
 
 
 
 
 
 
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e1f2f
 
 
 
 
 
 
 
 
 
 
 
 
7127075
 
56e1f2f
 
 
 
016c754
 
7127075
 
 
 
 
 
016c754
56e1f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
016c754
7127075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c7b86d
 
 
 
016c754
 
 
 
 
56e1f2f
 
 
 
 
 
 
 
 
 
 
 
7127075
 
 
 
 
 
 
 
 
 
 
 
0c7b86d
 
 
 
 
 
 
 
 
 
 
 
 
7127075
0c7b86d
 
 
 
 
 
 
 
 
 
 
 
 
 
7127075
 
 
 
 
 
 
 
 
 
56e1f2f
016c754
56e1f2f
016c754
56e1f2f
 
 
016c754
56e1f2f
 
 
 
 
 
016c754
56e1f2f
 
 
016c754
56e1f2f
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e1f2f
 
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e1f2f
 
 
 
 
016c754
 
 
 
 
56e1f2f
016c754
56e1f2f
 
 
 
 
 
 
 
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e1f2f
016c754
56e1f2f
 
 
 
 
 
 
016c754
 
 
 
56e1f2f
016c754
 
56e1f2f
016c754
 
 
56e1f2f
016c754
 
 
 
 
56e1f2f
016c754
 
56e1f2f
016c754
 
 
56e1f2f
 
016c754
 
56e1f2f
 
016c754
56e1f2f
 
 
 
016c754
56e1f2f
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e1f2f
 
 
016c754
56e1f2f
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56e1f2f
016c754
 
 
 
 
 
 
 
 
 
7127075
 
 
 
016c754
 
 
56e1f2f
 
016c754
 
7127075
56e1f2f
016c754
 
 
 
 
56e1f2f
016c754
 
 
56e1f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7127075
016c754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * TimeSeriesPanel.tsx β€” owner item 7 (contract C-TS), rebuilt for wave-14 items 16c Β· 17 Β· 18.
 *
 * ⚠ **HOST-AGNOSTIC ON PURPOSE β€” it reads no CustomerGrid state, ever.** RECORD re-mounts this
 * exact component inside the record modal for item 13 (contract C-EMBED) with `pids=[pid]` and
 * `locked`, so every input arrives as a prop. The moment this file imports a grid hook, the
 * record-detail Insights tab stops being possible.
 *
 * All arithmetic and every honest disclosure live in `timeSeriesData.ts`, which
 * `web/verify_timeseries.py` gates under node. This file is layout, fetch orchestration and
 * one chart adapter β€” deliberately nothing a wrong number could hide in.
 *
 * ── What wave 14 changed, and why ──────────────────────────────────────────────────────────
 *
 * The panel WAS a chip bar over a fixed table: you toggled metrics on and off above the data,
 * and the table was a read-only report of whatever survived. The owner asked for a SHEET β€”
 * something you build rather than something you filter. So:
 *
 *   Β· the metric chips are GONE. A metric is a ROW, added from a "+ Add metric" row at the
 *     bottom the way a spreadsheet grows, and removed from the row itself. The list of what is
 *     on screen and the list of what could be are the same list, in the same place.
 *   Β· rows carry the server's WINDOW LABEL as a sublabel (R1/C-TSWIN). Under identical month
 *     headings, a year-to-date row and a trailing-90 row are different claims, and nothing on
 *     screen used to say which one you were reading.
 *   Β· custom NOTE and FORMULA rows (R2) β€” the reader's own arithmetic, evaluated per column
 *     against the resolved buckets, refusing rather than inventing on every failure.
 *   Β· "Change vs prior" was ONE toggle producing ONE sub-row. It is now four named comparisons
 *     (item 18), each of which can refuse for its own stated reason.
 */

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { fetchTimeseries } from "./apiBridge";
import type { SurfaceScope } from "./apiBridge";
import { isStreamlitComponent } from "./hostBridge";
import {
  DEFAULT_TS_BUCKET,
  DEFAULT_TS_LAST_N,
  TS_DELTA_LABELS,
  buildTsRequest,
  buildTsSheet,
  buildTsSnapshotRow,
  buildTsTable,
  classifyTsField,
  formatTsDelta,
  formatTsValue,
  resolveTsStyle,
  sparklinePoints,
  sparklineSegments,
  tsDisplayNumber,
  tsRefusalReason,
  tsRowToChartModel,
} from "./timeSeriesData";
import type {
  TsDeltaSubRow,
  TsPayload,
  TsSheet,
  TsSheetRow,
  TsTableRow,
} from "./timeSeriesData";
import {
  TS_BUCKETS,
  TS_DELTA_KINDS,
  TS_MAX_CUSTOM_ROWS,
  TS_MAX_FIELDS,
  TS_ROW_LABEL_MAX,
  TS_MAX_EXPR,
} from "./types";
import type {
  DisplaySpec,
  Field,
  TsBucket,
  TsCellStyle,
  TsCustomRow,
  TsDeltaKind,
} from "./types";
import { FieldSelectButton } from "./FieldSelect";
import { Popover } from "../filter-kit";
import { toVegaLiteSpec } from "../viz/vega/toVegaLiteSpec";
import VegaLiteChart from "../viz/vega/VegaLiteChart";

const BUCKET_LABELS: Record<TsBucket, string> = {
  week: "Weekly",
  month: "Monthly",
  quarter: "Quarterly",
  year: "Yearly",
};

/** The rolling spans offered, per bucket. Capped well inside `TS_MAX_LAST_N`. */
const LAST_N_CHOICES = [6, 12, 24, 36];

/** The sparkline's box. Small enough to sit in a table cell, wide enough to have a shape. */
const SPARK_W = 72;
const SPARK_H = 18;

/**
 * wave17 owner item 7 β€” the Compare popover's mark: a rising step over a baseline.
 *
 * Private to this file, the way `Toolbar.tsx` keeps its own `Icon*` set: the toolbar's glyphs
 * are not exported, and this is the only surface that means "compare with the prior period".
 * A step rather than an arrow β€” all four comparisons are period-to-period, and an arrow would
 * claim a direction the control does not have.
 */
function IconCompare() {
  const s = {
    stroke: "currentColor",
    strokeWidth: 1.5,
    strokeLinecap: "round" as const,
    strokeLinejoin: "round" as const,
    fill: "none",
  };
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" aria-hidden>
      <path d="M2.5 11.5h4v-4h4v-3h3" {...s} />
      <path d="M2.5 13.5h11" {...s} opacity="0.45" />
    </svg>
  );
}

export interface TimeSeriesPanelProps {
  scope: SurfaceScope;
  /** The rows in scope. The server intersects with the caller's book regardless. */
  pids: number[];
  /** Every field the table has β€” the panel classifies them itself (item 5 / R9). */
  fields: Field[];
  /**
   * wave17 item 5 / R9 β€” the view's data rows, for SNAPSHOT metrics only.
   *
   * ⚠ Does NOT break this file's host-agnostic rule. The rule is that the panel reads no
   * CustomerGrid STATE; `pids` and `fields` already arrive the same way, and RECORD passes its
   * one record. It must be the SAME population `pids` came from, or the two halves of one sheet
   * would answer different questions with nothing going red β€” CustomerGrid derives both from
   * `modeDataRows`.
   */
  rows?: readonly Record<string, unknown>[];
  /** The view's `config.display`; absent keys fall back to the panel's defaults. */
  display?: DisplaySpec;
  /** Persist a display change. Absent = the panel is ephemeral (RECORD's embed, v1). */
  onDisplay?: (next: Partial<DisplaySpec>) => void;
  /** Item 13 β€” the pid set is the caller's and cannot be widened from here. */
  locked?: boolean;
  /**
   * owner item 3 (2026-08-03) β€” publish the built sheet so the view menu's Export can carry it.
   * Absent = this mount cannot be exported (RECORD's embed), which is the honest default.
   */
  onSheet?: (sheet: TsSheet) => void;
}

/**
 * wave17 item 5 / owner R9 β€” **OFFER EVERYTHING, best-effort.**
 *
 * v1 offered `key.startsWith("measure_")`, which was both too narrow and the wrong test. The
 * classification now lives in `timeSeriesData.classifyTsField` (pure, gated under node) and this
 * file only groups the result. A formula FIELD is still refused, for the reason it always was: it
 * has no time dimension of its own, and a formula ROW on this sheet (R2) is a different thing.
 */
function classifyFields(fields: Field[]): {
  server: Field[];
  snapshot: Field[];
  refused: { field: Field; why: string }[];
} {
  const out = {
    server: [] as Field[],
    snapshot: [] as Field[],
    refused: [] as { field: Field; why: string }[],
  };
  for (const f of fields) {
    const cls = classifyTsField(f);
    if (cls === "server") out.server.push(f);
    else if (cls === "snapshot") out.snapshot.push(f);
    else out.refused.push({ field: f, why: tsRefusalReason(f) });
  }
  return out;
}

/** A stable-enough id for a new custom row. `TS_ROW_ID_MAX` is 40; this is 12. */
function newRowId(existing: readonly TsCustomRow[]): string {
  let n = existing.length + 1;
  const taken = new Set(existing.map((r) => r.id));
  while (taken.has(`tsr_${n}`)) n += 1;
  return `tsr_${n}`;
}

export default function TimeSeriesPanel({
  scope,
  pids,
  fields,
  rows,
  display,
  onDisplay,
  locked,
  onSheet,
}: TimeSeriesPanelProps) {
  const classed = useMemo(() => classifyFields(fields), [fields]);
  // The OFFERED list: everything with a way onto the sheet, server-served first so a real series
  // is never buried under a flat one in the picker.
  const eligible = useMemo(
    () => [...classed.server, ...classed.snapshot],
    [classed.server, classed.snapshot]
  );
  const snapshotKeys = useMemo(
    () => new Set(classed.snapshot.map((f) => f.key)),
    [classed.snapshot]
  );

  const bucket: TsBucket = (TS_BUCKETS as readonly string[]).includes(display?.tsBucket ?? "")
    ? (display!.tsBucket as TsBucket)
    : DEFAULT_TS_BUCKET;
  const lastN =
    typeof display?.tsSpan?.lastN === "number" ? display.tsSpan.lastN : DEFAULT_TS_LAST_N;
  const selected = useMemo(() => {
    const want = display?.tsFields ?? [];
    const live = want.filter((k) => eligible.some((f) => f.key === k));
    // A view whose stored fields have all been deleted falls back to the first eligible
    // metric rather than to an empty table, which would read as "no data" when the truth is
    // "no fields chosen".
    return live.length ? live : eligible.slice(0, 1).map((f) => f.key);
  }, [display?.tsFields, eligible]);

  /**
   * wave17 item 5 β€” the selection SPLIT by where its answer comes from.
   *
   * ⚠ Only `wired` reaches the server. Sending a snapshot key would be answered with
   * `not_a_measure_field` and rendered as a refusal footnote β€” telling the reader a field failed
   * when the panel chose, deliberately, to compute it here.
   */
  const wired = useMemo(
    () => selected.filter((k) => !snapshotKeys.has(k)),
    [selected, snapshotKeys]
  );
  const snapshotSelected = useMemo(
    () => selected.filter((k) => snapshotKeys.has(k)),
    [selected, snapshotKeys]
  );

  const customRows = useMemo(() => display?.tsRows ?? [], [display?.tsRows]);
  const deltaKinds = useMemo(() => display?.tsDeltas ?? [], [display?.tsDeltas]);
  const styles = display?.tsStyles;
  // ⚠ PRESENCE, not truthiness β€” `tsGridlines` is `false | undefined` and absent means SHOWN.
  // `!display?.tsGridlines` would hide the gridlines on every view that never chose.
  const gridlines = display?.tsGridlines !== false;
  const sparkline = display?.tsSparkline === true;

  const [payload, setPayload] = useState<TsPayload | null>(null);
  const [state, setState] = useState<"idle" | "loading" | "error">("idle");
  const [errStatus, setErrStatus] = useState(0);
  const [charted, setCharted] = useState<Set<string>>(new Set());
  // Guards a slow response from overwriting a newer one β€” the request the user is waiting on
  // is the LAST one they asked for, not the last one to arrive.
  const reqRef = useRef(0);

  const embedded = isStreamlitComponent();

  useEffect(() => {
    if (embedded) return;
    if (!wired.length || !pids.length) {
      setPayload(null);
      setState("idle");
      return;
    }
    const seq = ++reqRef.current;
    setState("loading");
    const body = buildTsRequest({ pids, bucket, span: { lastN }, fields: wired });
    fetchTimeseries(body, scope).then(({ payload: p, status }) => {
      if (seq !== reqRef.current) return;
      if (!p) {
        setPayload(null);
        setErrStatus(status);
        setState("error");
        return;
      }
      setPayload(p);
      setState("idle");
    });
  }, [embedded, scope, pids, bucket, lastN, wired]);

  const served = useMemo(() => buildTsTable(payload), [payload]);
  /**
   * wave17 item 5 / R9 β€” the snapshot rows, spliced in AFTER the server's.
   *
   * ⚠ They ride the SERVER's columns. Bucket starts and bucket labels are server math
   * (`_ts_next`/`_ts_label`), and re-deriving them here would be a second copy with no parity
   * gate holding it to the first. The consequence β€” a snapshot-only sheet has no columns to sit
   * on β€” is DISCLOSED below rather than papered over; the relaxation that would remove it is a
   * one-line 400β†’200 on the TS route, requested as an amendment in the wave doc.
   */
  const table = useMemo(() => {
    if (!snapshotSelected.length || !served.columns.length) return served;
    const byKey = new Map(fields.map((f) => [f.key, f]));
    const extra = snapshotSelected
      .map((k) => byKey.get(k))
      .filter((f): f is Field => !!f)
      .map((f) => buildTsSnapshotRow(f, rows ?? [], served.columns, payload?.meta?.today));
    return { ...served, rows: [...served.rows, ...extra], empty: false };
  }, [served, snapshotSelected, fields, rows, payload?.meta?.today]);
  const sheet: TsSheet = useMemo(
    () =>
      buildTsSheet(table, {
        customRows,
        deltas: deltaKinds,
        bucket,
        today: payload?.meta?.today,
      }),
    [table, customRows, deltaKinds, bucket, payload?.meta?.today]
  );

  /**
   * ⭐ owner item 3 (2026-08-03) β€” the sheet is PUBLISHED, not downloaded from here.
   *
   * This panel used to carry its own "Export CSV" button. It was the only view in the product
   * with a second export door, and the only one offering a single format, while every other
   * view exports from the "…" menu in the rail with four. So the button is gone and the sheet
   * goes UP instead: the owner of the view menu builds the file, and the time-series view
   * exports its SHEET rather than the customer rows underneath it.
   *
   * ⚠ A PROP, WHICH IS WHAT KEEPS THIS FILE HOST-AGNOSTIC. The rule at the top of this file is
   * that the panel reads no CustomerGrid state β€” a callback the caller supplies is the same
   * shape `onDisplay` already is. RECORD's embed passes neither and simply cannot export, which
   * is correct: there is no view menu in a record modal.
   *
   * Effect rather than a render-time call: publishing during render would set state in another
   * component mid-render. `sheet` is a `useMemo`, so this fires on a real change, not per frame.
   */
  useEffect(() => {
    onSheet?.(sheet);
  }, [sheet, onSheet]);

  const toggleChart = useCallback((key: string) => {
    setCharted((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);
      else next.add(key);
      return next;
    });
  }, []);

  // ── display writers. Each one DELETES its key for the default rather than storing a second
  // spelling of it β€” the `kanbanClamp` law, which `tsGridlines` and `tsSparkline` inherit
  // exactly (the host accepts only the literal `false` / literal `true`).
  const setMetrics = (keys: string[]) => {
    // Never persist an EMPTY metric list: it would read back as "no data" on the next open.
    if (!keys.length) return;
    onDisplay?.({ tsFields: keys.slice(0, TS_MAX_FIELDS) });
  };
  const setRows = (rows: TsCustomRow[]) =>
    onDisplay?.({ tsRows: rows.length ? rows.slice(0, TS_MAX_CUSTOM_ROWS) : undefined });
  const toggleDelta = (kind: TsDeltaKind) => {
    const next = deltaKinds.includes(kind)
      ? deltaKinds.filter((k) => k !== kind)
      : [...deltaKinds, kind];
    onDisplay?.({ tsDeltas: next.length ? next : undefined });
  };
  const setStyle = (rowId: string, patch: TsCellStyle) => {
    const next: Record<string, TsCellStyle> = { ...(styles ?? {}) };
    const merged = { ...resolveTsStyle(styles, rowId), ...patch };
    // A style that reduces to nothing is DELETED, never stored as `{}`: an empty object is the
    // absent state's second spelling, and 200 of them would evict real emphasis under the cap
    // (GRID's C-TYPES2 asymmetry #1, mirrored here so a save round-trips unchanged).
    const kept: TsCellStyle = {};
    if (merged.bold) kept.bold = true;
    if (merged.line) kept.line = true;
    if (kept.bold || kept.line) next[rowId] = kept;
    else delete next[rowId];
    onDisplay?.({ tsStyles: Object.keys(next).length ? next : undefined });
  };

  // ── the Streamlit embed. C-TS: an honest placeholder, and above all it must not crash the
  // component β€” the grid still runs inside app.py and a throw here would take the page.
  if (embedded) {
    return (
      <div className="cg-mode-empty">
        The time-series view runs in the web app. Open Loopable in a browser tab to see it.
      </div>
    );
  }

  if (!eligible.length) {
    return (
      <div className="cg-mode-empty">
        This table has no number fields to plot. A time series needs either a metric with a
        period, or a numeric column to snapshot β€” add one from a column menu, then pick it here.
      </div>
    );
  }

  const unused = eligible.filter((f) => !selected.includes(f.key));
  const colCount = sheet.columns.length + 2 + (sparkline ? 1 : 0);
  /* wave17 item 5 / R9 β€” the honest edge, while the TS route still 400s a request with no
     measure field in it. Snapshot rows are painted under the SERVER's bucket columns, so with
     no measure metric on the sheet there is nowhere to put them. Said in words, with the fix,
     rather than rendering an empty table that looks broken. */
  const snapshotsUnplaced =
    snapshotSelected.length > 0 && sheet.columns.length === 0 && state !== "loading";

  return (
    <div className="cg-ts">
      <div className="cg-ts-bar">
        <label className="cg-ts-ctl">
          <span className="cg-ts-ctl-k">Period</span>
          <select
            className="cg-select"
            value={bucket}
            onChange={(e) => onDisplay?.({ tsBucket: e.target.value as TsBucket })}
            disabled={!onDisplay}
          >
            {TS_BUCKETS.map((b) => (
              <option key={b} value={b}>
                {BUCKET_LABELS[b]}
              </option>
            ))}
          </select>
        </label>
        <label className="cg-ts-ctl">
          <span className="cg-ts-ctl-k">Span</span>
          <select
            className="cg-select"
            value={String(lastN)}
            onChange={(e) => onDisplay?.({ tsSpan: { lastN: Number(e.target.value) } })}
            disabled={!onDisplay}
          >
            {LAST_N_CHOICES.map((n) => (
              <option key={n} value={n}>
                Last {n}
              </option>
            ))}
          </select>
        </label>

        {/* Item 18 β€” four named comparisons where there used to be one unnamed toggle.
            "Change vs prior" could not say WHICH prior, and there are four honest answers.

            wave17 owner item 7 β€” those four sat OPEN on the bar as a labelled strip, which made
            this panel's most consequential control look like nothing else in the product. It is
            a `Popover` now: the same component Filter / Sort / Group mount, so "the same" is
            achieved by BEING the same rather than by resembling it (the component's own note).
            The count rides the label in the `Filter Β· 2` grammar, and `active` lights the button
            while any comparison is on β€” the strip used to be the only way to know. */}
        <Popover
          label={deltaKinds.length ? `Compare Β· ${deltaKinds.length}` : "Compare"}
          icon={<IconCompare />}
          active={deltaKinds.length > 0}
        >
          {() => (
            <div className="cg-pop-body">
              <div className="cg-pop-title">Compare each period with</div>
              <div className="cg-pop-note">
                Each choice adds a sub-row under every metric. A comparison that cannot be
                answered for a metric says so in the footnotes rather than printing a number.
              </div>
              {TS_DELTA_KINDS.map((kind) => (
                <label key={kind} className="cg-check-row">
                  <input
                    type="checkbox"
                    checked={deltaKinds.includes(kind)}
                    disabled={!onDisplay}
                    onChange={() => toggleDelta(kind)}
                  />
                  <span className="cg-check-label">{TS_DELTA_LABELS[kind]}</span>
                </label>
              ))}
            </div>
          )}
        </Popover>

        <span className="cg-ts-group">
          <button
            type="button"
            className={"cg-ts-tog" + (gridlines ? " is-on" : "")}
            aria-pressed={gridlines}
            disabled={!onDisplay}
            // The literal `false` is the ONLY storable opt-out; the default is stored by
            // DELETING the key. Writing `true` would be a second spelling the host drops,
            // and the toggle would look broken.
            onClick={() => onDisplay?.({ tsGridlines: gridlines ? false : undefined })}
          >
            Gridlines
          </button>
          <button
            type="button"
            className={"cg-ts-tog" + (sparkline ? " is-on" : "")}
            aria-pressed={sparkline}
            disabled={!onDisplay}
            onClick={() => onDisplay?.({ tsSparkline: sparkline ? undefined : true })}
          >
            Trend
          </button>
        </span>

        {/* β›” NO EXPORT BUTTON HERE (owner item 3, 2026-08-03). Export lives in the view's "…"
            menu, on every view, in four formats β€” and from a time-series view it now carries
            THIS SHEET rather than the rows beneath it (see `onSheet` above). A second door on
            one surface is how "where do I export from?" stops having an answer. */}
        <span className="cg-ts-pool">
          {locked
            ? "This record"
            : `${sheet.pool.toLocaleString()} ${sheet.pool === 1 ? "customer" : "customers"}`}
        </span>
      </div>

      {state === "error" && (
        <div className="cg-ts-note cg-ts-error">
          {errStatus === 400
            ? "That span is too wide to bucket. Choose a shorter span or a larger period."
            : errStatus === 403
              ? "None of these records are in your book."
              : "The time series could not be loaded. Nothing is shown rather than a guess."}
        </div>
      )}

      {snapshotsUnplaced && (
        <div className="cg-ts-note">
          {snapshotSelected.length === 1 ? "That column has" : "Those columns have"} no period of
          its own, so {snapshotSelected.length === 1 ? "it is" : "they are"} shown as a snapshot
          across the periods on the sheet β€” and this sheet has no periods yet. Add one metric with
          a period and {snapshotSelected.length === 1 ? "it" : "they"} will appear beside it.
        </div>
      )}

      {/* wave17 item 5 / R9 β€” "offered is the ruling, undisclosed is not", and its converse: a
          field that CANNOT be plotted is NAMED here rather than quietly missing from the picker.
          A reader who can see "Status" in the table and cannot find it in this list otherwise has
          no way to tell a refusal from an oversight.

          β›” COLLAPSED, AFTER THE OWNER READ IT AS BROKEN MARKUP (2026-08-03). R9's disclosure was
          shipped as a bare strip of every refused label β€” struck through, unheaded, at the small
          end of the type scale. On the customer table that is ~25 names, and 25 crossed-out words
          in a row under a toolbar do not read as "these columns have no period"; they read as a
          stylesheet that failed to load. The strip said WHAT but never WHY IT WAS THERE.

          A `<details>` fixes exactly that and nothing else: the disclosure is still complete and
          still one click from the panel, but it now leads with a SENTENCE that says what the list
          is, and it is shut until asked. Native rather than a Popover β€” no state, keyboard and
          screen-reader behaviour for free, and it degrades to an open list if CSS never arrives,
          which is the failure this element is being fixed for. */}
      {classed.refused.length > 0 && (
        <details className="cg-ts-refused">
          <summary className="cg-ts-refsum">
            {classed.refused.length === 1
              ? "1 column has no period of its own"
              : `${classed.refused.length} columns have no period of their own`}
          </summary>
          <div className="cg-ts-reflist">
            {classed.refused.map(({ field, why }) => (
              <span key={field.key} className="cg-ts-refchip" title={why}>
                {field.label}
              </span>
            ))}
          </div>
        </details>
      )}

      {/* wave17 GRID β€” item 3 / R6. Only the LOADING note becomes a spinner; the refusal notes
          above it keep their words, because "could not be loaded" is an answer and R6 is about
          the wait. A spinner in place of a refusal would spin forever. */}
      {state === "loading" && !payload && (
        <div className="cg-ts-note">
          <span className="lp-spin" role="status" aria-label="Loading" />
        </div>
      )}

      {payload && (
        <div className="cg-ts-scroll">
          <table className={"cg-ts-table" + (gridlines ? "" : " is-nogrid")}>
            <thead>
              <tr>
                <th className="cg-ts-stick">Metric</th>
                {sheet.columns.map((c) => (
                  <th key={c.key} className={c.partial ? "is-partial" : undefined}>
                    {c.label}
                    {c.partial && <span className="cg-ts-partial"> Β· partial</span>}
                  </th>
                ))}
                <th className="cg-ts-total">Total</th>
                {sparkline && <th className="cg-ts-sparkhead">Trend</th>}
              </tr>
            </thead>
            <tbody>
              {sheet.rows.map((row) => (
                <TsRowBlock
                  key={row.id}
                  row={row}
                  sheet={sheet}
                  style={resolveTsStyle(styles, row.id)}
                  styles={styles}
                  sparkline={sparkline}
                  charted={charted.has(row.id)}
                  editable={!!onDisplay}
                  metricRow={table.rows.find((r) => r.field === row.id)}
                  onToggleChart={() => toggleChart(row.id)}
                  onStyle={(patch) => setStyle(row.id, patch)}
                  onRemove={() => {
                    if (row.kind === "metric")
                      setMetrics(selected.filter((k) => k !== row.id));
                    else setRows(customRows.filter((r) => r.id !== row.id));
                  }}
                  onEditRow={(patch) =>
                    setRows(customRows.map((r) => (r.id === row.id ? { ...r, ...patch } : r)))
                  }
                />
              ))}
              {/* Item 17 β€” the sheet GROWS from its bottom edge, the way a spreadsheet does.
                  This row is both the list of what could be added and the control that adds
                  it; a picker somewhere else would be a second inventory to keep in sync. */}
              {onDisplay && (
                <tr className="cg-ts-addrow">
                  <th className="cg-ts-stick" colSpan={colCount}>
                    <span className="cg-ts-addbar">
                      {/* C-FLDSEL (item 20) β€” the type mark travels with the name. `value` is
                          deliberately left UNSET: this control never displays a choice, it
                          only makes one, so the placeholder IS its resting state (which is
                          also the scar the contract names β€” a native <select> with no value
                          paints its first option and claims a choice nobody made). */}
                      <FieldSelectButton
                        fields={unused}
                        value={undefined}
                        onChange={(key) => setMetrics([...selected, key])}
                        className="cg-select cg-ts-addsel"
                        ariaLabel="Add a metric row"
                        disabled={!unused.length || selected.length >= TS_MAX_FIELDS}
                        placeholder={
                          !unused.length
                            ? "Every metric is on the sheet"
                            : selected.length >= TS_MAX_FIELDS
                              ? `At the ${TS_MAX_FIELDS}-metric limit`
                              : "+ Add metric"
                        }
                      />
                      <button
                        type="button"
                        className="cg-ts-tog"
                        disabled={customRows.length >= TS_MAX_CUSTOM_ROWS}
                        onClick={() =>
                          setRows([
                            ...customRows,
                            { id: newRowId(customRows), kind: "note", label: "" },
                          ])
                        }
                      >
                        + Note
                      </button>
                      <button
                        type="button"
                        className="cg-ts-tog"
                        disabled={customRows.length >= TS_MAX_CUSTOM_ROWS}
                        onClick={() =>
                          setRows([
                            ...customRows,
                            { id: newRowId(customRows), kind: "formula", label: "", expr: "" },
                          ])
                        }
                      >
                        + Formula
                      </button>
                    </span>
                  </th>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {payload && sheet.empty && (
        <div className="cg-ts-note">No metrics returned a series for this span.</div>
      )}

      {sheet.notes.length > 0 && (
        <ul className="cg-ts-notes">
          {sheet.notes.map((n) => (
            <li key={n}>{n}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

/** A row's own controls: emphasis, then removal. Hover-revealed, always in the tab order. */
function RowTools({
  style,
  editable,
  onStyle,
  onRemove,
  label,
}: {
  style: TsCellStyle;
  editable: boolean;
  onStyle: (patch: TsCellStyle) => void;
  onRemove: () => void;
  label: string;
}) {
  if (!editable) return null;
  return (
    <span className="cg-ts-rowtools">
      <button
        type="button"
        className={"cg-ts-rowtool" + (style.bold ? " is-on" : "")}
        aria-pressed={!!style.bold}
        aria-label={`Bold ${label}`}
        title="Bold"
        onClick={() => onStyle({ bold: style.bold ? undefined : true })}
      >
        B
      </button>
      <button
        type="button"
        className={"cg-ts-rowtool" + (style.line ? " is-on" : "")}
        aria-pressed={!!style.line}
        aria-label={`Rule above ${label}`}
        title="Rule above"
        onClick={() => onStyle({ line: style.line ? undefined : true })}
      >
        ―
      </button>
      <button
        type="button"
        className="cg-ts-rowtool"
        aria-label={`Remove ${label}`}
        title="Remove row"
        onClick={onRemove}
      >
        Γ—
      </button>
    </span>
  );
}

/**
 * One sheet row: its values, its delta sub-rows, and an optional line chart.
 *
 * The chart is built from `tsRowToChartModel`, NOT from `viz/chartData.buildChartData` β€” see
 * that function's note. `buildChartData` caps at 12 buckets, which for a time series means
 * silently deleting periods.
 */
function TsRowBlock({
  row,
  sheet,
  style,
  styles,
  sparkline,
  charted,
  editable,
  metricRow,
  onToggleChart,
  onStyle,
  onRemove,
  onEditRow,
}: {
  row: TsSheetRow;
  sheet: TsSheet;
  style: TsCellStyle;
  styles: Record<string, TsCellStyle> | undefined;
  sparkline: boolean;
  charted: boolean;
  editable: boolean;
  metricRow: TsTableRow | undefined;
  onToggleChart: () => void;
  onStyle: (patch: TsCellStyle) => void;
  onRemove: () => void;
  onEditRow: (patch: Partial<TsCustomRow>) => void;
}) {
  const spec = useMemo(() => {
    if (!charted || !metricRow) return null;
    const model = tsRowToChartModel(metricRow, sheet.columns);
    if (!model.points.length) return null;
    return toVegaLiteSpec({
      spec: { id: row.id, kind: "line", agg: (row.agg ?? "sum") as never },
      model,
      yTitle: row.label,
      formatValue: (n) => n.toLocaleString(undefined, { maximumFractionDigits: 2 }),
    });
  }, [charted, metricRow, sheet.columns, row.id, row.agg, row.label]);

  const colCount = sheet.columns.length + 2 + (sparkline ? 1 : 0);
  const rowCls =
    (style.line ? "is-ruled" : "") + (style.bold ? " is-bold" : "") || undefined;

  // A NOTE row is a label across the sheet β€” a section heading in a financial model, not a
  // series with empty cells. Spanning it is what stops twelve blank cells from reading as
  // twelve unanswerable ones ("β€”" already means something else here).
  if (row.kind === "note") {
    return (
      <tr className={"cg-ts-noterow " + (rowCls ?? "")}>
        <th className="cg-ts-stick" colSpan={colCount}>
          <span className="cg-ts-rowhead">
            {editable ? (
              <input
                className="cg-ts-rowinput"
                value={row.label}
                maxLength={TS_ROW_LABEL_MAX}
                placeholder="Note β€” type a heading for this section"
                aria-label="Note row label"
                onChange={(e) => onEditRow({ label: e.target.value })}
              />
            ) : (
              <span className="cg-ts-rowlabel">{row.label}</span>
            )}
            <RowTools
              style={style}
              editable={editable}
              onStyle={onStyle}
              onRemove={onRemove}
              label={row.label || "note row"}
            />
          </span>
        </th>
      </tr>
    );
  }

  return (
    <>
      <tr className={rowCls}>
        <th scope="row" className="cg-ts-stick">
          <span className="cg-ts-rowhead">
            <span className="cg-ts-rowmain">
              {row.kind === "formula" ? (
                editable ? (
                  <input
                    className="cg-ts-rowinput"
                    value={row.label}
                    maxLength={TS_ROW_LABEL_MAX}
                    placeholder="Formula row name"
                    aria-label="Formula row label"
                    onChange={(e) => onEditRow({ label: e.target.value })}
                  />
                ) : (
                  <span className="cg-ts-rowlabel">{row.label}</span>
                )
              ) : (
                <button
                  type="button"
                  className="cg-ts-rowbtn"
                  onClick={onToggleChart}
                  aria-pressed={charted}
                  title={charted ? "Show as a row of numbers" : "Show as a line"}
                >
                  {row.label}
                </button>
              )}
              {/* R1 β€” the metric's OWN window. Two rows under the same month headings can be
                  a cumulative year-to-date and a trailing 90 days; without this line they
                  look like the same kind of number. */}
              {row.sublabel && <span className="cg-ts-rowsub">{row.sublabel}</span>}
              {row.kind === "formula" &&
                (editable ? (
                  <input
                    className="cg-ts-rowinput cg-ts-rowexpr"
                    value={row.expr ?? ""}
                    maxLength={TS_MAX_EXPR}
                    spellCheck={false}
                    placeholder="= [Sales] - [Returns]"
                    aria-label="Formula"
                    onChange={(e) => onEditRow({ expr: e.target.value })}
                  />
                ) : (
                  <span className="cg-ts-rowsub">{row.expr}</span>
                ))}
            </span>
            <RowTools
              style={style}
              editable={editable}
              onStyle={onStyle}
              onRemove={onRemove}
              label={row.label || "row"}
            />
          </span>
        </th>
        {row.cells.map((c, i) => {
          const col = sheet.columns[i];
          const cellStyle = resolveTsStyle(styles, row.id, col?.key);
          return (
            <td
              key={col?.key ?? i}
              className={
                (c.partial ? "is-partial" : "") + (cellStyle.bold ? " is-bold" : "") || undefined
              }
            >
              {/* item 6 β€” `tsDisplayNumber`, never an inline toLocaleString: the CSV calls the
                  same function, and that is the only thing making "the file matches the sheet"
                  a property rather than a coincidence. */}
              {formatTsValue(c.value, tsDisplayNumber)}
            </td>
          );
        })}
        <td className="cg-ts-total">
          {/* An avg/min/max row has NO total β€” the cell stays empty rather than carrying an
              average of averages. See timeSeriesData's header note (2). Formula and note rows
              carry none either: an arbitrary expression is not additive across periods. */}
          {row.total == null ? "" : tsDisplayNumber(row.total)}
        </td>
        {sparkline && (
          <td className="cg-ts-spark">
            <Sparkline values={row.cells.map((c) => c.value)} label={row.label} />
          </td>
        )}
      </tr>
      {row.deltas.map((d) => (
        <TsDeltaRow key={d.kind} delta={d} sparkline={sparkline} />
      ))}
      {charted && (
        <tr className="cg-ts-chartrow">
          <td colSpan={colCount}>
            {spec ? (
              <VegaLiteChart spec={spec} label={`${row.label} over time`} />
            ) : (
              <div className="cg-ts-note">
                Nothing to plot β€” every period for this metric is unanswered.
              </div>
            )}
          </td>
        </tr>
      )}
    </>
  );
}

/**
 * One comparison sub-row.
 *
 * ONE typography for all four (item 18's "standardized type"): the same 2xs size, the sign
 * carried by a `-deep` tint, refusals as "β€”". A comparison that cannot be answered AT ALL
 * (no year in the span; year-to-date growth asked of a trailing-90 row) renders its dashes and
 * the sheet's footnotes say why once β€” the alternative is a column of dashes indistinguishable
 * from missing data.
 */
function TsDeltaRow({
  delta,
  sparkline,
}: {
  delta: TsDeltaSubRow;
  sparkline: boolean;
}) {
  return (
    <tr className="cg-ts-delta">
      <th scope="row" className="cg-ts-stick">
        {delta.label}
      </th>
      {delta.values.map((v, i) => (
        <td key={i} className={v == null ? undefined : v >= 0 ? "is-up" : "is-down"}>
          {delta.percent
            ? formatTsDelta(v)
            : v == null
              ? "β€”"
              : `${v > 0 ? "+" : ""}${tsDisplayNumber(v)}`}
        </td>
      ))}
      <td className="cg-ts-total" />
      {sparkline && <td className="cg-ts-spark" />}
    </tr>
  );
}

/**
 * The trend column: a hand-rolled polyline, no library.
 *
 * ⚠ Gaps BREAK the line rather than being bridged. A stroke drawn straight across an
 * unanswerable period asserts a value for it β€” the same lie the table refuses one cell to the
 * left, at 72 pixels wide.
 */
function Sparkline({ values, label }: { values: (number | null)[]; label: string }) {
  const segments = useMemo(
    () => sparklineSegments(values, SPARK_W, SPARK_H),
    [values]
  );
  if (!segments.length) return <span className="cg-ts-sparkempty">β€”</span>;
  const answered = values.filter((v) => v != null).length;
  return (
    <svg
      className="cg-ts-sparksvg"
      width={SPARK_W}
      height={SPARK_H}
      viewBox={`0 0 ${SPARK_W} ${SPARK_H}`}
      role="img"
      aria-label={`${label}: trend over ${answered} of ${values.length} periods`}
    >
      {segments.map((s, i) => (
        <polyline
          key={i}
          points={sparklinePoints(s)}
          fill="none"
          stroke="currentColor"
          strokeWidth="1.25"
          strokeLinejoin="round"
          strokeLinecap="round"
        />
      ))}
    </svg>
  );
}