facett-core 0.3.1

facett — visual kernel: render a node/edge Scene into egui (wgpu fast path to come)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
//! **facett-core** — the visual kernel. Render a node/edge **`Scene`** into egui.
//! Source-agnostic: build a `Scene` from anything (Arrow rows, a graph, a DAG),
//! hand it here, get pixels. The CPU painter is the reference; a **wgpu** fast
//! path (GPU viewport-cull + indirect draw, seeded from katana-osm's
//! `osm-viewer`) lands behind this same `draw()` call — consumers don't change.

use egui::{Align2, Color32, FontId, Pos2, Rect, Sense, Stroke, Ui, vec2};

pub mod a11y;
/// The bounded WebGPU adapter retry + the plain "no GPU" messages, shared by every
/// wasm entry point (facet-wrapped mounts, facett-demo's pages bundle).
pub mod adapter_retry;
/// Embedded-asset integrity: the `const fn` every `include_bytes!` site in this
/// workspace checks itself with, so a Git-LFS pointer standing in for a font fails the
/// BUILD instead of shipping as a font that draws nothing.
pub mod asset;
pub mod interface;
pub mod layered;
/// **Barnes–Hut N-body repulsion** — the shared O(n log n) force-layout kernel
/// (dimension-generic quadtree/octree, gatling-parallel) that every facett
/// force-directed layout consumes so a 30 000-node graph lays out without the
/// O(n²)-per-iteration hang. See [`barnes_hut`].
pub mod barnes_hut;
/// The shared **action bus** (BUS-1) — a typed, deterministic outbox facets use
/// to hand side work (a drag move, a time-scrub, a command) to the host. The
/// common carrier [`dragdrop`] / [`time_axis`] `Effect`s flow through.
pub mod action_bus;
pub mod caps;
pub mod chrome;
pub mod clip;
pub mod clipboard;
pub mod deckfx;
/// The shared **drag-and-drop** primitive (DND-1) — the one reducer behind
/// items-dragged-onto-zones (cards→columns, bars→lanes). Engine-agnostic sibling
/// of [`nav::Navigable`]; the caps flag [`FacetCaps::draggable`] points here.
pub mod dragdrop;
pub mod edges;
pub mod effects;
/// **THE unified view core** (ENGINE-1) — the one *cull · project · label-collide ·
/// pick* spine that `facett-map`, `facett-map3d`, `facett-geomap`, the L1 overlay
/// and every graph view collapse onto. Only THREE things differ between a map and
/// a graph, and they are the three traits
/// ([`PositionSource`](engine::PositionSource),
/// [`ElevationSource`](engine::ElevationSource), [`Hierarchy`](engine::Hierarchy)).
/// See [`engine`].
pub mod engine;
/// The **UI error-code scheme** (`facet-<component>-<n>`) — the stable, unique code
/// every facett UI part carries so tests + consumers react to the CODE, not a matched
/// string. See [`errcode::FacetError`], the [`facet_err!`] macro, the canonical
/// [`errcode::REGISTRY`], and the pink [`errcode::code_color`] renderer.
pub mod devid;
/// **The NAMED empty state** — what a pane draws when its feed has nothing in it:
/// the feed's own name, why it is empty (`no-rows` / `unreachable` / `not-configured`),
/// and optionally what would fill it. The alternative a 2026-09-10 audit found in the
/// wild was a *fixture* — plausible hand-written rows behind a `source: "fixture"`
/// tag — and rows read as data no matter what the tag says. See [`empty::EmptyState`].
pub mod empty;
pub mod errcode;
/// The canonical **Elm contract** (FC-2 / FC-9) — the [`Elm`] trait +
/// [`impl_facet_via_elm!`] bridge macro that lift `facett-security`'s hand-rolled
/// Model/Msg/Effect/pure-view pattern into reusable infra. Pair with
/// [`harness`] to drive an `Elm` component headlessly.
pub mod elm;
pub mod fly;
pub mod focus;
pub mod graph_split;
/// **The golden-image guard** (feature `golden`) — [`golden::assert_golden`], the
/// one comparison every facett screenshot proof runs against its committed PNG.
/// Exact match, failure artifacts under `target/`, a **missing golden FAILS**, and
/// blessing is the explicit opt-in `UPDATE_SNAPSHOTS=1`. Enabled from the
/// `[dev-dependencies]` of the crates that own goldens; absent from release builds.
#[cfg(feature = "golden")]
pub mod golden;
pub mod imgscan; // image-analysis oracle (SCAN-THE-PIXELS law): spoke/high-freq/
                 // coverage/centroid features computed FROM the rendered pixels.
pub mod labels3d;
/// **ROOT LAW #0 — the rayon-free law**, as machinery a test can actually fail
/// on ([`law`]). ONE writer for korp and facett so the two repos hold the same
/// line: our calls and our manifests are always red, a *normal* dependency edge
/// to rayon is red, and the known dev-only third-party edge (image→ravif inside
/// the screenshot-diff harness) is reported as context and never fails.
pub mod law;
/// **The label-declutter contract** — the order-independent spatial-grid collision
/// rule shared by the CPU painter and the WGSL compute passes (GFX_V2 item 4). One
/// writer, two executions; see the module docs for why [`legibility::place_labels`]
/// (greedy, order-dependent, displaces into alternative slots) could not be the one.
pub mod label_grid;
/// **Legibility at scale** — the shared screen-space toolbox (spatial hover index,
/// label collision avoidance, density-aware edge thinning) that makes a 100 000-node
/// graph or a 1 000 000-pin map readable. Pure, deterministic, headless-testable; the
/// legibility half of the story whose speed half is [`render::gpu::graphcloud`].
pub mod legibility;
pub mod harness;
pub mod look;
pub mod nav;
pub mod navgraph; // dev-mode numbered navigation graph + overlay (navgraph-design.md phase 1)
pub mod overlay;
/// The constellation-wide **`Panel` trait** (Phase 0 foundation) — the primary
/// UI-pane seam, with backend (1) native in-process (the blanket
/// `impl<T: Facet> Panel for T`) and backend (4) headless ([`panel::drive`]).
/// See `.nornir/wasm-ui-panels-design.md` §1.
pub mod panel;
pub mod rabbit;
/// The L0 shared render kernel (CONS-CORE) — shared `Camera`, z-ordered
/// `LayerStack`, the CPU rect scissor, and (feature `wgpu`) the extracted GPU
/// scaffold. Map skins + `facett-graphview` draw through this.
pub mod render;
pub mod runtrace; // in-memory, wasm-safe "what RAN" ledger (no FS) — folded into
                  // state_json["trace"]["ran"], read via the JS hook on wasm.
pub mod scroll_engine;
pub mod severity; // STRUCTURAL error signal for the Robot-UI HARD GATE — each
                  // pane/atom reports Severity{Info,Warning,Error}; the gate asserts
                  // on this instead of scanning rendered text (RESOLVED decision (a)).
pub mod testmatrix; // functional-status → nornir test-matrix bridge (feature
                    // `testmatrix`); no-op in release.
pub mod theme;
/// The shared **pan/zoom-in-time axis** (TIME-1) — the one time-window model
/// behind gantt/CFD/calendar/timeline, linkable across facets. Temporal sibling
/// of [`nav::Navigable`]; the caps flag [`FacetCaps::time_scrollable`] points here.
pub mod time_axis;
pub mod trace; // structured IN/OUT/END event stream ($FACETT_TRACE) — the
               // machine-readable data a facet actually rendered.
pub use a11y::{Semantics, node as a11y_node, stable_id};
pub use errcode::{FacetError, MountedFacetError};
pub use action_bus::{ActionBus, BusAction, BusMsg};
pub use caps::FacetCaps;
pub use dragdrop::{DragDrop, DragEffect, DragMsg, Move as DragMove};
pub use clip::{ArrowColumnRef, ClipKind, ClipPayload, CopySource, PasteTarget};
pub use clipboard::ClipAction;
pub use deckfx::{DeckFx, DeckRaven};
pub use elm::Elm;
pub use imgscan::{BBox, Rgba, ScanReport, coverage, high_freq_ratio, painted_centroid_and_bbox, scan, spoke_score};
pub use look::{Action, KeyMap, Palette};
pub use nav::{Dir4, Navigable, nearest_in_direction};
pub use panel::Panel;
pub use rabbit::{Rabbit, RabbitMesh, rabbit_mesh, rabbit_outline};
pub use scroll_engine::SmoothScroll;
pub use severity::{Severity, worst as worst_severity};
pub use theme::{Theme, set_theme, theme};
pub use time_axis::{TimeAxis, TimeEffect, TimeMsg};

// The rich look-&-feel `Theme` (the work-order architecture) is re-exported under
// an unambiguous alias so it coexists with the legacy flat palette `Theme` above.
pub use look::Theme as LookTheme;

/// A node: a label + a colour (the *consumer* picks the colour policy — hash by
/// label, by status, …).
#[derive(Clone)]
pub struct Node {
    pub label: String,
    pub color: Color32,
}

/// A directed edge between node indices.
#[derive(Clone, Copy)]
pub struct Edge {
    pub src: usize,
    pub dst: usize,
}

/// A drawable graph: nodes + edges (edges index into `nodes`).
#[derive(Default, Clone)]
pub struct Scene {
    pub nodes: Vec<Node>,
    pub edges: Vec<Edge>,
}

impl Scene {
    pub fn new() -> Self {
        Self::default()
    }
    /// Push a node, returning its index.
    pub fn node(&mut self, label: impl Into<String>, color: Color32) -> usize {
        self.nodes.push(Node { label: label.into(), color });
        self.nodes.len() - 1
    }
    pub fn edge(&mut self, src: usize, dst: usize) {
        self.edges.push(Edge { src, dst });
    }
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }
}

/// Node placement strategy.
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub enum Layout {
    #[default]
    Circular,
    /// Deterministic Fruchterman–Reingold (edges pull, all nodes repel). O(n²)
    /// per iteration — best for small/medium graphs.
    Force,
}

/// Draw a `Scene` into `ui` — the reusable render primitive. Empty scenes show
/// `empty_hint`. Labels render when the node count is small enough to read.
pub fn draw(ui: &mut Ui, scene: &Scene, layout: Layout, empty_hint: &str) {
    let (rect, _) = ui.allocate_exact_size(ui.available_size(), Sense::hover());
    let n = scene.nodes.len();
    if n == 0 {
        let th = theme(ui);
        ui.painter_at(rect).text(rect.center(), Align2::CENTER_CENTER, empty_hint, FontId::proportional(13.0), th.text_dim);
        return;
    }
    let pos = positions(layout, scene, rect);
    draw_positions(ui, scene, &pos, rect, empty_hint);
}

/// Paint a `Scene` into `rect` using **pre-computed** node positions — the drawing
/// half of [`draw`], split out so a stateful host can **freeze** the layout: compute
/// the O(n log n) force positions once (cached until the graph structure changes, see
/// [`ForceCache`]) and paint them every frame WITHOUT re-running the layout. `pos`
/// must be indexed like `scene.nodes`; short/empty falls back to the empty hint.
pub fn draw_positions(ui: &mut Ui, scene: &Scene, pos: &[Pos2], rect: Rect, empty_hint: &str) {
    let th = theme(ui);
    let painter = ui.painter_at(rect);
    let n = scene.nodes.len();
    if n == 0 || pos.len() != n {
        painter.text(rect.center(), Align2::CENTER_CENTER, empty_hint, FontId::proportional(13.0), th.text_dim);
        return;
    }
    for e in &scene.edges {
        if e.src < n && e.dst < n {
            painter.line_segment([pos[e.src], pos[e.dst]], Stroke::new(0.6_f32, th.edge));
        }
    }
    for (i, node) in scene.nodes.iter().enumerate() {
        painter.circle_filled(pos[i], 5.0, node.color);
    }
    draw_position_labels(ui, scene, pos, rect);
}

/// The label half of [`draw_positions`] alone: a host whose node/edge cloud went to the
/// GPU (`graphcloud::cloud::draw_cloud`) still paints the text through egui, with the
/// same font, offset and `n <= 60` cut as the CPU painter.
pub fn draw_position_labels(ui: &Ui, scene: &Scene, pos: &[Pos2], rect: Rect) {
    let th = theme(ui);
    let painter = ui.painter_at(rect);
    let n = scene.nodes.len();
    if n <= 60 && pos.len() == n {
        for (i, node) in scene.nodes.iter().enumerate() {
            painter.text(pos[i] + vec2(7.0, 0.0), Align2::LEFT_CENTER, &node.label, FontId::proportional(10.0), th.text);
        }
    }
}

