taxa-server 0.1.0

axum web server for taxa: reproduces the HTTP contract + serves the embedded D3 frontend.
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
// Generic, manifest-driven sidebar + shared control state. Renders the
// treemap / line / scatter / detail sidebars from the dataset config and
// exposes the getter + event surface the viz modules consume.

import { API } from "/static/api.js";

// Escape dataset-derived strings (filter option values, labels) before innerHTML.
const esc = (s) => String(s ?? "").replace(/[&<>"']/g,
  (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));

let M = null;                      // the manifest
let activeTab = "treemap";

// ── lookups ──────────────────────────────────────────────────────────
const metricsById = () => {
  const o = {};
  for (const m of (M?.metrics || [])) o[m.id] = m;
  return o;
};
export const metricLabel = (id) => (metricsById()[id]?.label) || id;

// ── state (seeded from the manifest in setManifest) ──────────────────
let treemapAxis, treemapMetric, treemapLevels;
// Bounding knobs (govern the "+N others" fold), overridable from the sidebar.
// treemapMode toggles windowed (per-branch top-K, uses branch cap + lookahead) vs
// full (whole-tree top-K, uses leaf cap). The *Default copies are captured from the
// manifest so the sidebar "Reset" can restore them.
let treemapBranchCap, treemapLeafCap, treemapLookahead, treemapMode;
let treemapBranchCapDefault, treemapLeafCapDefault, treemapLookaheadDefault, treemapModeDefault;
let treemapFilters = {};                       // {facetId: value}
let geoMap = null, geoMetric = null, geoOutline = false;   // Geo (map) view state
// Layer registry (Stage 0 backbone): the list of every geography the Geo view can
// offer. `geoMap` holds the selected geography id. Built-in geographies (states/
// counties/countries) route through the Rust /api/geo path; `static` ones load a
// TopoJSON + a metric-values JSON straight from /static/vendor/geo. Loaded async
// from registry.json (see loadGeoRegistry); null until then → fall back to the
// manifest's built-in maps so the view still works without the registry.
let geoRegistry = null;
const geoLayerCache = {};   // geographyId -> {metrics:[{id,label,unit}], values:{geoid:{mid:val}}}
let geoColormap = "Blues", geoScale = "linear", geoLegendPos = "bl-h", geoLegendSize = 100, geoRes = "low";
let geoAnimType = "smooth", geoAnimDur = 600, geoEasing = "cubicInOut";  // zoom animation
let geoProjection = "equalEarth";  // world-map projection (ignored by US Albers maps)
// Sequential colormaps offered in the map sidebar (name -> d3 interpolator).
// `div: true` = a two-sided (diverging) map, rendered with a midpoint (0 when the
// data straddles zero, e.g. Net) instead of a one-ended sequential ramp.
export const CMAPS = [
  // ── Sequential ──
  { name: "Blues", interp: "interpolateBlues" },
  { name: "Greens", interp: "interpolateGreens" },
  { name: "Oranges", interp: "interpolateOranges" },
  { name: "Reds", interp: "interpolateReds" },
  { name: "Purples", interp: "interpolatePurples" },
  { name: "Greys", interp: "interpolateGreys" },
  { name: "Viridis", interp: "interpolateViridis" },
  { name: "Magma", interp: "interpolateMagma" },
  { name: "Inferno", interp: "interpolateInferno" },
  { name: "Plasma", interp: "interpolatePlasma" },
  { name: "Cividis", interp: "interpolateCividis" },
  { name: "Turbo", interp: "interpolateTurbo" },
  { name: "Warm", interp: "interpolateWarm" },
  { name: "Cool", interp: "interpolateCool" },
  { name: "Cubehelix", interp: "interpolateCubehelixDefault" },
  { name: "YlGnBu", interp: "interpolateYlGnBu" },
  { name: "YlOrRd", interp: "interpolateYlOrRd" },
  { name: "GnBu", interp: "interpolateGnBu" },
  { name: "BuPu", interp: "interpolateBuPu" },
  { name: "PuBuGn", interp: "interpolatePuBuGn" },
  { name: "YlGn", interp: "interpolateYlGn" },
  // ── Diverging (two-sided) ──
  { name: "RdBu (diverging)", interp: "interpolateRdBu", div: true },
  { name: "RdYlBu (diverging)", interp: "interpolateRdYlBu", div: true },
  { name: "RdYlGn (diverging)", interp: "interpolateRdYlGn", div: true },
  { name: "Spectral (diverging)", interp: "interpolateSpectral", div: true },
  { name: "BrBG (diverging)", interp: "interpolateBrBG", div: true },
  { name: "PiYG (diverging)", interp: "interpolatePiYG", div: true },
  { name: "PRGn (diverging)", interp: "interpolatePRGn", div: true },
  { name: "PuOr (diverging)", interp: "interpolatePuOr", div: true },
  { name: "RdGy (diverging)", interp: "interpolateRdGy", div: true },
];
const cmapSwatch = (interp) =>
  `linear-gradient(to right, ${Array.from({ length: 11 }, (_, i) => d3[interp](i / 10)).join(",")})`;
let treemapOptions = {};                        // {facetId: [options]} for provider facets
let lineMetric, lineAgg, lineWindow, lineScale = "linear", lineResolution = "d";
let entityWindow, entityMetric, entityScale = "linear", entityResolution = "d",
    entityStyle = "line", entityShowMeta = false, entityMetric2 = "", entityTiling = "overlay";

export function setManifest(manifest) {
  M = manifest;
  const tv = M.views.treemap, sv = M.views.series, dv = M.views.detail;
  if (tv) {
    treemapAxis = tv.default_axis;
    treemapMetric = tv.default_size_by;
    treemapLevels = (tv.levels && tv.levels.default) || 2;
    treemapBranchCap = tv.branch_cap ?? 12;
    treemapLeafCap = tv.leaf_cap ?? 50;
    // Manifest lookahead: a number = windowed; null/absent = full tree. We keep a
    // concrete lookahead value (so the Windowed slider has something to show even
    // when the manifest ships full) and track the active mode separately.
    treemapMode = (typeof tv.lookahead === "number") ? "windowed" : "full";
    treemapLookahead = (typeof tv.lookahead === "number") ? tv.lookahead : 2;
    treemapBranchCapDefault = treemapBranchCap;
    treemapLeafCapDefault = treemapLeafCap;
    treemapLookaheadDefault = treemapLookahead;
    treemapModeDefault = treemapMode;
  }
  if (sv) {
    // The plotted metric MUST be a SERIES metric (the series frame may be
    // narrower than the treemap). Seed from the treemap's size-by only when it's
    // actually a series metric; otherwise the series view's first metric.
    const seriesMetrics = (sv.metrics && sv.metrics.length) ? sv.metrics : [];
    lineMetric = (treemapMetric && seriesMetrics.includes(treemapMetric))
      ? treemapMetric
      : (seriesMetrics[0] || treemapMetric);
    lineAgg = (metricsById()[lineMetric]?.default_agg) || "sum";
    lineWindow = sv.default_window;
    // Seed the resolution from the series view's declared default (or its first
    // allowed resolution) — NOT a hardcoded "d". A frame restricted to ["w"]
    // must default to a VALID resolution the now-frame-scoped /api/series accepts.
    lineResolution = sv.default_resolution ||
      (sv.resolutions && sv.resolutions[0]) || "d";
  }
  const gv = M.views.geo;
  if (gv) {
    geoMap = gv.default_map || (gv.maps && gv.maps[0] && gv.maps[0].id);
    geoMetric = (tv && tv.default_size_by) || (tv && tv.size_by && tv.size_by[0]);
    geoOutline = gv.default_outline === true;
    geoColormap = gv.default_colormap || "Blues";
    geoScale = gv.default_scale || "linear";
    geoLegendPos = "bl-h";
    geoLegendSize = 100;
    geoRes = gv.default_res || "low";
    geoProjection = gv.default_projection || "equalEarth";
    geoAnimType = "direct"; geoAnimDur = 600; geoEasing = "expOut";
    readGeoUrl();   // URL overrides the defaults above (shareable views)
  }
  if (dv) {
    entityWindow = (dv.windows && dv.windows[0] && dv.windows[0].id) || "1y";
    entityMetric = (dv.series_metrics && dv.series_metrics[0]) || "";
    // Seed the detail resolution from the detail view's declared default (or its
    // first allowed resolution) — NOT a hardcoded "d". For a frame that only
    // allows ["w","m","y"] the first detail fetch must send a VALID resolution,
    // not the global "d" the server would reject.
    entityResolution = dv.default_resolution ||
      (dv.resolutions && dv.resolutions[0]) || "d";
    // No chartable series -> show the facts panel by default (it's all there is).
    entityShowMeta = !(dv.series_metrics && dv.series_metrics.length);
  }
}

// ── getters consumed by the viz modules ──────────────────────────────
export const getManifest = () => M;
// ── Geo layer registry (geography selector + static layer loading) ───
export const getGeoRegistry = () => geoRegistry;
export const geoGeographyById = (id) =>
  (geoRegistry && geoRegistry.geographies.find(g => g.id === id)) || null;
export const getGeoLayer = (id) => geoLayerCache[id] || null;

// Fetch + cache registry.json. Best-effort: on failure the Geo view falls back to
// the manifest's built-in maps (county/state/world), so this never blocks the app.
async function loadGeoRegistry() {
  if (geoRegistry) return geoRegistry;
  try {
    geoRegistry = await (await fetch("/static/vendor/geo/registry.json")).json();
  } catch { geoRegistry = null; }
  return geoRegistry;
}

// Load + cache a static geography's metric layer: merge every installed family file
// ({metrics:[…], values:{geoid:{mid:val}}}) into one GEOID-keyed table. Modular —
// each family is an independent file; whichever are present contribute their metrics.
async function loadGeoLayer(geo) {
  if (!geo || geo.kind !== "static") return null;
  if (geoLayerCache[geo.id]) return geoLayerCache[geo.id];
  const merged = { metrics: [], values: {} };
  const seen = new Set();
  for (const fam of geo.families || []) {
    let data;
    try { data = await (await fetch(fam.file)).json(); } catch { continue; }
    for (const m of data.metrics || []) {
      if (seen.has(m.id)) continue;
      seen.add(m.id); merged.metrics.push(m);
    }
    for (const [gid, vals] of Object.entries(data.values || {}))
      merged.values[gid] = Object.assign(merged.values[gid] || {}, vals);
  }
  geoLayerCache[geo.id] = merged;
  return merged;
}

// The metric definitions ({id,label,unit}) valid for the CURRENT geography. For a
// static layer these come from its loaded files; for a built-in map they're the
// manifest treemap's size-by metrics. Drives the sidebar "Color by" list + greying.
export function getGeoMetricDefs() {
  const geo = geoGeographyById(geoMap);
  if (geo && geo.kind === "static") {
    const layer = geoLayerCache[geo.id];
    return layer ? layer.metrics : [];
  }
  const tv = M && M.views.treemap;
  return ((tv && tv.size_by) || (geoMetric ? [geoMetric] : []))
    .map(id => ({ id, label: metricLabel(id), unit: metricUnit(id) }));
}
// Layer-aware label/unit (static metrics aren't in the manifest) — used by geomap.js.
export function geoMetricLabel(id) {
  const layer = geoLayerCache[geoMap];
  const m = layer && layer.metrics.find(x => x.id === id);
  return m ? m.label : metricLabel(id);
}
export function geoMetricUnit(id) {
  const layer = geoLayerCache[geoMap];
  const m = layer && layer.metrics.find(x => x.id === id);
  return m ? (m.unit || "number") : metricUnit(id);
}
// ── Geo (map) view state ─────────────────────────────────────────────
export const getGeoMap = () => geoMap;
export const getGeoRes = () => geoRes;
export function setGeoRes(v) { if (!v || v === geoRes) return; geoRes = v; renderSidebar(); geoData(); }
export const getGeoMetric = () => geoMetric;
export const getGeoOutline = () => geoOutline;
export const getGeoColormap = () => geoColormap;
export const getGeoScale = () => geoScale;
export const getGeoLegendPos = () => geoLegendPos;
export const getGeoLegendSize = () => geoLegendSize;
// DATA changes (map/metric) refetch + rebuild; STYLE changes (colormap/scale/
// legend/size/outline) only recolor + redraw the legend — no map re-render.
const geoData = () => { syncGeoUrl(); document.dispatchEvent(new CustomEvent("geo-data-changed")); };
const geoStyle = () => { syncGeoUrl(); document.dispatchEvent(new CustomEvent("geo-style-changed")); };
// Projection change rebuilds geometry from cache (re-project) WITHOUT a refetch.
const geoProj = () => { syncGeoUrl(); document.dispatchEvent(new CustomEvent("geo-proj-changed")); };
export const getGeoProjection = () => geoProjection;
export function setGeoProjection(v) { if (!v || v === geoProjection) return; geoProjection = v; renderSidebar(); geoProj(); }

// Persist every map-sidebar setting (and active filters) to the URL so a view is
// shareable/reloadable. Geo params are namespaced g_*; filters as f_<id>.
export function syncGeoUrl() {
  if (!M || !M.views.geo) return;
  const u = new URL(location.href), p = u.searchParams;
  p.set("g_map", geoMap);
  p.set("g_metric", geoMetric);
  p.set("g_cmap", geoColormap);
  p.set("g_scale", geoScale);
  p.set("g_legend", geoLegendPos);
  p.set("g_lsize", String(geoLegendSize));
  p.set("g_outline", geoOutline ? "1" : "0");
  p.set("g_anim", geoAnimType);
  p.set("g_dur", String(geoAnimDur));
  p.set("g_ease", geoEasing);
  p.set("g_res", geoRes);
  p.set("g_proj", geoProjection);
  for (const k of [...p.keys()]) if (k.startsWith("f_")) p.delete(k);
  for (const [k, v] of Object.entries(getTreemapFilters()))
    p.set("f_" + k, Array.isArray(v) ? v.join(",") : String(v));
  const m = location.search.match(/[?&]focus=([^&]*)/);
  p.delete("focus");
  const qs = p.toString(), focus = m ? "focus=" + m[1] : "";
  const full = [qs, focus].filter(Boolean).join("&");
  history.replaceState({}, "", u.pathname + (full ? "?" + full : ""));
}

// Seed geo state + filters from the URL (called from setManifest, before defaults).
function readGeoUrl() {
  if (!M || !M.views.geo) return;
  const p = new URL(location.href).searchParams, tv = M.views.treemap;
  if (p.get("g_map")) geoMap = p.get("g_map");
  if (p.get("g_metric")) geoMetric = p.get("g_metric");
  if (p.get("g_cmap")) geoColormap = p.get("g_cmap");
  if (p.get("g_scale")) geoScale = p.get("g_scale");
  if (p.get("g_legend")) geoLegendPos = p.get("g_legend");
  if (p.get("g_lsize")) geoLegendSize = Math.max(50, Math.min(300, parseInt(p.get("g_lsize"), 10) || 100));
  if (p.get("g_outline") != null) geoOutline = p.get("g_outline") === "1";
  if (p.get("g_anim")) geoAnimType = p.get("g_anim");
  if (p.get("g_dur")) geoAnimDur = Math.max(0, Math.min(1200, parseInt(p.get("g_dur"), 10) || 600));
  if (p.get("g_ease")) geoEasing = p.get("g_ease");
  if (p.get("g_res")) geoRes = p.get("g_res");
  if (p.get("g_proj")) geoProjection = p.get("g_proj");
  for (const f of (tv && tv.filters) || []) {
    const raw = p.get("f_" + f.id);
    if (raw == null) continue;
    treemapFilters[f.id] = f.control === "multiselect" ? raw.split(",") : raw;
  }
}

// Keep the URL in sync when filters change on the map tab (geo control changes are
// handled in geoChanged), and write the full state when the map view opens.
document.addEventListener("treemap-filters-changed", () => { if (activeTab === "map") syncGeoUrl(); });
document.addEventListener("view-changed", (e) => { if (e.detail === "map") syncGeoUrl(); });
export function setGeoMap(v) {
  if (!v || v === geoMap) return;
  const geo = geoGeographyById(v);
  if (geo && !geo.available) return;          // greyed options are unselectable
  geoMap = v;
  if (geo && geo.kind === "static") {
    // Load the layer, then snap the active metric to one this geography offers and
    // refresh. Render once now (sidebar reflects the new geography immediately) and
    // again after the async load resolves with the real metric list.
    renderSidebar();
    loadGeoLayer(geo).then(layer => {
      if (!layer.metrics.find(m => m.id === geoMetric))
        geoMetric = layer.metrics[0] && layer.metrics[0].id;
      renderSidebar(); geoData();
    }).catch(() => { renderSidebar(); geoData(); });
    return;
  }
  // Built-in map: ensure the active metric is a valid manifest size-by metric.
  const tv = M && M.views.treemap;
  const valid = (tv && tv.size_by) || [];
  if (valid.length && !valid.includes(geoMetric))
    geoMetric = (tv && tv.default_size_by) || valid[0];
  renderSidebar(); geoData();
}
export function setGeoMetric(v) { if (!v || v === geoMetric) return; geoMetric = v; renderSidebar(); geoStyle(); }
export function setGeoOutline(on) { on = !!on; if (on === geoOutline) return; geoOutline = on; renderSidebar(); geoStyle(); }
export function setGeoColormap(v) { if (!v || v === geoColormap) return; geoColormap = v; renderSidebar(); geoStyle(); }
export function setGeoScale(v) { if (!v || v === geoScale) return; geoScale = v; renderSidebar(); geoStyle(); }
export function setGeoLegendPos(v) { if (!v || v === geoLegendPos) return; geoLegendPos = v; renderSidebar(); geoStyle(); }
export function setGeoLegendSize(v) {
  const n = Math.max(50, Math.min(300, parseInt(v, 10) || 100));
  if (n === geoLegendSize) return;
  geoLegendSize = n; geoStyle();   // no renderSidebar — avoid DOM churn mid-drag
}
// Zoom-animation settings only affect the NEXT zoom — no map redraw needed.
export const getGeoAnimType = () => geoAnimType;
export const getGeoAnimDuration = () => geoAnimDur;
export const getGeoEasing = () => geoEasing;
export function setGeoAnimType(v) { if (!v || v === geoAnimType) return; geoAnimType = v; renderSidebar(); syncGeoUrl(); }
export function setGeoEasing(v) { if (!v || v === geoEasing) return; geoEasing = v; renderSidebar(); syncGeoUrl(); }
export function setGeoAnimDur(v) {
  const n = Math.max(0, Math.min(1200, parseInt(v, 10) || 0));
  if (n === geoAnimDur) return;
  geoAnimDur = n; syncGeoUrl();     // no renderSidebar — avoid churn mid-drag
}

function legendPosSelectHTML(cur) {
  const grp = (lab, opts) => `<optgroup label="${lab}">` +
    opts.map(([v, t]) => `<option value="${v}"${v === cur ? " selected" : ""}>${esc(t)}</option>`).join("") +
    `</optgroup>`;
  return `<select id="geo-legendpos" class="filter-select" style="width:100%;box-sizing:border-box;margin-bottom:16px">` +
    grp("Spanning", [["span-bottom", "Bottom (full)"], ["span-top", "Top (full)"], ["span-left", "Left (full)"], ["span-right", "Right (full)"]]) +
    grp("Centered", [["bottom", "Bottom center"], ["top", "Top center"], ["left", "Left center"], ["right", "Right center"]]) +
    grp("Corners", [
      ["bl-h", "Bottom-left, horizontal"], ["bl-v", "Bottom-left, vertical"],
      ["br-h", "Bottom-right, horizontal"], ["br-v", "Bottom-right, vertical"],
      ["tl-h", "Top-left, horizontal"], ["tl-v", "Top-left, vertical"],
      ["tr-h", "Top-right, horizontal"], ["tr-v", "Top-right, vertical"],
    ]) + `</select>`;
}

// Geography selector: a grouped <select> over the registry. Unavailable geographies
// render as disabled (greyed) <option>s with a short reason, so the full menu of
// planned layers is always visible and installing a module lights its row up.
function geographySelectHTML(cur) {
  const geos = (geoRegistry && geoRegistry.geographies) || null;
  if (!geos) {   // registry absent → fall back to manifest built-in maps
    const cells = ((M.views.geo && M.views.geo.maps) || []).map(m => [m.id, m.label || m.id]);
    return segHTML("geo-map", cells, cur);
  }
  const order = ["National", "Sub-county", "High-resolution"];
  const byGroup = {};
  for (const g of geos) (byGroup[g.group] = byGroup[g.group] || []).push(g);
  const groups = order.filter(o => byGroup[o]).concat(Object.keys(byGroup).filter(k => !order.includes(k)));
  const opt = (g) => {
    const note = g.available ? "" : `  ${g.note || "unavailable"}`;
    return `<option value="${esc(g.id)}"${g.id === cur ? " selected" : ""}` +
      `${g.available ? "" : " disabled"}>${esc(g.label)}${esc(note)}</option>`;
  };
  return `<select id="geo-map-sel" class="filter-select" style="width:100%;box-sizing:border-box;margin-bottom:16px">` +
    groups.map(gn => `<optgroup label="${esc(gn)}">${byGroup[gn].map(opt).join("")}</optgroup>`).join("") +
    `</select>`;
}

// Custom colormap dropdown: each row shows the name + a gradient preview swatch.
function cmapDropdownHTML(cur) {
  const c = CMAPS.find(x => x.name === cur) || CMAPS[0];
  const row = (x) =>
    `<div class="cmap-opt" data-v="${esc(x.name)}"><span class="cmap-swatch" style="background:${cmapSwatch(x.interp)}"></span><span>${esc(x.name)}</span></div>`;
  return `<div class="cmap-dd" id="cmap-dd">` +
    `<button type="button" class="cmap-cur" id="cmap-toggle"><span class="cmap-swatch" style="background:${cmapSwatch(c.interp)}"></span><span>${esc(c.name)}</span><span class="cmap-caret"></span></button>` +
    `<div class="cmap-list" id="cmap-list" style="display:none">${CMAPS.map(row).join("")}</div></div>`;
}

function renderMapSidebar(root) {
  const gv = M.views.geo, tv = M.views.treemap;
  if (!gv) { root.innerHTML = ""; return; }
  const metricCells = getGeoMetricDefs().map(m => [m.id, m.label]);
  // Projection applies to non-US maps; resolution tiers only exist for the built-in
  // US atlas (county/state). Determine both from the active geography's registry row
  // (falling back to id heuristics when the registry isn't loaded).
  const geo = geoGeographyById(geoMap);
  const isUS = geo ? !!geo.us : (geoMap === "states" || geoMap === "counties");
  const isBuiltin = geo ? geo.kind === "builtin" : true;
  // All built-in maps now ship resolution tiers (US atlas: 10m/500k; world: 110m/50m).
  const showRes = isBuiltin;
  const isUSmap = isUS;
  const projCells = [["naturalEarth", "Flat"], ["orthographic", "Globe"]];
  root.innerHTML =
    label("Geography") + geographySelectHTML(geoMap) +
    (showRes ? label("Resolution") + segHTML("geo-res", [["low", "Low"], ["med", "Med"], ["high", "High"]], geoRes) : "") +
    (isUSmap ? "" : label("Projection") + segHTML("geo-proj", projCells, geoProjection)) +
    label("Color by") + segHTML("geo-metric", metricCells, geoMetric) +
    label("Colormap") + cmapDropdownHTML(geoColormap) +
    label("Color scale") + segHTML("geo-scale", [["linear", "Linear"], ["log", "Log"]], geoScale) +
    label("Legend position") + legendPosSelectHTML(geoLegendPos) +
    label("Colorbar size") + sliderHTML("legendsize", geoLegendSize, 50, 300) +
    label("State outlines") + segHTML("geo-outline", [["off", "Off"], ["on", "On"]], geoOutline ? "on" : "off") +
    label("Zoom animation") + segHTML("geo-anim", [["smooth", "Smooth"], ["direct", "Direct"]], geoAnimType) +
    label("Zoom easing") + segHTML("geo-ease", [["cubicInOut", "Cubic"], ["cubicOut", "Out"], ["quadOut", "Quad"], ["expOut", "Exp"], ["linear", "Linear"]], geoEasing) +
    label("Zoom duration (ms)") + sliderHTML("zoomdur", geoAnimDur, 0, 1200) +
    filtersHTML((tv && tv.filters) || []);
  const geoSel = root.querySelector("#geo-map-sel");
  if (geoSel) geoSel.addEventListener("change", (e) => setGeoMap(e.target.value));
  else wireSeg(root, "geo-map", setGeoMap);   // fallback (registry absent)
  wireSeg(root, "geo-res", setGeoRes);
  wireSeg(root, "geo-proj", setGeoProjection);
  wireSeg(root, "geo-metric", setGeoMetric);
  wireSeg(root, "geo-scale", setGeoScale);
  wireSeg(root, "geo-outline", v => setGeoOutline(v === "on"));
  const lp = root.querySelector("#geo-legendpos");
  if (lp) lp.addEventListener("change", (e) => setGeoLegendPos(e.target.value));
  wireSlider(root, "legendsize", setGeoLegendSize);
  wireSeg(root, "geo-anim", setGeoAnimType);
  wireSeg(root, "geo-ease", setGeoEasing);
  wireSlider(root, "zoomdur", setGeoAnimDur);
  wireFilters(root, (tv && tv.filters) || []);
  // Custom colormap dropdown open/close + selection.
  const toggle = root.querySelector("#cmap-toggle"), listEl = root.querySelector("#cmap-list");
  if (toggle && listEl) {
    toggle.addEventListener("click", (e) => {
      e.stopPropagation();
      const open = listEl.style.display !== "none";
      listEl.style.display = open ? "none" : "block";
      if (!open) setTimeout(() => document.addEventListener("click", function h() {
        listEl.style.display = "none"; document.removeEventListener("click", h);
      }), 0);
    });
    for (const opt of root.querySelectorAll(".cmap-opt"))
      opt.addEventListener("click", () => setGeoColormap(opt.dataset.v));
  }
}
export const getTreemapAxis = () => treemapAxis;
export const getTreemapMetric = () => treemapMetric;
export const getTreemapLevels = () => treemapLevels;
// Prefetch config: lookahead = a number (windowed/bounded fetch, N levels beyond
// the display) or null (load the whole tree at once). Absent → treat as full.
export const getTreemapLookahead = () => (treemapMode === "full" ? null : treemapLookahead);
export const getTreemapBranchCap = () => treemapBranchCap;
export const getTreemapLeafCap = () => treemapLeafCap;
export const getTreemapMode = () => treemapMode;
export const getTreemapFilters = () => {
  const out = {};
  for (const [k, v] of Object.entries(treemapFilters))
    if (v != null && v !== "" && !(Array.isArray(v) && v.length === 0)) out[k] = v;
  return out;
};
export function getTreemapTitle() {
  // Root node / breadcrumb label: "All <plural>" (e.g. "All Rounds") for the whole
  // tree, with any active filters appended.
  const plural = M?.entity_noun_plural;
  const base = plural ? `All ${plural}` : (M?.title || "All");
  const parts = Object.entries(getTreemapFilters()).map(([k, v]) =>
    Array.isArray(v) ? v.join("/") : String(v));
  return parts.length ? `${base} · ${parts.join(", ")}` : base;
}
export const getLineMetric = () => lineMetric;
export const getLineAgg = () => lineAgg;
export const getLineWindow = () => lineWindow;
export const getLineScale = () => lineScale;
export const getLineResolution = () => lineResolution;
export const getEntityWindow = () => entityWindow;
export const getEntityMetric = () => entityMetric;
export const getEntityScale = () => entityScale;
export const getEntityResolution = () => entityResolution;
export const getEntityStyle = () => entityStyle;
export const getEntityShowMeta = () => entityShowMeta;
export const getEntityMetric2 = () => entityMetric2;
export const getEntityTiling = () => entityTiling;
export const getSelection = () => null;          // scatter plots the full set
export const getSizeByMetrics = () => (M?.views?.treemap?.size_by) || [];
export const metricUnit = (id) => (metricsById()[id]?.unit) || "number";

// ── URL sync (axis/metric/levels/filters; treemap.js owns ?focus=) ───
export function syncTreemapPickerUrl() {
  const u = new URL(location.href), p = u.searchParams;
  const tv = M.views.treemap;
  const set = (k, v, def) => (v === def ? p.delete(k) : p.set(k, v));
  set("axis", treemapAxis, tv.default_axis);
  set("metric", treemapMetric, tv.default_size_by);
  set("levels", String(treemapLevels), String((tv.levels && tv.levels.default) || 2));
  // keep ?focus= raw (treemap.js manages it)
  const m = location.search.match(/[?&]focus=([^&]*)/);
  p.delete("focus");
  const qs = p.toString();
  const focus = m ? "focus=" + m[1] : "";
  const full = [qs, focus].filter(Boolean).join("&");
  history.replaceState({}, "", u.pathname + (full ? "?" + full : ""));
}
export function reloadTreemapPickerFromUrl() {
  const p = new URL(location.href).searchParams;
  const tv = M.views.treemap;
  treemapAxis = p.get("axis") || tv.default_axis;
  treemapMetric = p.get("metric") || tv.default_size_by;
  const lv = parseInt(p.get("levels"), 10);
  treemapLevels = Number.isFinite(lv) ? lv : ((tv.levels && tv.levels.default) || 2);
  if (activeTab === "treemap") renderSidebar();
}

// ── lifecycle ────────────────────────────────────────────────────────
export async function initSidebar() {
  // Geo layer registry (Stage 0): load before the first sidebar render so the
  // Geography selector lists every geography (greying unavailable ones). If a
  // static geography is active (e.g. restored from the URL), preload its layer
  // and snap the active metric to one it offers.
  if (M.views.geo) {
    await loadGeoRegistry();
    const geo = geoGeographyById(geoMap);
    if (geo && geo.kind === "static") {
      const layer = await loadGeoLayer(geo);
      if (layer && !layer.metrics.find(m => m.id === geoMetric))
        geoMetric = layer.metrics[0] && layer.metrics[0].id;
    }
  }
  // Pre-fetch dynamic filter options for provider-backed facets.
  const tv = M.views.treemap;
  if (tv) {
    for (const f of tv.filters || []) {
      if (f.options_provider) {
        try { treemapOptions[f.id] = await API.filterOptions(f.id); } catch { treemapOptions[f.id] = []; }
      } else if (f.options) {
        treemapOptions[f.id] = f.options;
      }
    }
    // Seed manifest-declared filter defaults so a view can open on a specific
    // value (e.g. the latest year) instead of "Any" / the whole-history sum.
    for (const f of tv.filters || []) {
      if (f.default == null) continue;
      if (f.control === "multiselect") {
        if (treemapFilters[f.id] === undefined)
          treemapFilters[f.id] = (Array.isArray(f.default) ? f.default : [f.default]).map(String);
      } else if (f.control === "range") {
        if (Array.isArray(f.default)) {
          if (treemapFilters[f.id + "_min"] === undefined) treemapFilters[f.id + "_min"] = f.default[0];
          if (treemapFilters[f.id + "_max"] === undefined) treemapFilters[f.id + "_max"] = f.default[1];
        }
      } else if (treemapFilters[f.id] === undefined) {
        treemapFilters[f.id] = String(f.default);
      }
    }
  }
  renderSidebar();
}

export function setActiveTab(tab) {
  activeTab = tab;
  if (M) renderSidebar();
}

function renderSidebar() {
  const root = document.querySelector("#sidebar-content");
  if (!root || !M) return;
  if (activeTab === "map") return renderMapSidebar(root);
  if (activeTab === "treemap") return renderTreemapSidebar(root);
  if (activeTab === "timeseries") return renderLineSidebar(root);
  if (activeTab === "scatter") return renderScatterSidebar(root);
  if (activeTab === "entity") return renderEntitySidebar(root);
  root.innerHTML = "";
}

// ── small control helpers ────────────────────────────────────────────
function segHTML(group, cells, current) {
  // cells: [value, label] or [value, label, disabled] tuples. Disabled cells render
  // greyed + unclickable (e.g. a size-by metric not valid for the current bucket).
  return `<div class="mode-tabs" data-group="${group}">` +
    cells.map(([v, lab, disabled]) =>
      `<button data-v="${esc(v)}"${disabled ? " disabled" : ""} class="${v === current ? "active" : ""}">${esc(lab)}</button>`).join("") +
    `</div>`;
}
function wireSeg(root, group, onPick) {
  for (const btn of root.querySelectorAll(`[data-group="${group}"] button`))
    if (!btn.disabled) btn.addEventListener("click", () => onPick(btn.dataset.v));
}
function label(text, cls = "") { return `<label class="picker-label ${cls}">${esc(text)}</label>`; }
// A range slider paired with an editable number input. Used for the treemap
// bounding knobs: drag the slider or type an exact value, both stay in sync.
function sliderHTML(id, value, min, max) {
  return `<div class="slider-row">` +
    `<input type="range" id="tm-${id}" min="${min}" max="${max}" step="1" value="${value}">` +
    `<input type="number" class="slider-val" id="tm-${id}-num" min="${min}" max="${max}" step="1" value="${value}"></div>`;
}
function wireSlider(root, id, setter) {
  const range = root.querySelector(`#tm-${id}`);
  const num = root.querySelector(`#tm-${id}-num`);
  if (!range) return;
  const lo = +range.min, hi = +range.max;
  // Dragging the slider fires `input` per tick → live preview; the setter is
  // unchanged (it clamps + dispatches), and the treemap throttles the re-fetches.
  // The number box mirrors the slider and lets you type an exact value; it's only
  // clamped to [lo,hi] on `change` (blur/enter) so partial typing isn't fought.
  const push = (v) => { range.value = v; if (num) num.value = v; setter(v); };
  range.addEventListener("input", () => push(range.value));
  range.addEventListener("change", () => push(range.value));
  if (num) {
    num.addEventListener("input", () => { range.value = num.value; setter(num.value); });
    num.addEventListener("change", () =>
      push(Math.max(lo, Math.min(hi, parseInt(num.value, 10) || lo))));
  }
}

// ── treemap control setters ──────────────────────────────────────────
// Shared by the sidebar pickers AND the keyboard shortcuts (shortcuts.js) so a
// key press and a click take the exact same path: mutate → re-render → sync URL
// → dispatch the change event the treemap view listens for. Each is a no-op when
// the value is unchanged or out of range.
export function setTreemapAxis(v) {
  if (!v || v === treemapAxis) return;
  treemapAxis = v;
  // Keep the user's size-by metric when it's still valid for the new bucket; otherwise
  // fall back to the axis's preferred metric (default_size_by) or its first valid one.
  const ax = (M?.views?.treemap?.axes || []).find(a => a.id === v);
  const valid = (ax && ax.size_by) || (M?.views?.treemap?.size_by) || [];
  if (valid.length && !valid.includes(treemapMetric))
    treemapMetric = (ax && ax.default_size_by) || valid[0];
  else if (ax && ax.default_size_by) treemapMetric = ax.default_size_by;
  renderSidebar();
  syncTreemapPickerUrl();
  document.dispatchEvent(new CustomEvent("treemap-axis-changed", { detail: v }));
}
export function setTreemapMetric(v) {
  if (!v || v === treemapMetric) return;
  treemapMetric = v;
  // Mirror onto the Line tab's plotted metric ONLY when it's a series metric
  // (else the Line tab would request a metric the series frame can't serve, 400).
  const sv = M.views.series;
  if (sv && (sv.metrics || []).includes(v)) {
    lineMetric = v;
    lineAgg = (metricsById()[v]?.default_agg) || "sum";
  }
  renderSidebar();
  syncTreemapPickerUrl();
  document.dispatchEvent(new CustomEvent("treemap-metric-changed", { detail: v }));
}
export function setTreemapLevels(n) {
  n = parseInt(n, 10);
  if (!Number.isFinite(n) || n === treemapLevels) return;
  const lv = (M?.views?.treemap?.levels) || { min: 1, max: 4 };
  if (n < lv.min || n > lv.max) return; // ignore an out-of-range level key
  treemapLevels = n;
  renderSidebar();
  syncTreemapPickerUrl();
  document.dispatchEvent(new CustomEvent("treemap-levels-changed", { detail: n }));
}
// Bounding knobs: how many children render per branch before the rest fold into
// "+N others". Changing any re-fetches the treemap (top_k is server-side). No
// renderSidebar() — the slider already shows its value, so don't churn the DOM
// mid-drag.
const _clampInt = (v, lo, hi) => {
  const n = parseInt(v, 10);
  return Number.isFinite(n) ? Math.max(lo, Math.min(hi, n)) : null;
};
export function setTreemapBranchCap(v) {
  const n = _clampInt(v, 1, 100); // engine clamps top_k to MAX_TOP_K (100)
  if (n === null || n === treemapBranchCap) return;
  treemapBranchCap = n;
  document.dispatchEvent(new CustomEvent("treemap-bounds-changed"));
}
export function setTreemapLeafCap(v) {
  const n = _clampInt(v, 1, 100);
  if (n === null || n === treemapLeafCap) return;
  treemapLeafCap = n;
  document.dispatchEvent(new CustomEvent("treemap-bounds-changed"));
}
export function setTreemapLookahead(v) {
  const n = _clampInt(v, 0, 12);
  if (n === null || n === treemapLookahead) return;
  treemapLookahead = n;
  document.dispatchEvent(new CustomEvent("treemap-bounds-changed"));
}
// Windowed ⇄ full. Swaps which cap is active, so re-render the sidebar (to show the
// right slider) AND re-fetch (lookahead null vs number changes the server top-K).
export function setTreemapMode(v) {
  if ((v !== "windowed" && v !== "full") || v === treemapMode) return;
  treemapMode = v;
  renderSidebar();
  document.dispatchEvent(new CustomEvent("treemap-bounds-changed"));
}
// Restore the bounding knobs to the manifest defaults (the sidebar "Reset" button).
export function resetTreemapBounds() {
  treemapMode = treemapModeDefault;
  treemapBranchCap = treemapBranchCapDefault;
  treemapLeafCap = treemapLeafCapDefault;
  treemapLookahead = treemapLookaheadDefault;
  renderSidebar();
  document.dispatchEvent(new CustomEvent("treemap-bounds-changed"));
}
// Prev/next cycle over an id list, used by the bracket shortcuts.
function cycleIds(ids, current, dir, set) {
  if (!ids.length) return;
  const i = ids.indexOf(current);
  set(ids[(i + dir + ids.length) % ids.length]);
}
export const cycleTreemapAxis = (dir) =>
  cycleIds((M?.views?.treemap?.axes || []).map(a => a.id), treemapAxis, dir, setTreemapAxis);
export const cycleTreemapMetric = (dir) =>
  cycleIds(M?.views?.treemap?.size_by || [], treemapMetric, dir, setTreemapMetric);

/** The active tab id ("treemap" | "timeseries" | "scatter" | "entity"). */
export const getActiveTab = () => activeTab;

// ── treemap sidebar ──────────────────────────────────────────────────
function renderTreemapSidebar(root) {
  const tv = M.views.treemap;
  const axisCells = tv.axes.map(a => [a.id, a.label]);
  // Size-by metrics not valid for the current bucket (axis.size_by whitelist) render
  // greyed/disabled rather than silently returning an empty treemap.
  const curAxis = tv.axes.find(a => a.id === treemapAxis);
  const validMetrics = (curAxis && curAxis.size_by) || tv.size_by;
  const sizeCells = tv.size_by.map(id => [id, metricLabel(id), !validMetrics.includes(id)]);
  const lv = tv.levels || { min: 1, max: 4, default: 2 };
  const levelCells = [];
  for (let n = lv.min; n <= lv.max; n++) levelCells.push([String(n), String(n)]);

  // Bounding knobs ("+N others"): a mode toggle picks the strategy, then only the
  // caps ACTIVE for that mode are shown. Windowed: branch cap (per-branch top-K) +
  // lookahead. Full: leaf cap (whole-tree top-K). A Reset restores manifest defaults.
  const windowed = treemapMode === "windowed";
  const bounding =
    label("Window mode") +
    segHTML("tmmode", [["windowed", "Windowed"], ["full", "Full"]], treemapMode) +
    (windowed
      ? label('Branch cap ("+N others")') + sliderHTML("branchcap", treemapBranchCap, 1, 100)
        + label("Lookahead") + sliderHTML("lookahead", treemapLookahead, 0, 12)
      : label('Leaf cap ("+N others")') + sliderHTML("leafcap", treemapLeafCap, 1, 100)) +
    `<button type="button" class="reset-bounds" id="tm-reset">Reset to defaults</button>`;

  root.innerHTML =
    label("Bucket by") + segHTML("axis", axisCells, treemapAxis) +
    label("Size by") + segHTML("metric", sizeCells, treemapMetric) +
    label("Levels") + segHTML("levels", levelCells, String(treemapLevels)) +
    filtersHTML(tv.filters || []) +
    `<div class="bounding-controls">${bounding}</div>`;

  // Pickers and keyboard shortcuts share the same setters (above).
  wireSeg(root, "axis", setTreemapAxis);
  wireSeg(root, "metric", setTreemapMetric);
  wireSeg(root, "levels", setTreemapLevels);
  wireFilters(root, tv.filters || []);
  wireSeg(root, "tmmode", setTreemapMode);
  wireSlider(root, "branchcap", setTreemapBranchCap);
  wireSlider(root, "leafcap", setTreemapLeafCap);
  wireSlider(root, "lookahead", setTreemapLookahead);
  const reset = root.querySelector("#tm-reset");
  if (reset) reset.addEventListener("click", resetTreemapBounds);
}

// ── filter facets (select / multiselect / range) ─────────────────────
function filtersHTML(facets) {
  return facets.map(f => {
    if (f.control === "range") {
      return label(`Filter  ${f.label}`, "filter") +
        `<div class="age-range">
           <input id="flt-${f.id}-min" type="number" placeholder="from" value="${treemapFilters[f.id + "_min"] ?? ""}">
           <span class="age-sep"></span>
           <input id="flt-${f.id}-max" type="number" placeholder="to" value="${treemapFilters[f.id + "_max"] ?? ""}">
         </div>`;
    }
    const opts = treemapOptions[f.id] || f.options || [];
    if (f.control === "multiselect") {
      // Selected values are stored as strings (from button data-v); option values
      // may be numbers (e.g. year from an int column), so compare as strings —
      // otherwise the active highlight never matches and toggles look unchanged.
      const sel = new Set((treemapFilters[f.id] || []).map(String));
      return label(`Filter  ${f.label}`, "filter") +
        `<div class="mode-tabs" data-group="flt-${f.id}">` +
        opts.map(o => `<button data-v="${esc(o)}" class="${sel.has(String(o)) ? "active" : ""}">${esc(o)}</button>`).join("") +
        `</div>`;
    }
    // select (real dropdown). Numeric options (e.g. years) sort high→low so the
    // latest is at the top; otherwise keep provider order (already alphabetical).
    const allNum = opts.length && opts.every(o => o !== "" && !isNaN(Number(o)));
    const sorted = allNum ? [...opts].sort((a, b) => Number(b) - Number(a)) : opts;
    const cur = treemapFilters[f.id] != null ? String(treemapFilters[f.id]) : "";
    return label(`Filter  ${f.label}`, "filter") +
      `<select id="flt-${f.id}" class="filter-select">` +
      `<option value="">Any</option>` +
      sorted.map(o => `<option value="${esc(o)}"${String(o) === cur ? " selected" : ""}>${esc(o)}</option>`).join("") +
      `</select>`;
  }).join("");
}
function wireFilters(root, facets) {
  const changed = () => document.dispatchEvent(new CustomEvent("treemap-filters-changed"));
  for (const f of facets) {
    if (f.control === "range") {
      for (const which of ["min", "max"]) {
        const el = root.querySelector(`#flt-${f.id}-${which}`);
        if (!el) continue;
        // Live preview as you type — the treemap throttles the resulting re-fetches.
        const apply = () => {
          const v = el.value.trim();
          treemapFilters[`${f.id}_${which}`] = v === "" ? null : parseInt(v, 10);
          syncTreemapPickerUrl(); changed();
        };
        el.addEventListener("input", apply);
        el.addEventListener("change", apply);
      }
    } else if (f.control === "multiselect") {
      for (const btn of root.querySelectorAll(`[data-group="flt-${f.id}"] button`))
        btn.addEventListener("click", () => {
          const set = new Set(treemapFilters[f.id] || []);
          set.has(btn.dataset.v) ? set.delete(btn.dataset.v) : set.add(btn.dataset.v);
          treemapFilters[f.id] = [...set];
          renderSidebar(); changed();
        });
    } else {
      // select: a real <select> dropdown. "" (the "Any" option) clears the filter.
      const el = root.querySelector(`#flt-${f.id}`);
      if (!el) continue;
      el.addEventListener("change", () => {
        treemapFilters[f.id] = el.value || null;
        changed();
      });
    }
  }
}

// ── line sidebar (shares axis/filters/focus from the treemap) ────────
function renderLineSidebar(root) {
  const sv = M.views.series, tv = M.views.treemap;
  // The plotted metric MUST come from the SERIES view's metrics — the series
  // frame may be narrower than the treemap (e.g. only declares `mcap_usd`).
  // Sourcing the buttons from the treemap's `size_by` would offer metrics the
  // series dataset can't plot, 400ing /api/series. The treemap `size_by` stays a
  // separate ranking input (timeseries.js sends it as `size_by` for branch
  // alignment), NOT a plottable metric. So: plotted `metric` ∈ series metrics.
  const metricIds = (sv.metrics && sv.metrics.length) ? sv.metrics : (tv ? tv.size_by : []);
  const metricCells = metricIds.map(id => [id, metricLabel(id)]);
  const winCells = sv.windows.map(w => [w.id, w.id]);
  const resCells = sv.resolutions.map(r => [r, r.toUpperCase()]);
  const aggCells = sv.aggs.map(a => [a, a]);

  root.innerHTML =
    (tv ? label("Bucket by") + segHTML("axis", tv.axes.map(a => [a.id, a.label]), treemapAxis) : "") +
    label("Metric") + segHTML("line-metric", metricCells, lineMetric) +
    label("Aggregate") + segHTML("line-agg", aggCells, lineAgg) +
    label("Window") + segHTML("line-window", winCells, lineWindow) +
    label("Resolution") + segHTML("line-res", resCells, lineResolution) +
    (sv.log_scale ? label("Y scale") + segHTML("line-scale", [["linear", "linear"], ["log", "log"]], lineScale) : "") +
    (tv ? filtersHTML(tv.filters || []) : "");

  if (tv) wireSeg(root, "axis", v => {
    if (v === treemapAxis) return;
    treemapAxis = v; renderSidebar(); syncTreemapPickerUrl();
    document.dispatchEvent(new CustomEvent("treemap-axis-changed", { detail: v }));
  });
  const setMetric = (v) => {
    lineMetric = v; lineAgg = (metricsById()[v]?.default_agg) || "median";
    renderSidebar();
    document.dispatchEvent(new CustomEvent("line-metric-changed", { detail: v }));
  };
  wireSeg(root, "line-metric", setMetric);
  wireSeg(root, "line-agg", v => { if (v === lineAgg) return; lineAgg = v; renderSidebar(); document.dispatchEvent(new CustomEvent("line-agg-changed", { detail: v })); });
  wireSeg(root, "line-window", v => { if (v === lineWindow) return; lineWindow = v; renderSidebar(); document.dispatchEvent(new CustomEvent("line-window-changed", { detail: v })); });
  wireSeg(root, "line-res", v => { if (v === lineResolution) return; lineResolution = v; renderSidebar(); document.dispatchEvent(new CustomEvent("line-resolution-changed", { detail: v })); });
  wireSeg(root, "line-scale", v => { if (v === lineScale) return; lineScale = v; renderSidebar(); document.dispatchEvent(new CustomEvent("line-scale-changed", { detail: v })); });
  if (tv) wireFilters(root, tv.filters || []);
}

// ── scatter sidebar (x/y metric pickers) ─────────────────────────────
let scatterX, scatterY;
export const getScatterX = () => scatterX;
export const getScatterY = () => scatterY;
function renderScatterSidebar(root) {
  const sc = M.views.scatter;
  scatterX = scatterX || sc.default_x;
  scatterY = scatterY || sc.default_y;
  const opts = (cur) => sc.metrics.map(id => `<option value="${esc(id)}" ${id === cur ? "selected" : ""}>${esc(metricLabel(id))}</option>`).join("");
  root.innerHTML =
    label("X axis") + `<select id="sc-x">${opts(scatterX)}</select>` +
    label("Y axis") + `<select id="sc-y">${opts(scatterY)}</select>`;
  root.querySelector("#sc-x").addEventListener("change", e => { scatterX = e.target.value; document.dispatchEvent(new CustomEvent("scatter-changed")); });
  root.querySelector("#sc-y").addEventListener("change", e => { scatterY = e.target.value; document.dispatchEvent(new CustomEvent("scatter-changed")); });
}

// ── detail sidebar ───────────────────────────────────────────────────
function renderEntitySidebar(root) {
  const dv = M.views.detail;
  if (!dv) { root.innerHTML = ""; return; }
  const winCells = dv.windows.map(w => [w.id, w.id]);
  const resCells = dv.resolutions.map(r => [r, r.toUpperCase()]);
  const metricOpts = (dv.series_metrics || []).map(id => `<option value="${esc(id)}" ${id === entityMetric ? "selected" : ""}>${esc(metricLabel(id))}</option>`).join("");
  const styleCells = (dv.chart_styles || ["line", "area"]).map(s => [s, s]);

  root.innerHTML =
    label("Window") + segHTML("ent-window", winCells, entityWindow) +
    label("Resolution") + segHTML("ent-res", resCells, entityResolution) +
    label("Metric") + `<select id="ent-metric">${metricOpts}</select>` +
    label("Graph") + segHTML("ent-style", styleCells, entityStyle) +
    label("Y scale") + segHTML("ent-scale", [["linear", "linear"], ["log", "log"]], entityScale) +
    label("Metadata") + segHTML("ent-meta", [["show", "show"], ["hide", "hide"]], entityShowMeta ? "show" : "hide");

  wireSeg(root, "ent-window", v => { if (v === entityWindow) return; entityWindow = v; renderSidebar(); document.dispatchEvent(new CustomEvent("entity-window-changed", { detail: v })); });
  wireSeg(root, "ent-res", v => { if (v === entityResolution) return; entityResolution = v; renderSidebar(); document.dispatchEvent(new CustomEvent("entity-resolution-changed", { detail: v })); });
  const me = root.querySelector("#ent-metric");
  if (me) me.addEventListener("change", () => { entityMetric = me.value; document.dispatchEvent(new CustomEvent("entity-metric-changed", { detail: entityMetric })); });
  wireSeg(root, "ent-style", v => { if (v === entityStyle) return; entityStyle = v; renderSidebar(); document.dispatchEvent(new CustomEvent("entity-style-changed", { detail: v })); });
  wireSeg(root, "ent-scale", v => { if (v === entityScale) return; entityScale = v; renderSidebar(); document.dispatchEvent(new CustomEvent("entity-scale-changed", { detail: v })); });
  wireSeg(root, "ent-meta", v => { const show = v === "show"; if (show === entityShowMeta) return; entityShowMeta = show; renderSidebar(); document.dispatchEvent(new CustomEvent("entity-meta-toggled", { detail: show })); });
}