/// **Converge-once-then-freeze** layout cache. A force layout is a pure function of
/// the graph structure (node count + edge set) and the paint `rect`, so this holds the
/// last-computed positions and only re-runs [`layout_positions`] when the structure or
/// rect actually changes. Embed it on a stateful host (e.g. a `GraphView`) and call
/// [`ForceCache::positions`] from the render path — the O(n log n) (with Barnes–Hut)
/// or O(n²) (small graphs) layout stops running every frame, which is the other half
/// (besides Barnes–Hut) of killing the 30 000-node hang.
#[derive(Default, Clone)]
pub struct ForceCache {
    sig: u64,
    rect: [u32; 4],
    pos: Vec<Pos2>,
}

impl ForceCache {
    /// The node positions for `scene` under `layout` in `rect`, computed on the first
    /// call and on any structural/rect change, and returned from cache otherwise.
    pub fn positions(&mut self, layout: Layout, scene: &Scene, rect: Rect) -> &[Pos2] {
        let n = scene.nodes.len();
        let key = self.structure_key(layout, scene);
        let rb = [rect.min.x.to_bits(), rect.min.y.to_bits(), rect.max.x.to_bits(), rect.max.y.to_bits()];
        if self.sig != key || self.rect != rb || self.pos.len() != n {
            self.pos = positions(layout, scene, rect);
            self.sig = key;
            self.rect = rb;
        }
        &self.pos
    }

    /// Whether the next [`positions`](Self::positions) call for this `layout`/`scene`
    /// in this `rect` will be a cache hit (a no-op relayout) — the *frozen/settled*
    /// signal a `tick` can assert.
    #[must_use]
    pub fn is_settled(&self, layout: Layout, scene: &Scene, rect: Rect) -> bool {
        let rb = [rect.min.x.to_bits(), rect.min.y.to_bits(), rect.max.x.to_bits(), rect.max.y.to_bits()];
        self.sig == self.structure_key(layout, scene) && self.rect == rb && self.pos.len() == scene.nodes.len()
    }

    /// Force a recompute on the next [`positions`](Self::positions) call.
    pub fn invalidate(&mut self) {
        self.sig = 0;
        self.rect = [0; 4];
        self.pos.clear();
    }

    fn structure_key(&self, layout: Layout, scene: &Scene) -> u64 {
        let edges: Vec<(usize, usize)> = scene.edges.iter().map(|e| (e.src, e.dst)).collect();
        let key = match layout {
            Layout::Circular => "circular",
            Layout::Force => "force",
        };
        crate::barnes_hut::structure_sig(key, scene.nodes.len(), &edges)
    }
}

/// **Test/host hook (additive).** The public, return-asserted view of the
/// private [`positions`] layout node — the exact node centres [`draw`] paints for
/// `scene` under `layout` inside `rect`. Exposed so the graph-skin call-chain
/// matrix can assert the *layout* stage (finite, in-rect, count == nodes,
/// circular radius, force-fit normalisation) without a painter. Calls the **same**
/// private fn `draw` uses, so it IS the layout the pixels come from — additive,
/// no behaviour change.
pub fn layout_positions(layout: Layout, scene: &Scene, rect: Rect) -> Vec<Pos2> {
    positions(layout, scene, rect)
}

fn positions(layout: Layout, scene: &Scene, rect: Rect) -> Vec<Pos2> {
    let n = scene.nodes.len();
    let center = rect.center();
    let radius = rect.size().min_elem() * 0.42;
    let circular = |i: usize| {
        let a = std::f32::consts::TAU * (i as f32) / (n as f32);
        vec2(a.cos(), a.sin())
    };
    match layout {
        Layout::Circular => (0..n).map(|i| center + radius * circular(i)).collect(),
        Layout::Force => {
            // Deterministic Fruchterman–Reingold from a circular seed (unit space).
            let mut p: Vec<egui::Vec2> = (0..n).map(circular).collect();
            let k = (1.0 / (n.max(1) as f32).sqrt()).clamp(0.05, 1.0);
            // Above the threshold the O(n²) all-pairs repulsion is the 30 000-node
            // hang — swap it for the shared Barnes–Hut O(n log n) kernel (parallel,
            // deterministic). Below the threshold the exact loop runs unchanged, so
            // every small-graph golden is byte-for-byte identical (additive).
            let use_bh = n >= crate::barnes_hut::BH_THRESHOLD;
            for _ in 0..120 {
                let mut disp = vec![egui::Vec2::ZERO; n];
                if use_bh {
                    let pts: Vec<[f32; 2]> = p.iter().map(|v| [v.x, v.y]).collect();
                    let rep = crate::barnes_hut::repulsion_forces::<2>(&pts, k, crate::barnes_hut::BH_THETA);
                    for i in 0..n {
                        disp[i] = egui::vec2(rep[i][0], rep[i][1]);
                    }
                } else {
                    for i in 0..n {
                        for j in (i + 1)..n {
                            let d = p[i] - p[j];
                            let dist = d.length().max(1e-3);
                            let f = k * k / dist;
                            let dir = d / dist;
                            disp[i] += dir * f;
                            disp[j] -= dir * f;
                        }
                    }
                }
                for e in &scene.edges {
                    if e.src < n && e.dst < n {
                        let d = p[e.src] - p[e.dst];
                        let dist = d.length().max(1e-3);
                        let f = dist * dist / k;
                        let dir = d / dist;
                        disp[e.src] -= dir * f;
                        disp[e.dst] += dir * f;
                    }
                }
                for i in 0..n {
                    let dl = disp[i].length().max(1e-3);
                    p[i] += disp[i] / dl * dl.min(0.04); // capped step (cooling-free, deterministic)
                }
            }
            // Normalise to fit the rect.
            let (mut mn, mut mx) = (egui::vec2(f32::MAX, f32::MAX), egui::vec2(f32::MIN, f32::MIN));
            for v in &p {
                mn.x = mn.x.min(v.x);
                mn.y = mn.y.min(v.y);
                mx.x = mx.x.max(v.x);
                mx.y = mx.y.max(v.y);
            }
            let span = (mx - mn).max(egui::vec2(1e-3, 1e-3));
            p.iter()
                .map(|v| center + egui::vec2(((v.x - mn.x) / span.x - 0.5) * 2.0 * radius, ((v.y - mn.y) / span.y - 0.5) * 2.0 * radius))
                .collect()
        }
    }
}

/// The facett **component contract**. Every facet — graph, map, pipeline, table,
/// the ported nornir viewers — implements this, so consumers (korp, nornir, …)
/// compose them uniformly *and* get headless robot-testing for free.
///
/// The things a component owes its host:
/// 1. a **title** (tab label / panel heading),
/// 2. how to **draw** itself into egui,
/// 3. its **observable state** as JSON — dumped to `$APP_STATE` for headless
///    assertions. **Rule:** every visible list/status/count goes in `state_json`.
/// 4. (**defaulted**) [`update_json`](Facet::update_json) — the Elm mutation path,
///    a no-op by default so it costs existing facets nothing; overriding it (and
///    the three above) makes a facet interchangeable with a [`Panel`](crate::Panel).
pub trait Facet {
    fn title(&self) -> &str;
    fn ui(&mut self, ui: &mut Ui);
    fn state_json(&self) -> serde_json::Value;

    /// The **Elm mutation path** — apply one message (JSON). This is the fourth
    /// member of the component contract (`title`/`ui`/`state_json`/`update_json`),
    /// and it is **defaulted to a no-op** so it is purely ADDITIVE: every existing
    /// `impl Facet` keeps compiling unchanged, while a facet that wants the writable
    /// input surface overrides it (an Elm-backed facet routes the JSON through its
    /// `update`). With this default in place `Facet` and [`Panel`](crate::Panel)
    /// share the same four-method shape, which is what lets the blanket
    /// `impl<T: Facet> Panel for T` (see [`panel`](crate::panel)) make **every**
    /// `Facet` a `Panel` for free. Unknown/undriven messages are ignored — the
    /// default simply does nothing.
    fn update_json(&mut self, _msg_json: &str) {}

    /// The pane's **STRUCTURAL severity** — the RESOLVED Robot-UI error signal
    /// (decision (a)). A facet returns the WORST [`Severity`](crate::Severity) over
    /// its currently-rendered atoms (compute it with
    /// [`worst_severity`](crate::worst_severity)): [`Severity::Info`] when it is
    /// showing real data, [`Severity::Warning`] when degraded, and
    /// [`Severity::Error`] when it surfaced a failure (a load error, an unavailable
    /// backend, an empty data-bearing surface).
    ///
    /// **Defaulted to [`Severity::Info`]** so it is purely ADDITIVE — every existing
    /// `impl Facet` stays green and keeps compiling. The Robot-UI HARD GATE reads
    /// THIS (surfaced through the [`Panel`](crate::Panel) seam the headless robot
    /// drives), not the `nornir_robotui::error_atoms()` substring scan, which is kept
    /// only as a MIGRATION FALLBACK for panes that have not yet overridden this.
    /// A pane that returns [`Severity::Error`] is RED and FAILS the gate.
    /// **This pane's stable DEV-ID** — the [`errcode`](crate::errcode) *component*
    /// string (the `<component>` in `facet-<component>-<n>`), so the identity a pane
    /// shows and the identity its errors carry are the SAME vocabulary rather than two
    /// naming schemes that drift.
    ///
    /// Shown as a click-to-copy chip in non-release builds ([`devid::badge`](crate::devid::badge)),
    /// because a screenshot cannot tell you which crate drew a pane and a title like
    /// "Map" appears in four of them. Pasting the chip resolves to a crate dir and a
    /// source file via [`devid::resolve`](crate::devid::resolve).
    ///
    /// **Defaulted to `""`** so it is purely ADDITIVE — every existing `impl Facet`
    /// keeps compiling. A pane that has not overridden it renders a visibly-different
    /// `⟨unregistered⟩` marker instead of an id, never a plausible-looking string that
    /// resolves to nothing (the `facet-map-99` hole that
    /// `facett-core/tests/errcode_raise_sites.rs` documents). So the badge is also the
    /// to-do list: every marker is a pane still to declare this.
    fn component(&self) -> &'static str {
        ""
    }

    fn severity(&self) -> crate::Severity {
        crate::Severity::Info
    }

    // --- uniform capability surface (all defaulted; see caps.rs / clipboard.rs) ---

    /// What this facet can do. Override to opt into capabilities.
    fn caps(&self) -> FacetCaps {
        FacetCaps::NONE
    }

    /// Current uniform scale (1.0 = native). Override if `caps().scalable`.
    fn scale(&self) -> f32 {
        1.0
    }
    /// Set the uniform scale; clamp internally. Default no-op (not scalable).
    fn set_scale(&mut self, _scale: f32) {}

    /// **The band `[min, max]`, relative to native (`1.0`), that this facet's uniform
    /// scale may be driven over.** [`FacetDeck::scale_active`] clamps into it.
    ///
    /// The default `[0.25, 4.0]` is a *document viewer's* range — a quarter size to
    /// quadruple size, which is all a table, a form or a text pane ever wants. It was
    /// for years the deck's only vocabulary, hardcoded in `scale_active`, and that is
    /// a bug for any facet whose native range is wider. A MAP's is: `OsmView`'s camera
    /// spans `[ZOOM_MIN, ZOOM_MAX]` = a 1.25-million-fold range, so a hardcoded 16-fold
    /// clamp both **stalls** zoom-in a couple of clicks past the fit *and* — because
    /// the wheel and pinch drive the camera directly, never through [`Self::set_scale`]
    /// — makes the next `+` click **saturate the clamp and slam the camera backwards**,
    /// a zoom-IN button that visibly zooms OUT. Guarded by
    /// `facett-geomap/tests/osm2d_deck_scale.rs`.
    ///
    /// Override alongside [`Self::scale`]/[`Self::set_scale`] when native has no fixed
    /// pixel size. Must contain `1.0` — [`FacetDeck::reset_scale`] writes it.
    fn scale_range(&self) -> (f32, f32) {
        (0.25, 4.0)
    }

    /// The current selection as JSON (also folded into `state_json` by
    /// convention). `Null` when nothing/none selectable.
    fn selection_json(&self) -> serde_json::Value {
        serde_json::Value::Null
    }

    /// Clipboard hooks — see clipboard.rs. Defaults: nothing to give/take.
    /// Returns the text to place on the clipboard (None = nothing copyable now).
    fn copy(&mut self) -> Option<String> {
        None
    }
    /// Like `copy`, but also removes the selection. Default delegates to `copy`.
    fn cut(&mut self) -> Option<String> {
        self.copy()
    }
    /// Accept pasted text. Returns true if consumed.
    fn paste(&mut self, _text: &str) -> bool {
        false
    }

    /// Optional downcast handle for hosts that need typed access to a specific
    /// facet living inside a [`FacetDeck`] (e.g. a robot-UI driver clicking an
    /// app-level control that must forward to a concrete component's own API).
    /// Defaulted to `None` so no existing facet has to change; a component opts in
    /// by returning `Some(self)`.
    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
        None
    }

    // --- cross-instance state clone (copy/paste BETWEEN same-component instances) ---
    // See `.nornir/design/copy-paste-between-instances.md` + `clipboard.rs`. The trio
    // below is the type-tagged STATE layer on top of the text clipboard: two
    // instances with the SAME `kind()` exchange `portable_state()` via the OS
    // clipboard envelope (`clipboard::encode_component`/`decode_component`). Each is
    // defaulted to the opt-OUT floor — a component that doesn't implement all three
    // neither copies nor accepts cross-instance state, and nothing panics.

    /// Stable component-type id (e.g. `"jobview"`, `"graphpan"`, `"table"`). Two
    /// instances with the **same** kind can exchange portable state; the empty
    /// default `""` means **opted out** of cross-instance clone.
    fn kind(&self) -> &'static str {
        ""
    }

    /// The **portable** subset of this facet's state — the fields a same-kind
    /// sibling can adopt. `None` = not cloneable. Kept SEPARATE from
    /// [`state_json`](Self::state_json) (the introspection dump, which may carry
    /// derived / render-only data) so this stays round-trippable through
    /// [`load_state`](Self::load_state).
    fn portable_state(&self) -> Option<serde_json::Value> {
        None
    }

    /// Adopt a portable state produced by [`portable_state`](Self::portable_state)
    /// on a same-kind sibling. Returns `true` if accepted. Default `false`
    /// (opt-in per component).
    fn load_state(&mut self, _state: &serde_json::Value) -> bool {
        false
    }
}

/// The per-facet states [`FacetDeck::state_json_rolling`] serves inactive tabs from.
/// One per publishing host; `Default` = empty (the first call builds everything).
///
/// The map is MOVED into the returned state, not cloned (a clone of 80 tabs' JSON trees
/// cost as much as building them), so the host hands it back with
/// [`FacetDeck::return_rolling`] after serialising — or the next call rebuilds every tab
/// (correct, only slow).
#[derive(Default, Debug)]
pub struct DeckStateCache {
    facets: serde_json::Map<String, serde_json::Value>,
    /// Each facet's state as JSON text ([`FacetDeck::serialize_rolling`]); dropped when
    /// that facet's state is rebuilt, so it is re-serialised exactly then.
    text: std::collections::HashMap<String, String>,
    next: usize,
    /// Facet `state_json` builds made through this cache (the honesty counter).
    pub built: u64,
}

/// A tabbed set of [`Facet`]s — the reusable multi-component shell. Draws a tab
/// bar + the active facet, and composes **every** facet's `state_json` under its
/// title, so the whole-app introspection contract is free. korp/nornir can build
/// their window from a `FacetDeck` instead of hand-rolling tabs + the state dump.
pub struct FacetDeck {
    facets: Vec<Box<dyn Facet>>,
    active: usize,
    /// Opt-in deck effects (palette override + glow). `Default` = all off, so a
    /// deck that never opts in is unchanged and pays nothing.
    fx: DeckFx,
    /// A raven summoned through the deck, in flight or perched (or `None`).
    raven: Option<DeckRaven>,
    /// A transient, themed component-clone toast (message + the `ctx.input.time`
    /// it was raised at), shown briefly after a Copy-/Paste-component gesture —
    /// chiefly the type-mismatch rejection ("clipboard holds a `table`, not a
    /// `graphpan`"). `None` = nothing to show. See [`Self::component_toast`].
    toast: Option<(String, f64)>,
    /// **Responsive MENU collapse.** Host-driven: on a narrow (phone-class) viewport
    /// the long tab bar (one selectable per facet — a deck can hold 60+) wraps into
    /// many rows and buries the active facet below the screen fold. When
    /// `menu_collapsed` is set (by the host, classifying the viewport — e.g.
    /// `facett_app::scene::Device`) the tab bar renders as a compact HAMBURGER header
    /// (`≡` + the active choice's label) with the full choice list behind a drawer
    /// (canvas-first). On a wide viewport it stays the inline wrapped strip. See
    /// [`set_menu_collapsed`](Self::set_menu_collapsed).
    menu_collapsed: bool,
    /// The hamburger drawer's open state (deck-owned). Default **closed** ⇒ the
    /// collapsed header is a single row and the canvas gets the screen; opening lists
    /// every choice, and picking one switches the tab AND shuts the drawer.
    menu_open: bool,
    /// Last frame's tab-bar (menu header) rect — the observable geometry a headless
    /// test reads (`state_json.menu.bar_rect`) to prove the collapsed menu is ONE
    /// compact row, not a multi-row wrap that eats the viewport.
    menu_bar_rect: Rect,
    /// Last frame's active-facet content rect — the "canvas" the collapse hands the
    /// screen to (`state_json.menu.content_rect`).
    content_rect: Rect,
    /// **Tab groups** (opt-in, [`with_groups`](Self::with_groups)). Empty = the one flat
    /// strip, exactly as before. Set = a TWO-LEVEL bar: a row of group names, then the
    /// active group's tabs. Every facet sits in exactly one group (unlisted ones land in
    /// a trailing group), and the active group is DERIVED from the active facet, so a
    /// programmatic switch ([`set_active_by_title`](Self::set_active_by_title), a deep
    /// link, a tour) can never show a tab row that does not hold the active tab.
    groups: Vec<TabGroup>,
}

/// One named group of deck tabs: its label and its members as facet indices, in deck
/// order. Built by [`FacetDeck::with_groups`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TabGroup {
    /// The group's label in the group row (also its navgraph field key).
    pub name: String,
    /// Facet indices, ascending (deck order).
    pub members: Vec<usize>,
    /// The member last shown, so re-entering a group returns to where the user was.
    last: usize,
}

impl TabGroup {
    /// The member index re-entering this group opens (the last one shown).
    pub fn entry(&self) -> usize {
        if self.members.contains(&self.last) { self.last } else { self.members.first().copied().unwrap_or(0) }
    }
}

/// How long a component-clone [`toast`](FacetDeck::toast) stays on screen.
const TOAST_SECS: f64 = 2.6;

impl FacetDeck {
    pub fn new(facets: Vec<Box<dyn Facet>>) -> Self {
        Self {
            facets,
            active: 0,
            fx: DeckFx::OFF,
            raven: None,
            toast: None,
            menu_collapsed: false,
            menu_open: false,
            menu_bar_rect: Rect::ZERO,
            content_rect: Rect::ZERO,
            groups: Vec::new(),
        }
    }

    /// **Group the tab bar** into named groups — `(name, tab titles)` in display order.
    ///
    /// Tab titles are matched exactly; a title the deck does not hold is skipped (a
    /// native-only tab named in a list a wasm build shares). A facet no group names is
    /// put in a trailing group called `rest` (created only when needed), so no tab can
    /// become unreachable by being forgotten. A facet named by two groups belongs to the
    /// first. Groups left empty are dropped. Inside a group the tabs keep DECK order, so
    /// the tab strip's navgraph draw order is the deck order filtered, as before.
    ///
    /// Must be called after the facets are in place (it indexes them); a later
    /// [`push`](Self::push) lands in the `rest` group on the next call only.
    #[must_use]
    pub fn with_groups(mut self, groups: &[(&str, &[&str])], rest: &str) -> Self {
        self.set_groups(groups, rest);
        self
    }

    /// The in-place form of [`with_groups`](Self::with_groups).
    pub fn set_groups(&mut self, groups: &[(&str, &[&str])], rest: &str) {
        let mut owner: Vec<Option<usize>> = vec![None; self.facets.len()];
        for (g, (_, titles)) in groups.iter().enumerate() {
            for t in titles.iter() {
                if let Some(i) = self.facets.iter().position(|f| f.title() == *t)
                    && owner[i].is_none()
                {
                    owner[i] = Some(g);
                }
            }
        }
        let mut out: Vec<TabGroup> = groups
            .iter()
            .enumerate()
            .map(|(g, (name, _))| TabGroup {
                name: (*name).to_string(),
                members: (0..self.facets.len()).filter(|&i| owner[i] == Some(g)).collect(),
                last: usize::MAX,
            })
            .collect();
        let orphans: Vec<usize> = (0..self.facets.len()).filter(|&i| owner[i].is_none()).collect();
        if !orphans.is_empty() {
            // A `rest` group the caller already declared takes the orphans too.
            match out.iter_mut().find(|g| g.name == rest) {
                Some(g) => {
                    g.members.extend(orphans);
                    g.members.sort_unstable();
                }
                None => out.push(TabGroup { name: rest.to_string(), members: orphans, last: usize::MAX }),
            }
        }
        out.retain(|g| !g.members.is_empty());
        self.groups = out;
    }

    /// The tab groups (empty when the bar is one flat strip).
    pub fn groups(&self) -> &[TabGroup] {
        &self.groups
    }

    /// The index of the group holding the active facet, or `None` when ungrouped.
    pub fn active_group(&self) -> Option<usize> {
        self.groups.iter().position(|g| g.members.contains(&self.active))
    }

    /// The name of the group holding the active facet.
    pub fn active_group_name(&self) -> Option<&str> {
        self.active_group().map(|g| self.groups[g].name.as_str())
    }

    /// Switch to group `name`: the active facet becomes the group's last-shown member
    /// (its first, the first time). Returns `false` for an unknown group. The
    /// programmatic twin of clicking the group's label.
    pub fn set_active_group(&mut self, name: &str) -> bool {
        match self.groups.iter().find(|g| g.name == name) {
            Some(g) => {
                self.active = g.entry();
                true
            }
            None => false,
        }
    }

    /// Remember the active facet as its group's last-shown member.
    fn note_group_entry(&mut self) {
        let active = self.active;
        if let Some(g) = self.groups.iter_mut().find(|g| g.members.contains(&active)) {
            g.last = active;
        }
    }

    /// The group row of a grouped bar: one selectable per group, a draw-order-declared
    /// navgraph `groups` strip (each label a `Field`). Clicking a group opens its entry.
    /// Returns `true` when a group was picked this frame.
    fn draw_group_row(&mut self, ui: &mut Ui) -> bool {
        let active_group = self.active_group();
        let mut pick: Option<usize> = None;
        let nav = navgraph::begin(ui, "groups", navgraph::NavKind::Group, "groups");
        navgraph::declare_draw_order(ui, nav);
        let row = ui.horizontal_wrapped(|ui| {
            for (gi, g) in self.groups.iter().enumerate() {
                let r = ui
                    .selectable_label(active_group == Some(gi), g.name.as_str())
                    .on_hover_text(format!("{} tabs", g.members.len()));
                navgraph::field(ui, &g.name, &r);
                if r.clicked() {
                    pick = Some(gi);
                }
            }
        });
        navgraph::end(ui, nav, row.response.rect);
        if let Some(gi) = pick {
            self.active = self.groups[gi].entry();
        }
        pick.is_some()
    }
    /// Append a facet (the incremental form of [`new`](Self::new)). Lets a host
    /// build a deck pane-by-pane as it discovers what to show (e.g. one pane per
    /// warehouse table it finds).
    pub fn push(&mut self, facet: Box<dyn Facet>) {
        self.facets.push(facet);
    }
    pub fn active(&self) -> usize {
        self.active
    }

    /// The title of the currently-active facet (the deck's `state_json["active"]`),
    /// or `None` if the deck is empty.
    pub fn active_title(&self) -> Option<&str> {
        self.facets.get(self.active).map(|f| f.title())
    }

    /// The titles of every tabbed facet, in tab order — the discoverable surface a
    /// host (or a robot-UI control channel) enumerates to know which tabs exist.
    pub fn titles(&self) -> Vec<&str> {
        self.facets.iter().map(|f| f.title()).collect()
    }

    /// Make the facet titled `title` the active tab — the programmatic (headless,
    /// robot-addressable) equivalent of clicking its tab header. Returns `true` if a
    /// facet with that title exists (and is now active), `false` otherwise. This is
    /// the named boundary a control channel switches tabs through (the deck analogue
    /// of the viz's `Tab::from_name`), so a driver needn't replay a pointer click.
    pub fn set_active_by_title(&mut self, title: &str) -> bool {
        match self.facets.iter().position(|f| f.title() == title) {
            Some(i) => {
                self.active = i;
                true
            }
            None => false,
        }
    }

    // ── responsive menu (hamburger) — the reusable narrow-viewport tab bar ───────

    /// Host-driven: render the tab bar as a compact **hamburger menu** (`≡` + the
    /// active choice's label, the full list behind a drawer) instead of the inline
    /// wrapped strip. The host classifies the viewport (e.g.
    /// `facett_app::scene::Device::from_width`) and calls this each frame; on a
    /// narrow (phone-class) width the long tab bar would otherwise wrap into many
    /// rows and bury the active facet below the screen fold. Setting it `false` (a
    /// wide viewport) restores the inline bar AND shuts the drawer. This is the deck
    /// analogue of the demo shell's `⚙` control-strip fold — the SAME canvas-first
    /// pattern applied to the MAIN menu, living once here so every deck host
    /// (korp/nornir/…) inherits it.
    pub fn set_menu_collapsed(&mut self, collapsed: bool) {
        if !collapsed {
            self.menu_open = false;
        }
        self.menu_collapsed = collapsed;
    }
    /// Whether the tab bar is currently rendered as the collapsed hamburger menu.
    pub fn menu_collapsed(&self) -> bool {
        self.menu_collapsed
    }
    /// Whether the hamburger drawer is open (the full choice list is showing).
    pub fn menu_open(&self) -> bool {
        self.menu_open
    }
    /// Open / shut the hamburger drawer explicitly (the programmatic equivalent of
    /// tapping `≡`). No visible effect while the menu is not collapsed.
    pub fn set_menu_open(&mut self, open: bool) {
        self.menu_open = open;
    }
    /// Toggle the hamburger drawer; returns the new open state.
    pub fn toggle_menu(&mut self) -> bool {
        self.menu_open = !self.menu_open;
        self.menu_open
    }

    /// Typed mutable access to the facet with `title`, downcast to `T` — `None` if
    /// no such facet, or it doesn't opt into [`Facet::as_any_mut`], or the type
    /// mismatches. Lets a host drive a concrete component's own API (e.g. a
    /// robot-UI control forwarding a node selection to a `SystemChart`).
    pub fn facet_mut<T: std::any::Any>(&mut self, title: &str) -> Option<&mut T> {
        self.facets
            .iter_mut()
            .find(|f| f.title() == title)
            .and_then(|f| f.as_any_mut())
            .and_then(|a| a.downcast_mut::<T>())
    }

    /// Forward one [`Facet::update_json`] message to the facet titled `title` — the
    /// untyped twin of [`facet_mut`](Self::facet_mut) for a host that holds a message,
    /// not a type (a deep link, a control channel). `false` when no such facet.
    pub fn update_json_for(&mut self, title: &str, msg_json: &str) -> bool {
        match self.facets.iter_mut().find(|f| f.title() == title) {
            Some(f) => {
                f.update_json(msg_json);
                true
            }
            None => false,
        }
    }

    /// Replace the facet whose `title` matches with `facet` (the box's own title is
    /// what the deck enumerates afterwards). Returns `true` if a facet was replaced.
    /// Used by hosts that **reload** a tab's data in place — e.g. the OSM region
    /// picker rebuilds the `OSM 2D` / `OSM 3D` views from a freshly clipped region
    /// and swaps them in, keeping the same tab slots (and the active selection).
    pub fn replace_facet(&mut self, title: &str, facet: Box<dyn Facet>) -> bool {
        if let Some(slot) = self.facets.iter_mut().find(|f| f.title() == title) {
            *slot = facet;
            true
        } else {
            false
        }
    }

    // ── opt-in effects + theming (see deckfx.rs) ─────────────────────────────

    /// Enable deck effects up front (builder form of [`fx_mut`](Self::fx_mut)).
    pub fn with_fx(mut self, fx: DeckFx) -> Self {
        self.fx = fx;
        self
    }
    /// The current deck-effects config (read-only).
    pub fn fx(&self) -> &DeckFx {
        &self.fx
    }
    /// Mutate the deck-effects config (toggle glow, pin a palette, …).
    pub fn fx_mut(&mut self) -> &mut DeckFx {
        &mut self.fx
    }
    /// Override the deck theme with palette index `i` (wraps); enables the
    /// override. Convenience over `fx_mut().set_palette(i)`.
    pub fn set_palette(&mut self, i: usize) {
        self.fx.set_palette(i);
    }
    /// Advance to the next palette in [`Theme::ALL`] (wrapping); returns the new
    /// index. Convenience over `fx_mut().cycle_palette()`.
    pub fn cycle_palette(&mut self) -> usize {
        self.fx.cycle_palette()
    }

    /// **Summon the raven** to perch on `target` — any rect a facet/host hands us
    /// (a table row, a node, a header). Replaces any raven already in flight. The
    /// body is tinted from the deck's current palette (or the host theme). Logs an
    /// activity trail entry. Drive/paint happens automatically inside
    /// [`ui`](Self::ui).
    pub fn send_raven(&mut self, target: Rect) {
        let theme = self.effective_theme();
        self.raven = Some(DeckRaven::new(target, &theme));
        harness::trail(
            harness::Kind::Render,
            format!("raven launched → perch ({:.0},{:.0})", target.center().x, target.top()),
        );
    }
    /// True while a raven is present (flying or perched).
    pub fn has_raven(&self) -> bool {
        self.raven.is_some()
    }
    /// True once the summoned raven has landed (false if none).
    pub fn raven_perched(&self) -> bool {
        self.raven.as_ref().map(|r| r.is_perched()).unwrap_or(false)
    }
    /// Dismiss any raven.
    pub fn clear_raven(&mut self) {
        self.raven = None;
    }

    /// The theme the deck paints with: the fx palette override if set, else
    /// [`Theme::default`] (the host's own `set_theme` still applies its visuals;
    /// this is just the colour source for deck-owned effects/picker).
    fn effective_theme(&self) -> Theme {
        self.fx.theme().unwrap_or_default()
    }

    /// Draw a one-line **palette picker** — a switcher over [`Theme::ALL`] the
    /// host can place anywhere (toolbar, menu). Selecting a palette pins the fx
    /// override; `ui()` then applies it each frame. Returns the chosen index if it
    /// changed this frame.
    ///
    /// The override stays **off until the user actually clicks** a palette: merely
    /// drawing the picker must not pin index 0, otherwise a host that drives its
    /// own theme (e.g. the rich [`crate::look::Theme`]) would be silently clobbered
    /// every frame by the legacy `set_theme` in [`ui`](Self::ui) — size still
    /// changing (spacing) but colour frozen on `Theme::ALL[0]`. So we only pin when
    /// the selection genuinely changed this frame.
    pub fn palette_picker(&mut self, ui: &mut Ui) -> Option<usize> {
        let mut sel = self.fx.palette().unwrap_or(0);
        let before = sel;
        ui.horizontal_wrapped(|ui| {
            ui.label("Palette:");
            for (i, ctor) in Theme::ALL.iter().enumerate() {
                ui.selectable_value(&mut sel, i, ctor().name);
            }
        });
        if sel != before {
            self.fx.set_palette(sel);
        }
        (sel != before).then_some(sel)
    }

    /// The capabilities of the currently-active facet (or `NONE` if empty).
    pub fn active_caps(&self) -> FacetCaps {
        self.facets.get(self.active).map(|f| f.caps()).unwrap_or(FacetCaps::NONE)
    }

    /// Number of facets in the deck.
    pub fn len(&self) -> usize {
        self.facets.len()
    }
    /// True when the deck holds no facets.
    pub fn is_empty(&self) -> bool {
        self.facets.is_empty()
    }

    /// **Wall layout** — render **every** facet at once in a wrapping grid of
    /// `cols` columns, instead of the tabbed one-at-a-time [`ui`](Self::ui). This is
    /// the "multiple components visible simultaneously" mode a dashboard host wants
    /// (e.g. several `Graph3D` panes side-by-side). Each cell is a titled group; the
    /// fx palette override (if set) still applies, and every rendered facet is logged
    /// to the runtrace ledger keyed `deck.wall:<title>` (mirrors the tab path's
    /// `deck.render:<title>`), so `state_json`'s `trace.ran` proves each pane drew.
    pub fn wall_ui(&mut self, ui: &mut Ui, cols: usize) {
        if let Some(theme) = self.fx.theme() {
            set_theme(ui.ctx(), theme);
        }
        if self.facets.is_empty() {
            ui.weak("empty deck");
            return;
        }
        let cols = cols.max(1);
        let spacing = ui.spacing().item_spacing.x;
        let total_w = ui.available_width();
        let cell_w = ((total_w - spacing * (cols as f32 - 1.0)) / cols as f32).max(160.0);
        // A generous cell so 3D graphs have room; the inner facet fills it.
        let cell_h = 300.0_f32;
        egui::ScrollArea::vertical()
            .auto_shrink([false; 2])
            .show(ui, |ui| {
                ui.horizontal_wrapped(|ui| {
                    for f in self.facets.iter_mut() {
                        ui.allocate_ui(egui::vec2(cell_w, cell_h), |ui| {
                            let cell = ui.group(|ui| {
                                ui.set_min_size(egui::vec2(cell_w - 12.0, cell_h - 12.0));
                                ui.vertical(|ui| {
                                    ui.strong(f.title());
                                    ui.separator();
                                    runtrace::ran(&format!("deck.wall:{}", f.title()));
                                    f.ui(ui);
                                });
                            });
                            // The wall shows every pane at once, which is exactly when
                            // "which crate drew THAT one?" is hardest to answer.
                            devid::badge(ui, cell.response.rect, f.component(), f.title());
                        });
                    }
                });
            });
    }

    /// **Render ONE facet into the caller's `Ui`** — the seam a scene host needs to
    /// make a deck out of REAL panes instead of emulating one.
    ///
    /// [`wall_ui`](Self::wall_ui) owns its own grid: it decides the columns, the cell
    /// size and the scrolling, and draws every facet inside one `Ui`. That is right for
    /// a self-contained dashboard and wrong for `facett_app::scene`, which already has
    /// a pane tree, allots each pane its own rect, and gives each one chrome and a
    /// published address. A host with a scene could only mount the WHOLE deck into ONE
    /// pane, so N panes' worth of content ended up sharing a single allotment — which
    /// is precisely the shape that lets one pane's growth displace another.
    ///
    /// This renders facet `idx` and nothing else, into whatever rect the caller has
    /// already decided. No grid, no scroll area, no title strip — the scene's chrome
    /// bar carries the title, and a second one would be a second header row.
    ///
    /// Returns `false` when `idx` is out of range, so a host whose pane tree has
    /// drifted from the deck's contents gets a value it can assert on rather than a
    /// silently blank pane.
    ///
    /// The runtrace key is `deck.pane:<title>`, alongside `deck.wall:` and
    /// `deck.render:`, so `state_json`'s `trace.ran` still proves the pane drew.
    pub fn pane_ui(&mut self, idx: usize, ui: &mut Ui) -> bool {
        if let Some(theme) = self.fx.theme() {
            set_theme(ui.ctx(), theme);
        }
        let Some(f) = self.facets.get_mut(idx) else {
            return false;
        };
        runtrace::ran(&format!("deck.pane:{}", f.title()));
        // The pane's own rect, captured BEFORE it draws: a pane that consumes the whole
        // `Ui` leaves the cursor somewhere unhelpful, so reading it afterwards would
        // anchor the chip to wherever the content happened to end.
        let rect = ui.max_rect();
        let (component, title) = (f.component(), f.title().to_string());
        let nav = navgraph::collecting(ui.ctx())
            .then(|| devid::badge_text(component, &title).0)
            .and_then(|key| navgraph::begin(ui, &key, navgraph::NavKind::Pane, &title));
        f.ui(ui);
        navgraph::end(ui, nav, rect);
        // The DEV-ID chip — one draw site, so EVERY deck pane gets it for free (LAW 5)
        // rather than 70-odd panes each remembering to paint their own. No-op in release.
        devid::badge(ui, rect, component, &title);
        true
    }

    /// Open the active facet's navgraph Pane (dev mode, collecting only — the key is a
    /// `format!`, so it is not built otherwise).
    fn nav_pane_begin(&self, ui: &Ui) -> Option<navgraph::Token> {
        if !navgraph::collecting(ui.ctx()) {
            return None;
        }
        let f = self.facets.get(self.active)?;
        let (key, _) = devid::badge_text(f.component(), f.title());
        navgraph::begin(ui, &key, navgraph::NavKind::Pane, f.title())
    }

    /// The title of facet `idx`, for a host naming its panes from the deck.
    pub fn pane_title(&self, idx: usize) -> Option<&str> {
        self.facets.get(idx).map(|f| f.title())
    }

    /// The active facet's current scale (1.0 if none / not scalable).
    fn active_scale(&self) -> f32 {
        self.facets.get(self.active).map(|f| f.scale()).unwrap_or(1.0)
    }

    /// Multiply the active facet's scale by `k`, clamped to **the facet's own**
    /// [`Facet::scale_range`] — not to a hardcoded document-viewer band. A facet whose
    /// native range is wider (a map: 1.25-million-fold) would otherwise saturate the
    /// clamp on the first click and have its camera written backwards.
    fn scale_active(&mut self, k: f32) {
        if let Some(f) = self.facets.get_mut(self.active) {
            let (lo, hi) = f.scale_range();
            let s = (f.scale() * k).clamp(lo, hi);
            f.set_scale(s);
        }
    }

    /// Reset the active facet's scale to native.
    fn reset_scale(&mut self) {
        if let Some(f) = self.facets.get_mut(self.active) {
            f.set_scale(1.0);
        }
    }

    /// Draw the tab bar + capability toolbar + the active facet, and route
    /// capability-gated shortcuts (Ctrl-+/-/0 for scale; Ctrl-C/X/V for clipboard).
    pub fn ui(&mut self, ui: &mut Ui) {
        // Opt-in palette override: apply the chosen Theme::ALL palette + its
        // egui Visuals each frame so the whole deck (and every facet that reads
        // `theme(ui)`) follows. No override → the host's own theme stays.
        if let Some(theme) = self.fx.theme() {
            set_theme(ui.ctx(), theme);
        }

        let titles: Vec<String> = self.facets.iter().map(|f| f.title().to_string()).collect();
        // The tab bar has TWO forms (responsive, host-driven via `set_menu_collapsed`):
        //   • WIDE viewport → the inline wrapped strip (every tab visible + clickable).
        //   • NARROW (phone) → a compact `≡` HAMBURGER header + a drawer of choices,
        //     so the long list doesn't wrap into many rows and bury the canvas.
        // Capture the bar's rect either way so a headless test can prove the collapsed
        // menu is one compact row, not a viewport-eating wrap.
        let bar = ui.scope(|ui| {
            if self.menu_collapsed {
                self.draw_menu_drawer(&titles, ui);
            } else {
                // Wrap the tab bar: with many facets a single non-wrapping row overflows
                // the panel width and the trailing tabs become unreachable (off-screen,
                // unclickable for a robot driver / pointer). Wrapping keeps every tab
                // visible + clickable no matter how many facets the deck holds.
                // navgraph: the strip is a Group whose draw order IS its declared order
                // (the deck's facet order), and each tab is a focusable Field.
                //
                // GROUPED (opt-in `with_groups`): a group row first, then ONLY the active
                // group's tabs in the same `tabs` strip — so a tab's navgraph id
                // (`…tabs.<title>`) and its AccessKit label are the ones the flat strip had.
                let shown: Vec<usize> = match self.active_group() {
                    Some(g) => {
                        self.draw_group_row(ui);
                        // The group row may have switched the active facet.
                        let g = self.active_group().unwrap_or(g);
                        self.groups[g].members.clone()
                    }
                    None => (0..titles.len()).collect(),
                };
                let nav = navgraph::begin(ui, "tabs", navgraph::NavKind::Group, "tabs");
                navgraph::declare_draw_order(ui, nav);
                let strip = ui.horizontal_wrapped(|ui| {
                    for &i in &shown {
                        let t = &titles[i];
                        let r = ui.selectable_value(&mut self.active, i, t);
                        navgraph::field(ui, t, &r);
                    }
                });
                navgraph::end(ui, nav, strip.response.rect);
                self.note_group_entry();
            }
        });
        self.menu_bar_rect = bar.response.rect;

        let caps = self.active_caps();

        // Capability-driven toolbar: only show controls the active facet honors.
        if caps.scalable {
            ui.horizontal(|ui| {
                if ui.button("−").on_hover_text("Zoom out (Ctrl-−)").clicked() {
                    self.scale_active(1.0 / 1.1);
                }
                ui.label(format!("{:.0}%", self.active_scale() * 100.0));
                if ui.button("+").on_hover_text("Zoom in (Ctrl-+)").clicked() {
                    self.scale_active(1.1);
                }
                if ui.button("Reset").on_hover_text("Reset zoom (Ctrl-0)").clicked() {
                    self.reset_scale();
                }
            });
        }

        // Capability-gated scale shortcuts. egui has no semantic event for these,
        // so we hand-detect the key combos (clipboard uses semantic events below).
        if caps.scalable {
            let (cmd, plus, minus, zero) = ui.input(|i| {
                (
                    i.modifiers.command,
                    i.key_pressed(egui::Key::Plus) || i.key_pressed(egui::Key::Equals),
                    i.key_pressed(egui::Key::Minus),
                    i.key_pressed(egui::Key::Num0),
                )
            });
            if cmd {
                if plus {
                    self.scale_active(1.1);
                }
                if minus {
                    self.scale_active(1.0 / 1.1);
                }
                if zero {
                    self.reset_scale();
                }
            }
        }

        // Clipboard routing: drain semantic events and dispatch to the active
        // facet, gated by its caps. A focused TextEdit already consumed its own.
        self.route_clipboard(ui.ctx());

        // Cross-instance component clone (DISTINCT gesture): the Ctrl+Shift+C/V
        // accelerators + any pending envelope paste, drained the same frame.
        self.route_component_clipboard(ui);

        ui.separator();
        // Optionally wrap the active facet in the shared glass/card chrome
        // (`chrome` module), gated by the active EffectsPolicy. Reserve a paint slot
        // BEFORE the content so the glass fill sits behind it; the glow + border
        // edge is painted on top afterwards.
        let chrome_on = self.fx.chrome;
        let chrome_slot = chrome_on.then(|| ui.painter().add(egui::Shape::Noop));
        // navgraph: the active facet is a Pane keyed like its dev-id chip, opened
        // BEFORE it draws so its atoms hang under it; the badge below merges into it.
        let nav = self.nav_pane_begin(ui);
        // Render the active facet, capturing the rect it occupied so the deck can
        // bloom it (opt-in glow) without the facet knowing.
        let content = ui.scope(|ui| {
            if let Some(f) = self.facets.get_mut(self.active) {
                // Render-trace: this facet's `ui()` RAN this frame (the wasm-safe
                // "what ran" ledger — folded into state_json, read via the JS hook
                // on wasm). Keyed by tab title so the ran-list maps tab → ran?.
                runtrace::ran(&format!("deck.render:{}", f.title()));
                f.ui(ui);
            }
        });
        let content_rect = content.response.rect;
        navgraph::end(ui, nav, content_rect);
        // The DEV-ID chip, on the rect the facet actually occupied. This is the draw
        // path the apps really use (`Deck::ui`); `pane_ui` below is the host-driven
        // one. Both paint it, because a badge wired only into the path nobody calls is
        // a feature that ships green and never appears (facett-demo goes through HERE).
        if let Some(f) = self.facets.get(self.active) {
            let (component, title) = (f.component(), f.title().to_string());
            devid::badge(ui, content_rect, component, &title);
        }
        // Remember the "canvas" rect — the screen the collapsed menu hands to the
        // active facet (read back via `state_json.menu.content_rect`).
        self.content_rect = content_rect;

        // Paint the card chrome around the facet's content rect.
        if let Some(slot) = chrome_slot
            && content_rect.is_positive()
        {
            let theme = self.effective_theme();
            let policy = crate::look::effects_policy(ui);
            let style = chrome::ChromeStyle::default().for_policy(policy);
            let card = content_rect.expand(6.0);
            ui.painter().set(slot, chrome::fill_shape(card, &theme, policy, style));
            chrome::edge(ui.painter(), card, &theme, policy, style);
        }

        // Right-click the active facet body → the Copy/Paste-component menu (the
        // discoverable affordance for the cross-instance clone gesture). The
        // text clipboard's own copy/paste is unaffected (different gesture).
        if !self.active_kind().is_empty() {
            content.response.context_menu(|ui| self.component_menu(ui));
        }

        // Opt-in glow on the active facet's content rect, pulsing.
        if self.fx.glow && content_rect.is_positive() {
            let theme = self.effective_theme();
            let time = ui.input(|i| i.time);
            let painter = ui.painter_at(content_rect);
            deckfx::paint_active_glow(&painter, content_rect.shrink(2.0), &theme, &self.fx, time);
            ui.ctx().request_repaint(); // keep the pulse animating
        }

        // Drive + paint a summoned raven on a foreground layer above everything.
        self.drive_raven(ui.ctx());

        // Paint the component-clone toast (mismatch / rejection feedback) on top.
        self.paint_component_toast(ui);
    }

    /// Draw the collapsed **hamburger menu** for a narrow viewport: a compact header
    /// (`≡` / `✕` toggle + the active choice's label) and, when the drawer is open, the
    /// full choice list as a vertical, scrollable drawer. Picking a choice switches the
    /// active facet AND shuts the drawer (canvas-first again). Mirrors the demo shell's
    /// `⚙` control-strip fold, applied to the MAIN menu.
    fn draw_menu_drawer(&mut self, titles: &[String], ui: &mut Ui) {
        // Grouped deck: the group row stays visible on a phone too (a handful of short
        // names), so every group — Grafer, Kartor, … — is one tap away and the drawer
        // below lists only the active group's tabs. Picking a group opens its drawer.
        if self.active_group().is_some() && self.draw_group_row(ui) {
            self.menu_open = true;
        }
        let active_label = titles.get(self.active).cloned().unwrap_or_default();
        ui.horizontal(|ui| {
            // The hamburger toggle. `≡` closed, `✕` open — a single tappable glyph.
            let glyph = if self.menu_open { "✕" } else { "≡" };
            let hint = if self.menu_open { "close the menu — give the canvas the screen" } else { "choose a view" };
            if ui.selectable_label(self.menu_open, glyph).on_hover_text(hint).clicked() {
                self.menu_open = !self.menu_open;
            }
            // The current choice's label, so the collapsed header still says WHAT is shown.
            ui.label(&active_label);
        });
        if self.menu_open {
            // The full choice list as a vertical DRAWER (bounded + scrollable so 60+
            // choices never blow past the viewport). Selecting one switches + closes.
            // Bounded by the screen too: a phone in landscape is shorter than 420 pt.
            let max_h = (ui.ctx().content_rect().height() * 0.6).clamp(160.0, 420.0);
            egui::Frame::group(ui.style()).show(ui, |ui| {
                egui::ScrollArea::vertical().max_height(max_h).auto_shrink([false, true]).show(ui, |ui| {
                    // Grouped deck: the active group's tabs (the group row above picks
                    // the group). Ungrouped: the one flat list.
                    let members: Vec<usize> = match self.active_group() {
                        Some(g) => self.groups[g].members.clone(),
                        None => (0..titles.len()).collect(),
                    };
                    for i in members {
                        let Some(t) = titles.get(i) else { continue };
                        if ui.selectable_label(self.active == i, t.as_str()).clicked() {
                            self.active = i;
                            self.menu_open = false;
                        }
                    }
                });
            });
        }
    }

    /// Advance + paint the summoned raven (if any) on a foreground layer. Pins its
    /// launch time on the first frame and keeps repainting while it flies.
    fn drive_raven(&mut self, ctx: &egui::Context) {
        let Some(raven) = self.raven.as_mut() else { return };
        raven.sprite.update(ctx);
        let painter =
            ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("facett_deck_raven")));
        raven.sprite.paint(&painter);
    }

    /// Route this frame's clipboard events to the active facet, gated by caps.
    /// The single OS-touching write (`clipboard::put`) lives here.
    fn route_clipboard(&mut self, ctx: &egui::Context) {
        let caps = self.active_caps();
        if !(caps.copyable || caps.cuttable || caps.pasteable) {
            return;
        }
        for action in clipboard::poll(ctx) {
            let Some(f) = self.facets.get_mut(self.active) else { continue };
            match action {
                ClipAction::Copy if caps.copyable => {
                    if let Some(t) = f.copy() {
                        clipboard::put(ctx, t);
                    }
                }
                ClipAction::Cut if caps.cuttable => {
                    if let Some(t) = f.cut() {
                        clipboard::put(ctx, t);
                    }
                }
                ClipAction::Paste(s) if caps.pasteable => {
                    f.paste(&s);
                }
                // Capability not declared → ignore (event may belong to a focused
                // sub-widget egui already handled).
                _ => {}
            }
        }
    }

    // ── cross-instance component clone (Copy/Paste component) ────────────────
    //
    // A DISTINCT gesture from the text clipboard above: it transfers a facet's
    // type-tagged PORTABLE state (not a text selection) to a same-kind sibling.
    // See `.nornir/design/copy-paste-between-instances.md`. Surfaced two ways —
    // the context menu in `component_menu` (right-click the body) and the
    // `Ctrl+Shift+C / Ctrl+Shift+V` accelerators routed in `ui`.

    /// The active facet's [`Facet::kind`] (`""` if empty / opted out).
    pub fn active_kind(&self) -> &'static str {
        self.facets.get(self.active).map(|f| f.kind()).unwrap_or("")
    }

    /// **Copy component** — encode the active facet's [`Facet::portable_state`]
    /// into the tagged clipboard envelope and place it on the OS clipboard.
    /// Returns the envelope text on success, or `None` if the active facet opts
    /// out (empty `kind()` or no `portable_state()`). This is the data half the
    /// gesture handlers + tests drive; the OS write is the caller's via
    /// [`clipboard::put`] (done for them in [`copy_component`](Self::copy_component)).
    pub fn copy_component_envelope(&self) -> Option<String> {
        let f = self.facets.get(self.active)?;
        let kind = f.kind();
        if kind.is_empty() {
            return None;
        }
        let state = f.portable_state()?;
        Some(clipboard::encode_component(kind, &state))
    }

    /// Copy the active facet's portable state to the OS clipboard (the full
    /// gesture). Returns `true` if something was copied.
    pub fn copy_component(&mut self, ctx: &egui::Context) -> bool {
        match self.copy_component_envelope() {
            Some(env) => {
                clipboard::put(ctx, env);
                true
            }
            None => false,
        }
    }

    /// **Paste component** — decode a clipboard `text` envelope and, **only if its
    /// kind matches the active facet's** [`Facet::kind`], hand the state to
    /// [`Facet::load_state`]. Returns `true` if the active facet adopted it.
    /// A kind mismatch (or a non-envelope / wrong-version text) is a no-op that
    /// raises a themed mismatch [`toast`](Self::toast) — the type-match guard is
    /// the whole point: a `table` envelope NEVER loads into a `graphpan`.
    pub fn paste_component(&mut self, text: &str, now: f64) -> bool {
        let Some((kind, state)) = clipboard::decode_component(text) else {
            // Not a component envelope at all — leave it for the text path; no toast.
            return false;
        };
        let active_kind = self.active_kind();
        if active_kind.is_empty() {
            self.toast = Some(("this view doesn't accept a pasted component".to_string(), now));
            return false;
        }
        if kind != active_kind {
            self.toast = Some((format!("clipboard holds a `{kind}`, not a `{active_kind}`"), now));
            return false;
        }
        let Some(f) = self.facets.get_mut(self.active) else { return false };
        let accepted = f.load_state(&state);
        if !accepted {
            self.toast = Some((format!("this `{active_kind}` could not adopt the clipboard state"), now));
        }
        accepted
    }

    /// The current component-clone toast message (if one is live), for tests /
    /// hosts that want to surface it themselves.
    pub fn component_toast(&self) -> Option<&str> {
        self.toast.as_ref().map(|(m, _)| m.as_str())
    }

    /// Right-click context-menu entries for the cross-instance clone gesture —
    /// **Copy component** / **Paste component** — themed by the active style. A
    /// host attaches these to the facet body (or its tab) via
    /// `response.context_menu(|ui| deck.component_menu(ui))`. Greys out when the
    /// active facet opts out (empty `kind()`).
    pub fn component_menu(&mut self, ui: &mut egui::Ui) {
        let km = look::keymap(ui);
        let kind = self.active_kind();
        let can_clone = !kind.is_empty();
        ui.add_enabled_ui(can_clone && self.copy_component_envelope().is_some(), |ui| {
            let label = format!("Copy component  {}", km.label(Action::Copy, ui.ctx()));
            if ui.button(label).clicked() {
                self.copy_component(ui.ctx());
                ui.close();
            }
        });
        ui.add_enabled_ui(can_clone, |ui| {
            let label = format!("Paste component  {}", km.label(Action::Paste, ui.ctx()));
            if ui.button(label).clicked() {
                // Pull the OS clipboard via egui's paste request; the actual text
                // arrives next frame as an Event::Paste, routed in `route_component_clipboard`.
                ui.ctx().send_viewport_cmd(egui::ViewportCommand::RequestPaste);
                ui.close();
            }
        });
    }

    /// Route the `Ctrl+Shift+C / Ctrl+Shift+V` component-clone accelerators +
    /// drain any pending paste envelope. Called once per frame from [`ui`](Self::ui),
    /// AFTER the text clipboard so a focused TextEdit's plain Ctrl+C/V is untouched
    /// (the Shift discriminates this gesture from text copy/paste).
    fn route_component_clipboard(&mut self, ui: &mut egui::Ui) {
        let now = ui.input(|i| i.time);
        // Accelerators: Ctrl+Shift+C copies; Ctrl+Shift+V triggers an OS-clipboard
        // paste request (the text lands next frame as Event::Paste, decoded below).
        let copy_shift = egui::KeyboardShortcut::new(
            egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
            egui::Key::C,
        );
        let paste_shift = egui::KeyboardShortcut::new(
            egui::Modifiers::COMMAND | egui::Modifiers::SHIFT,
            egui::Key::V,
        );
        if ui.input_mut(|i| i.consume_shortcut(&copy_shift)) {
            self.copy_component(ui.ctx());
        }
        if ui.input_mut(|i| i.consume_shortcut(&paste_shift)) {
            ui.ctx().send_viewport_cmd(egui::ViewportCommand::RequestPaste);
        }
        // Drain any Paste events that look like a component envelope (a plain text
        // paste decodes to None here and is left for the text clipboard path).
        let pastes: Vec<String> = ui.input(|i| {
            i.events
                .iter()
                .filter_map(|e| match e {
                    egui::Event::Paste(s) if clipboard::decode_component(s).is_some() => Some(s.clone()),
                    _ => None,
                })
                .collect()
        });
        for text in pastes {
            self.paste_component(&text, now);
        }
        // Age out the toast.
        if let Some((_, raised)) = self.toast && now - raised > TOAST_SECS {
            self.toast = None;
        }
    }

    /// Paint the live component-clone toast on a foreground layer (themed, spacious),
    /// if one is set. A no-op when there is no toast.
    fn paint_component_toast(&self, ui: &mut egui::Ui) {
        let Some((msg, _)) = self.toast.as_ref() else { return };
        let th = theme(ui);
        let ctx = ui.ctx();
        let painter =
            ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("facett_deck_component_toast")));
        let screen = ctx.content_rect();
        let font = FontId::proportional(14.0);
        let galley = painter.layout_no_wrap(msg.clone(), font.clone(), th.text);
        let pad = vec2(14.0, 10.0); // spacious preset padding
        let size = galley.size() + pad * 2.0;
        // Bottom-centre, lifted off the edge.
        let center = Pos2::new(screen.center().x, screen.max.y - size.y * 0.5 - 18.0);
        let rect = Rect::from_center_size(center, size);
        painter.rect_filled(rect, 8.0, th.panel_bg);
        painter.rect_stroke(rect, 8.0, Stroke::new(1.0_f32, th.panel_stroke), egui::StrokeKind::Inside);
        painter.galley(rect.min + pad, galley, th.text);
        ctx.request_repaint(); // keep ticking so the toast ages out on time
    }

    /// The whole-app observable state: the active facet + each facet's
    /// `state_json`, plus an **additive** sibling `caps` map (title → caps JSON)
    /// so the existing flat `facets[title]` shape is unchanged for consumers.
    pub fn state_json(&self) -> serde_json::Value {
        self.state_json_inner(None)
    }

    /// [`state_json`](Self::state_json) for a host that publishes it **every frame**
    /// (the wasm demo's `window.__facett_state()`): the ACTIVE facet's state is built
    /// every call, ONE inactive facet's in turn (round-robin), and every other inactive
    /// facet's is the copy `cache` holds from its last turn — so a frame pays for the
    /// tab on screen plus 1/N of the rest instead of all N.
    ///
    /// MEASURED (lane M, 2026-10-02): the pages demo serialised all 81 tabs every frame;
    /// with `lineage` at 100k on screen that included the inactive `Graphs` tab's full
    /// demo-data state (its population graph: 102 kB, 1.2 ms per frame natively on
    /// dwarf, vs lineage's demo 34 µs when `Graphs` is the one on screen) — the whole
    /// gap between lineage's 56.8 fps and Graphs' 60.2 on loki's RTX 5080. An inactive
    /// tab's state is at most one round (N frames) old; a tab is fresh from the frame it
    /// becomes active. The shape is `state_json`'s exactly.
    pub fn state_json_rolling(&self, cache: &mut DeckStateCache) -> serde_json::Value {
        self.state_json_inner(Some(cache))
    }

    /// Hand the facets map of a [`state_json_rolling`](Self::state_json_rolling) result
    /// (`deck` = that value, or the `"deck"` subtree a host embedded it in) back to `cache`.
    pub fn return_rolling(cache: &mut DeckStateCache, mut deck: serde_json::Value) {
        if let Some(serde_json::Value::Object(m)) = deck.get_mut("facets").map(serde_json::Value::take) {
            cache.facets = m;
        }
    }

    /// **Serialise a state that embeds a rolling deck state** (at `deck_pointer`, e.g.
    /// `"/deck"`, or `""` for the deck state itself) and hand its facets back to `cache`.
    /// Each facet's JSON text is reused unless its state was rebuilt this call, so a
    /// frame serialises the tab on screen + one other, not every tab's tree — the bytes
    /// are `serde_json::to_string`'s exactly.
    pub fn serialize_rolling(cache: &mut DeckStateCache, mut state: serde_json::Value, deck_pointer: &str) -> String {
        const MARK: &str = "\u{0}facett-rolling-facets\u{0}";
        let slot = state.pointer_mut(&format!("{deck_pointer}/facets"));
        let Some(slot) = slot else { return serde_json::to_string(&state).unwrap_or_default() };
        let serde_json::Value::Object(facets) = std::mem::replace(slot, serde_json::Value::String(MARK.into())) else {
            return serde_json::to_string(&state).unwrap_or_default();
        };
        let head = serde_json::to_string(&state).unwrap_or_default();
        cache.text.retain(|k, _| facets.contains_key(k));
        let mut body = String::with_capacity(cache.text.values().map(|t| t.len() + 32).sum::<usize>() + 2);
        body.push('{');
        for (i, (k, v)) in facets.iter().enumerate() {
            if i > 0 {
                body.push(',');
            }
            body.push_str(&serde_json::to_string(k).unwrap_or_default());
            body.push(':');
            match cache.text.get(k) {
                Some(t) => body.push_str(t),
                None => {
                    let t = serde_json::to_string(v).unwrap_or_default();
                    body.push_str(&t);
                    cache.text.insert(k.clone(), t);
                }
            }
        }
        body.push('}');
        cache.facets = facets;
        let mark = serde_json::to_string(MARK).unwrap_or_default();
        head.replacen(&mark, &body, 1)
    }

    fn state_json_inner(&self, cache: Option<&mut DeckStateCache>) -> serde_json::Value {
        let mut caps = serde_json::Map::new();
        for f in &self.facets {
            caps.insert(f.title().to_string(), f.caps().to_json());
        }
        let facets = match cache {
            None => self.facets.iter().map(|f| (f.title().to_string(), f.state_json())).collect(),
            Some(c) => {
                let n = self.facets.len();
                // A map that does not hold exactly this deck's titles is rebuilt whole.
                if c.facets.len() != n || self.facets.iter().any(|f| !c.facets.contains_key(f.title())) {
                    c.facets.clear();
                    c.text.clear();
                }
                // This call's round-robin turn: the next inactive facet after the last one.
                let turn = (0..n).map(|k| (c.next + k) % n.max(1)).find(|&i| i != self.active);
                c.next = turn.map_or(0, |i| i + 1);
                for (i, f) in self.facets.iter().enumerate() {
                    if i == self.active || Some(i) == turn || !c.facets.contains_key(f.title()) {
                        c.built += 1;
                        c.facets.insert(f.title().to_string(), f.state_json());
                        c.text.remove(f.title());
                    }
                }
                std::mem::take(&mut c.facets)
            }
        };
        let mr = self.menu_bar_rect;
        let cr = self.content_rect;
        serde_json::json!({
            "active": self.facets.get(self.active).map(|f| f.title()),
            "facets": facets,
            "caps": caps,
            // The RESPONSIVE menu (#39-follow): whether the tab bar is the collapsed
            // hamburger (phone-class) and, if so, whether its drawer is open — plus the
            // menu-header rect and the active-facet ("canvas") rect, so a headless test
            // proves the collapsed menu is one compact row and the canvas gets the screen.
            "menu": {
                "collapsed": self.menu_collapsed,
                "open": self.menu_open,
                "active": self.facets.get(self.active).map(|f| f.title()),
                "count": self.facets.len(),
                // The two-level bar (`with_groups`): the active group + every group's
                // name and size, in display order. `null` / `[]` when ungrouped.
                "group": self.active_group_name(),
                "groups": self.groups.iter().map(|g| serde_json::json!({
                    "name": g.name,
                    "tabs": g.members.len(),
                })).collect::<Vec<_>>(),
                "bar_rect": [mr.min.x, mr.min.y, mr.width(), mr.height()],
                "content_rect": [cr.min.x, cr.min.y, cr.width(), cr.height()],
            },
            // The deck's opt-in effects (DeckFx) as data: whether the shared glass/
            // card `chrome` wrap is on, whether the active-facet bloom glow is on, and
            // the active palette override. A headless driver reads this to PROVE the
            // T1.3 showcase rendering (glass + bloom) is actually wired, not eyeballed.
            "fx": {
                "chrome": self.fx.chrome,
                "glow": self.fx.glow,
                "glow_layers": self.fx.glow_layers,
                "palette": self.fx.palette(),
            },
            // The wasm-safe "what RAN" ledger — every facet render + every traced
            // control handler that has executed this session (the readable proof
            // the shipped artifact actually ran each surface). See `runtrace`.
            "trace": { "ran": runtrace::snapshot(), "distinct": runtrace::distinct() },
            // The DEV-ID gate — enabled/env/profile/source. Reports whether the chips
            // are SWITCHED ON, not whether one is on screen; see `devid::gate_json`.
            "devid": devid::gate_json(),
        })
    }
}

/// A stable, bright-ish colour from a string (FNV-1a). Handy default node colour.
pub fn hash_color(s: &str) -> Color32 {
    let mut h: u32 = 2166136261;
    for b in s.bytes() {
        h = (h ^ b as u32).wrapping_mul(16777619);
    }
    Color32::from_rgb((h & 0xFF) as u8 | 0x60, ((h >> 8) & 0xFF) as u8 | 0x60, ((h >> 16) & 0xFF) as u8 | 0x60)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn scene_builds() {
        let mut s = Scene::new();
        let a = s.node("Person", hash_color("Person"));
        let b = s.node("Company", hash_color("Company"));
        s.edge(a, b);
        assert_eq!(s.nodes.len(), 2);
        assert_eq!(s.edges.len(), 1);
        assert!(!s.is_empty());
    }

    #[test]
    fn force_layout_produces_finite_bounded_positions() {
        let mut scene = Scene::new();
        for i in 0..12 { scene.node(format!("n{i}"), hash_color("n")); }
        for i in 0..12 { scene.edge(i, (i + 1) % 12); }
        let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(400.0, 400.0));
        let pos = positions(Layout::Force, &scene, rect);
        assert_eq!(pos.len(), 12);
        for p in &pos {
            assert!(p.x.is_finite() && p.y.is_finite(), "finite");
            assert!(rect.expand(50.0).contains(*p), "roughly within the rect");
        }
    }

    /// **Scale (RED-when-broken): the repulsion is sub-quadratic, measured as a
    /// GROWTH RATIO and not as a wall clock.**
    ///
    /// This was `assert!(ms < 20_000.0)` on one 10 000-node run, which is two defects
    /// in one line (stinky `mapgpu-2`): on a loaded box a *correct* implementation
    /// fails (MEASURED 2026-08-03: 39 616 ms at load average 120 on 32 cores), and on
    /// an idle box an O(n²) implementation *passes*. A wall clock cannot answer a
    /// complexity question — it answers a hardware question.
    ///
    /// What is measured instead is `t(4n) / t(n)`, which is ~16 for a quadratic
    /// repulsion and ~2–4 for `O(n log n)`. A ratio is immune to machine load because
    /// both halves of it contend for the same cores in the same run, and the **4×**
    /// spacing (rather than 2×) is deliberate: it puts the two classes an order of
    /// magnitude apart, so load only has to be survived, not eliminated.
    ///
    /// **ARM 1 is a red probe that runs every time.** Below
    /// [`BH_THRESHOLD`](crate::barnes_hut::BH_THRESHOLD) `positions` deliberately keeps
    /// the exact all-pairs loop, so the same instrument is pointed at a *known
    /// quadratic* and required to say so against the *same gate*. If arm 1 cannot see
    /// quadratic growth where quadratic growth demonstrably lives, arm 2's green is not
    /// evidence and the test fails at arm 1 instead of passing blind.
    ///
    /// MEASURED on oden 2026-08-22, debug build, load average 91 on 32 cores:
    /// quadratic arm `n=250 194.4 ms → n=1000 3 625.7 ms = 18.651`; Barnes–Hut arm
    /// `n=2000 1 541.5 ms → n=8000 3 043.7 ms = 1.975`. That is a **9.4× separation**,
    /// and the single gate below sits in the empty middle of it.
    ///
    /// **SEEN RED**: an earlier 2×-spaced revision of this test was run with `use_bh`
    /// forced to `false` in [`positions`] — the exact regression it exists to catch —
    /// and failed with `26 656.7 ms → 68 839.0 ms = 2.582` against a correct 1.502 on
    /// the same box. That run also showed *why* the spacing was widened to 4×: at load
    /// average 121 a 2× step compresses a true quadratic from 3.976 to 3.151 and the
    /// regressed Barnes–Hut arm to 2.582, which is far too little daylight.
    #[test]
    fn force_layout_repulsion_is_sub_quadratic() {
        /// The gate BOTH arms are judged against. Quadratic growth over a 4× step is
        /// ~16; `O(n log n)` is ~2–4. One number, so the red probe and the claim
        /// cannot drift apart.
        const QUADRATIC_GATE: f64 = 8.0;

        /// A sparse ring + chords: O(n) edges, so the only super-linear term left in
        /// the layout is the repulsion this test is about.
        fn ring_scene(n: usize) -> Scene {
            let mut scene = Scene::new();
            for i in 0..n {
                scene.node(format!("n{i}"), hash_color("n"));
            }
            for i in 0..n {
                scene.edge(i, (i + 1) % n);
                if i % 7 == 0 {
                    scene.edge(i, (i + 137) % n);
                }
            }
            scene
        }
        let rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1024.0, 1024.0));
        // Best of two: the MINIMUM is the estimator least polluted by a scheduler
        // steal, and a steal can only ever make a run slower, never faster.
        let run = |n: usize| -> f64 {
            let scene = ring_scene(n);
            let mut best = f64::INFINITY;
            for _ in 0..2 {
                let t0 = std::time::Instant::now();
                let pos = positions(Layout::Force, &scene, rect);
                let ms = t0.elapsed().as_secs_f64() * 1000.0;
                assert_eq!(pos.len(), n);
                for p in &pos {
                    assert!(p.x.is_finite() && p.y.is_finite(), "every node finite at n={n}");
                    assert!(rect.expand(50.0).contains(*p), "every node bounded at n={n}");
                }
                best = best.min(ms);
            }
            best
        };

        // ── ARM 1 (RED PROBE): the instrument sees a quadratic when there IS one ──
        const QUAD_N: usize = 250;
        const _: () = assert!(
            4 * QUAD_N < crate::barnes_hut::BH_THRESHOLD,
            "arm 1 must stay entirely on the exact all-pairs path"
        );
        let q1 = run(QUAD_N);
        let q4 = run(4 * QUAD_N);
        let quad_ratio = q4 / q1;
        assert!(
            quad_ratio >= QUADRATIC_GATE,
            "RED PROBE FAILED: the exact all-pairs repulsion below BH_THRESHOLD grew only \
             {quad_ratio:.3}x from n={QUAD_N} ({q1:.1} ms) to n={} ({q4:.1} ms), against the \
             {QUADRATIC_GATE} this test calls quadratic (measured 18.651 on oden). This box cannot \
             currently tell quadratic from n log n, so the Barnes-Hut arm below would be blind — \
             re-run it somewhere less contended rather than trusting a green.",
            4 * QUAD_N
        );

        // ── ARM 2: the claim ──────────────────────────────────────────────────
        const BH_N: usize = 2_000;
        const _: () = assert!(BH_N >= crate::barnes_hut::BH_THRESHOLD, "arm 2 must be on the Barnes-Hut path");
        let b1 = run(BH_N);
        let b4 = run(4 * BH_N);
        let bh_ratio = b4 / b1;
        assert!(
            bh_ratio < QUADRATIC_GATE,
            "the force layout is not sub-quadratic: t(4n)/t(n) = {bh_ratio:.3} \
             ({b1:.1} ms at n={BH_N} -> {b4:.1} ms at n={}), against {quad_ratio:.3} for the \
             all-pairs loop the same instrument measured seconds ago. A regression to quadratic \
             repulsion above BH_THRESHOLD lands exactly here.",
            4 * BH_N
        );
    }

    #[test]
    fn hash_color_is_stable() {
        assert_eq!(hash_color("Person"), hash_color("Person"));
        assert_ne!(hash_color("Person"), hash_color("Company"));
    }

    /// A minimal facet for deck tests.
    struct Stub(&'static str);
    impl Facet for Stub {
        fn title(&self) -> &str {
            self.0
        }
        fn ui(&mut self, ui: &mut Ui) {
            ui.label(self.0);
        }
        fn state_json(&self) -> serde_json::Value {
            serde_json::json!({ "t": self.0 })
        }
    }

    /// A facet whose state counts its own builds (`Cell` — `state_json` takes `&self`).
    struct Counted(&'static str, std::rc::Rc<std::cell::Cell<u32>>);
    impl Facet for Counted {
        fn title(&self) -> &str {
            self.0
        }
        fn ui(&mut self, _ui: &mut Ui) {}
        fn state_json(&self) -> serde_json::Value {
            self.1.set(self.1.get() + 1);
            serde_json::json!({ "t": self.0, "n": self.1.get() })
        }
    }

    /// The page publishes the deck's state every frame: the rolling form builds the
    /// active tab every call and ONE inactive tab per call, serves the rest from the
    /// cache, keeps `state_json`'s shape, and a newly active tab is fresh at once.
    #[test]
    fn rolling_state_builds_the_active_tab_and_one_other_per_frame() {
        let counts: Vec<_> = (0..5).map(|_| std::rc::Rc::new(std::cell::Cell::new(0u32))).collect();
        let names = ["a", "b", "c", "d", "e"];
        let mut deck = FacetDeck::new(
            names.iter().zip(&counts).map(|(n, c)| Box::new(Counted(n, c.clone())) as Box<dyn Facet>).collect(),
        );
        let mut cache = DeckStateCache::default();
        let first = deck.state_json_rolling(&mut cache);
        assert_eq!(cache.built, 5, "the first call builds everything");
        let full = deck.state_json();
        let keys = |v: &serde_json::Value| v.as_object().unwrap().keys().cloned().collect::<Vec<_>>();
        assert_eq!(keys(&first), keys(&full), "same shape as state_json");
        assert_eq!(keys(&first["facets"]), keys(&full["facets"]));
        FacetDeck::return_rolling(&mut cache, first);
        for _ in 0..8 {
            let v = deck.state_json_rolling(&mut cache);
            FacetDeck::return_rolling(&mut cache, v);
        }
        // 8 frames: the active tab 8 more times, the four others twice each (one per frame).
        assert_eq!(cache.built, 5 + 8 * 2);
        let after: Vec<u32> = counts.iter().map(|c| c.get()).collect();
        // +1 each for the plain `state_json` above.
        assert_eq!(after, vec![1 + 1 + 8, 1 + 1 + 2, 1 + 1 + 2, 1 + 1 + 2, 1 + 1 + 2]);
        // A tab made active is built on the very next call.
        assert!(deck.set_active_by_title("d"));
        let before = counts[3].get();
        let v = deck.state_json_rolling(&mut cache);
        assert_eq!(counts[3].get(), before + 1);
        assert_eq!(v["facets"]["d"]["n"], before + 1, "the active tab's state is this frame's");
        assert_eq!(v["active"], "d");
        // The spliced serialisation is byte-for-byte serde's, and reuses the text.
        let v = deck.state_json_rolling(&mut cache);
        let plain = serde_json::to_string(&v).unwrap();
        let spliced = FacetDeck::serialize_rolling(&mut cache, serde_json::json!({ "deck": v, "x": 1 }), "/deck");
        assert_eq!(spliced, format!("{{\"deck\":{plain},\"x\":1}}"));
        let v = deck.state_json_rolling(&mut cache);
        let plain = serde_json::to_string(&v).unwrap();
        assert_eq!(FacetDeck::serialize_rolling(&mut cache, v, ""), plain, "the deck state itself");
        // A host that never hands the map back still gets a whole, correct state.
        drop(deck.state_json_rolling(&mut cache));
        let built = cache.built;
        let w = deck.state_json_rolling(&mut cache);
        assert_eq!(cache.built, built + 5, "nothing to serve from: every tab rebuilt");
        assert_eq!(keys(&w["facets"]), keys(&full["facets"]));
    }

    /// A component-clone-capable stub: a `kind`, a JSON `payload` it round-trips
    /// through `portable_state`/`load_state`.
    struct CloneStub {
        kind: &'static str,
        payload: serde_json::Value,
    }
    impl Facet for CloneStub {
        fn title(&self) -> &str {
            self.kind
        }
        fn ui(&mut self, _ui: &mut Ui) {}
        fn state_json(&self) -> serde_json::Value {
            serde_json::json!({ "kind": self.kind })
        }
        fn kind(&self) -> &'static str {
            self.kind
        }
        fn portable_state(&self) -> Option<serde_json::Value> {
            Some(self.payload.clone())
        }
        fn load_state(&mut self, state: &serde_json::Value) -> bool {
            self.payload = state.clone();
            true
        }
    }

    /// **The deck reports the DEV-ID gate too.** `facett_app::scene` is korp's container,
    /// but facett-demo and the wasm surfaces go through `FacetDeck`, and an oracle asking
    /// "are the chips on?" must get the same answer from either. A gate readable from only
    /// one of the two containers is exactly the shape of miss #2.
    #[test]
    fn the_deck_state_reports_the_devid_gate() {
        let deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
        let gate = deck.state_json()["devid"].clone();
        assert!(!gate.is_null(), "the deck's state_json carries no `devid` gate");
        assert_eq!(gate["enabled"], devid::enabled(), "deck reports a gate badge() disobeys");
        assert_eq!(gate["debug_assertions"], cfg!(debug_assertions), "wrong profile: {gate}");
    }

    #[test]
    fn component_clone_round_trips_through_the_deck() {
        // Instance A (configured) → envelope → instance B adopts it.
        let a = CloneStub { kind: "graphpan", payload: serde_json::json!({ "zoom": 2.0, "pan": [3, 4] }) };
        let deck_a = FacetDeck::new(vec![Box::new(a)]);
        let env = deck_a.copy_component_envelope().expect("A copies its portable state");

        let mut deck_b = FacetDeck::new(vec![Box::new(CloneStub {
            kind: "graphpan",
            payload: serde_json::json!({ "zoom": 1.0, "pan": [0, 0] }),
        })]);
        assert!(deck_b.paste_component(&env, 0.0), "same-kind paste is accepted");
        // B now equals A's portable state.
        assert_eq!(
            deck_b.copy_component_envelope(),
            deck_a.copy_component_envelope(),
            "B adopted A's portable state exactly"
        );
        assert!(deck_b.component_toast().is_none(), "a successful paste raises no toast");
    }

    #[test]
    fn component_clone_rejects_a_type_mismatch_with_a_toast() {
        // A `table` envelope handed to a `graphpan` → load_state NOT called.
        let table_env = clipboard::encode_component("table", &serde_json::json!({ "rows": 3 }));
        let mut deck = FacetDeck::new(vec![Box::new(CloneStub {
            kind: "graphpan",
            payload: serde_json::json!({ "zoom": 1.0 }),
        })]);
        let before = deck.copy_component_envelope();
        assert!(!deck.paste_component(&table_env, 0.0), "cross-type paste returns false");
        assert_eq!(deck.copy_component_envelope(), before, "graphpan state untouched");
        let toast = deck.component_toast().expect("mismatch raises a toast");
        assert!(toast.contains("table") && toast.contains("graphpan"), "toast names both kinds: {toast}");
    }

    #[test]
    fn component_clone_version_guard_rejects_unknown_v() {
        let bad = serde_json::json!({ "facett.kind": "graphpan", "v": 7, "state": { "zoom": 9.0 } }).to_string();
        let mut deck = FacetDeck::new(vec![Box::new(CloneStub {
            kind: "graphpan",
            payload: serde_json::json!({ "zoom": 1.0 }),
        })]);
        let before = deck.copy_component_envelope();
        // An unknown-version text decodes to None → it's a no-op (left for the text path).
        assert!(!deck.paste_component(&bad, 0.0), "unknown version is not adopted");
        assert_eq!(deck.copy_component_envelope(), before, "state untouched by a bad-version paste");
    }

    #[test]
    fn component_clone_opt_out_floor_neither_copies_nor_accepts() {
        // The plain Stub does NOT implement the trio → empty kind, no copy.
        let mut deck = FacetDeck::new(vec![Box::new(Stub("plain"))]);
        assert_eq!(deck.active_kind(), "", "opted out");
        assert!(deck.copy_component_envelope().is_none(), "opt-out facet never copies a component");
        // A real envelope handed to an opt-out facet is refused (no panic, no state).
        let env = clipboard::encode_component("table", &serde_json::json!({ "rows": 1 }));
        assert!(!deck.paste_component(&env, 0.0), "opt-out facet never adopts a component");
        assert!(deck.component_toast().is_some(), "the refusal is surfaced");
    }

    #[test]
    fn deck_fx_is_off_by_default() {
        let deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
        assert_eq!(*deck.fx(), DeckFx::OFF, "no effects until the host opts in");
        assert!(!deck.has_raven());
        assert!(!deck.fx().glow);
        assert!(deck.fx().palette().is_none());
    }

    #[test]
    fn deck_state_json_reports_fx_as_data() {
        // The deck's opt-in effects must be observable as data (a robot proof reads
        // `fx.chrome` / `fx.glow` to know the showcase rendering is wired ON).
        let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
        let off = deck.state_json();
        assert_eq!(off["fx"]["chrome"].as_bool(), Some(false), "chrome off by default");
        assert_eq!(off["fx"]["glow"].as_bool(), Some(false), "glow off by default");
        assert!(off["fx"]["palette"].is_null(), "no palette override by default");

        deck.fx_mut().chrome = true;
        deck.fx_mut().glow = true;
        deck.set_palette(2);
        let on = deck.state_json();
        assert_eq!(on["fx"]["chrome"].as_bool(), Some(true), "chrome wired ON shows in state");
        assert_eq!(on["fx"]["glow"].as_bool(), Some(true), "glow wired ON shows in state");
        assert_eq!(on["fx"]["palette"].as_u64(), Some(2), "palette override shows in state");
    }

    #[test]
    fn deck_cycle_palette_walks_theme_all() {
        let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
        let first = deck.cycle_palette();
        assert_eq!(first, 0);
        assert_eq!(deck.fx().theme().map(|t| t.name), Some(Theme::ALL[0]().name));
        // walks forward and wraps
        for _ in 1..Theme::ALL.len() {
            deck.cycle_palette();
        }
        assert_eq!(deck.cycle_palette(), 0, "wraps back to the first palette");
    }

    #[test]
    fn deck_send_raven_launches_and_perches_after_a_full_flight() {
        use crate::effects::RAVEN_FLIGHT_SECS;
        let mut deck = FacetDeck::new(vec![Box::new(Stub("rows"))]);
        assert!(!deck.has_raven());
        let target = egui::Rect::from_min_size(egui::pos2(120.0, 80.0), egui::vec2(200.0, 28.0));
        deck.send_raven(target);
        assert!(deck.has_raven(), "raven summoned");
        assert!(!deck.raven_perched(), "not perched at launch");

        // Drive the sprite headlessly past the flight duration → it perches.
        if let Some(r) = deck.raven.as_mut() {
            r.sprite.advance(RAVEN_FLIGHT_SECS + 0.1);
        }
        assert!(deck.raven_perched(), "perched after the flight duration");

        deck.clear_raven();
        assert!(!deck.has_raven());
    }

    /// REGRESSION (inject-assert): merely *drawing* the palette picker without a
    /// user click must NOT pin a palette override. The bug: the picker auto-pinned
    /// index 0 on the first passive frame, turning the legacy `set_theme` override
    /// permanently on and clobbering a host's own theme (the rich `look::Theme`)
    /// every frame. We render one frame with no interaction and assert the override
    /// is still `None` (host theme wins).
    #[test]
    fn palette_picker_does_not_pin_without_a_user_click() {
        let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
        assert!(deck.fx().palette().is_none(), "starts with no override");
        let ctx = egui::Context::default();
        let mut chosen = Some(7usize);
        ctx.run_ui(egui::RawInput::default(), |ui| {
            egui::CentralPanel::default().show(ui, |ui| {
                // No synthetic click is fed → the picker is drawn but not used.
                chosen = deck.palette_picker(ui);
            });
        }).textures_delta.clear();
        assert_eq!(chosen, None, "drawing the picker reports no selection without a click");
        assert!(
            deck.fx().palette().is_none(),
            "drawing the picker must not pin index 0 — that would clobber the host's own theme each frame"
        );
    }

    #[test]
    fn deck_palette_override_applies_theme_in_a_ui_pass() {
        let mut deck = FacetDeck::new(vec![Box::new(Stub("a"))]);
        deck.set_palette(1); // sci-fi
        let ctx = egui::Context::default();
        let mut seen = "";
        ctx.run_ui(egui::RawInput::default(), |ui| {
            egui::CentralPanel::default().show(ui, |ui| {
                deck.ui(ui);
                seen = theme(ui).name;
            });
        }).textures_delta.clear();
        assert_eq!(seen, Theme::ALL[1]().name, "deck applied its palette override");
    }

    // ── tab groups (the two-level bar) ─────────────────────────────────────────

    fn grouped_deck() -> FacetDeck {
        FacetDeck::new(vec![
            Box::new(Stub("graph")),
            Box::new(Stub("grid")),
            Box::new(Stub("Graphs")),
            Box::new(Stub("map")),
            Box::new(Stub("loose")),
        ])
        .with_groups(&[("Grafer", &["Graphs", "graph", "not-here"]), ("Kartor", &["map"]), ("Tom", &[])], "Övrigt")
    }

    #[test]
    fn every_facet_lands_in_exactly_one_group_in_deck_order() {
        let deck = grouped_deck();
        let names: Vec<&str> = deck.groups().iter().map(|g| g.name.as_str()).collect();
        // The empty group is dropped; the unlisted facets fall into the rest group.
        assert_eq!(names, ["Grafer", "Kartor", "Övrigt"]);
        assert_eq!(deck.groups()[0].members, vec![0, 2], "deck order, not list order; unknown titles skipped");
        assert_eq!(deck.groups()[2].members, vec![1, 4], "grid + loose are orphans");
        let mut all: Vec<usize> = deck.groups().iter().flat_map(|g| g.members.clone()).collect();
        all.sort_unstable();
        assert_eq!(all, (0..deck.len()).collect::<Vec<_>>(), "each facet once");
    }

    #[test]
    fn the_active_group_follows_the_active_tab_and_remembers_its_entry() {
        let mut deck = grouped_deck();
        assert_eq!(deck.active_group_name(), Some("Grafer"));
        // A programmatic switch (deep link / tour) moves the group with it.
        assert!(deck.set_active_by_title("map"));
        assert_eq!(deck.active_group_name(), Some("Kartor"));
        // Entering a group opens its first member the first time …
        assert!(deck.set_active_group("Övrigt"));
        assert_eq!(deck.active_title(), Some("grid"));
        assert!(deck.set_active_by_title("loose"));
        // … and the last shown member when re-entered (the bar notes it while drawing).
        let ctx = egui::Context::default();
        ctx.run_ui(egui::RawInput::default(), |ui| {
            egui::CentralPanel::default().show(ui, |ui| deck.ui(ui));
        }).textures_delta.clear();
        assert!(deck.set_active_group("Grafer"));
        assert!(deck.set_active_group("Övrigt"));
        assert_eq!(deck.active_title(), Some("loose"));
        assert!(!deck.set_active_group("nope"));
        let j = deck.state_json();
        assert_eq!(j["menu"]["group"], "Övrigt");
        assert_eq!(j["menu"]["groups"].as_array().unwrap().len(), 3);
    }

    #[test]
    fn an_ungrouped_deck_keeps_the_flat_strip() {
        let deck = FacetDeck::new(vec![Box::new(Stub("a")), Box::new(Stub("b"))]);
        assert!(deck.groups().is_empty());
        assert_eq!(deck.active_group_name(), None);
        assert_eq!(deck.state_json()["menu"]["groups"], serde_json::json!([]));
    }
}