entviz 0.15.1

Visualize high-entropy values as comparable SVG diagrams (entviz, spec v15).
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
//! Full render pipeline: entropy string → SVG string.
//!
//! Faithful port of `src/entviz/pipeline.py` + `renderer.py` + `shapes.py`.
//! Produces an SVG whose normative `data-*` attributes and geometry let the
//! conformance Tier-A extractor recover the golden render model, and whose
//! non-text pixels match the golden Tier-B raster.

use crate::entropy::{self, tokenize_entropy, ParseError, BASE64URL};
use crate::second_digest;
use crate::util::{assign_cell_indices, band_letter, two_bit_counts};
use crate::{
    choose_grid, closest_palette_color, compute_fingerprint, median_token, nucleus_colors,
    quartile_tokens, select_visual_style, tokenize_fingerprint, Grid, Token, VisualStyle,
};

const DPI: f64 = 96.0;
// Transparent quiet-margin ring (user units) on all four sides of the canvas so
// the gray frame never sits on the canvas edge (issue #31).
const MARGIN: f64 = 1.0;
const NOTE_MAX_LEN: usize = 10;
const MAX_INPUT_CHARS: usize = 65536;
// Fixed monospace advance (em) used to size the top strip's character
// budget for prefix truncation. A spec constant — NOT the renderer's real font
// metric — so all implementations compute the same integer budget and the
// Tier-A label string is reproducible. 0.6 em is the conventional monospace
// advance; the raster is unaffected (labels are excluded from the Tier-B
// raster). See docs/spec.md -> "Label strips".
const LABEL_ADVANCE_EM: f64 = 0.6;
const MONOSPACE_FONT_FAMILY: &str = "\"JetBrains Mono\", \"Menlo\", \"Consolas\", \"DejaVu Sans Mono\", \"Liberation Mono\", \"Roboto Mono\", \"Noto Sans Mono\", monospace";

#[derive(Debug)]
pub enum RenderError {
    Note(String),
    InputTooLong,
    FontSizeRange,
    AspectRatioRange,
    NoTokens,
    /// EIP-55 checksum mismatch. `position` is the index (within the 40-hex
    /// address body, 0-based) of the first digit whose case disagrees with the
    /// canonical case derived from keccak256(lower(body)). The spec MUST
    /// "identify the first mismatched-case digit", so the position is carried
    /// through to the error (and surfaced by the CLI) rather than discarded.
    Eip55 {
        position: usize,
    },
    /// A bound checksum was surfaced (base58check / bech32 / CashAddr / LEI) but
    /// did not verify. The variant identifies which scheme's checksum
    /// failed; the input is rejected rather than rendered with a bad checksum.
    Base58Check,
    Bech32Checksum,
    CashAddrChecksum,
    LeiChecksum,
}

impl From<ParseError> for RenderError {
    fn from(e: ParseError) -> Self {
        match e {
            ParseError::Eip55 { position } => RenderError::Eip55 { position },
            ParseError::Base58Check => RenderError::Base58Check,
            ParseError::Bech32Checksum => RenderError::Bech32Checksum,
            ParseError::CashAddrChecksum => RenderError::CashAddrChecksum,
            ParseError::LeiChecksum => RenderError::LeiChecksum,
        }
    }
}

impl std::fmt::Display for RenderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RenderError::Note(msg) => write!(f, "{msg}"),
            RenderError::InputTooLong => write!(f, "input too long"),
            RenderError::FontSizeRange => write!(f, "font size out of range"),
            RenderError::AspectRatioRange => write!(f, "aspect ratio out of range"),
            RenderError::NoTokens => write!(f, "no tokens"),
            RenderError::Eip55 { position } => {
                write!(f, "EIP-55 checksum mismatch at position {position}")
            }
            RenderError::Base58Check => write!(f, "base58check checksum mismatch"),
            RenderError::Bech32Checksum => write!(f, "bech32 checksum mismatch"),
            RenderError::CashAddrChecksum => write!(f, "CashAddr checksum mismatch"),
            RenderError::LeiChecksum => write!(f, "LEI MOD 97-10 checksum mismatch"),
        }
    }
}

impl std::error::Error for RenderError {}

fn sanitize_note(note: Option<&str>) -> Result<Option<String>, RenderError> {
    match note {
        None => Ok(None),
        Some("") => Ok(None),
        Some(n) => {
            // Length first, then charset (matches the reference order so the
            // surfaced error catalog is identical across implementations).
            if n.chars().count() > NOTE_MAX_LEN {
                return Err(RenderError::Note(format!(
                    "note must be at most {} characters (got {})",
                    NOTE_MAX_LEN,
                    n.chars().count()
                )));
            }
            // Printable ASCII only (U+0020 space through U+007E tilde). This
            // excludes all control/format characters, bidi, zero-width and
            // combining marks, and every non-ASCII confusable by construction —
            // the whole Unicode-spoofing surface is gone. The note is still
            // XML-escaped on output, so injection is handled regardless.
            if !n.chars().all(|c| ('\u{20}'..='\u{7e}').contains(&c)) {
                return Err(RenderError::Note(
                    "note must be printable ASCII (U+0020-U+007E); no control or \
                     non-ASCII characters"
                        .into(),
                ));
            }
            Ok(Some(n.to_string()))
        }
    }
}

// ---- tiny XML helpers ----
fn esc_attr(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
}
fn esc_text(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}
/// Serialize a coordinate per the spec's numeric-serialization rule: a finite
/// plain decimal, never exponential, in the compact form (<=3 fractional
/// digits, no trailing zeros, integers without a decimal point, -0 as 0). The
/// rounding mode is unconstrained by the spec; Rust's `{:.3}` rounds half-to-
/// even, and the checker's 0.05 px tolerance absorbs cross-impl rounding diffs.
fn n(x: f64) -> String {
    if !x.is_finite() {
        return "0".to_string(); // coordinates are always finite; defensive
    }
    let mut s = format!("{:.3}", x);
    if s.contains('.') {
        s = s.trim_end_matches('0').trim_end_matches('.').to_string();
    }
    if s.is_empty() || s == "-0" {
        s = "0".to_string();
    }
    s
}

/// Build the eight structured-characterization `data-*` attributes for the root
/// `<svg>`. Order + form mirror the reference exactly:
/// `data-encoding data-scheme data-role data-size-basis data-entropy-type
/// data-size-bits data-qualifiers data-parts`. `scheme`/`role` emit the EMPTY
/// string when null; `qualifiers`/`parts` are compact XML-escaped JSON. These
/// attributes carry no ink (closed profile permits extra data-*), so the raster
/// is unaffected.
fn characterization_attrs(c: &crate::characterize::Characterization) -> String {
    format!(
        " data-encoding=\"{enc}\" data-scheme=\"{scheme}\" data-role=\"{role}\" \
         data-size-basis=\"{basis}\" data-entropy-type=\"{etype}\" \
         data-size-bits=\"{bits}\" data-qualifiers=\"{quals}\" data-parts=\"{parts}\"",
        enc = esc_attr(&c.encoding),
        scheme = esc_attr(c.scheme.as_deref().unwrap_or("")),
        role = esc_attr(c.role.unwrap_or("")),
        basis = c.size_basis,
        etype = esc_attr(&c.entropy_type),
        bits = c.size_bits,
        quals = esc_attr(&c.qualifiers.to_json()),
        parts = esc_attr(&c.parts_json()),
    )
}

/// Render entropy as an entviz SVG string.
pub fn render(
    entropy_text: &str,
    target_ar: f64,
    font_size_pt: f64,
    note: Option<&str>,
) -> Result<String, RenderError> {
    let note = sanitize_note(note)?;
    if entropy_text.chars().count() > MAX_INPUT_CHARS {
        return Err(RenderError::InputTooLong);
    }
    if !(6.0..=30.0).contains(&font_size_pt) {
        return Err(RenderError::FontSizeRange);
    }
    if !(0.01..=100.0).contains(&target_ar) {
        return Err(RenderError::AspectRatioRange);
    }

    let raw_input = entropy_text.trim().to_string();
    // Structured entropy characterization. Reporting-only: emitted as
    // data-* attributes on the root <svg>; it feeds no pixel, no fingerprint, and
    // (critically) size_bits is NOT the >512-bit truncation basis — truncation
    // stays keyed off the tokenizer byte-length test below.
    let characterization = crate::characterize::characterize(&raw_input)?;
    let parsed = entropy::parse(&raw_input)?;

    // The visible label is a projection of the characterization
    // (render_label), so the parser's `type_name` no longer feeds the label and
    // is not retained here. `prefix`/`suffix`/`prefix_semantic` still drive the
    // fingerprint-fold and the bottom-strip suffix.
    let (core, alphabet, prefix, suffix, prefix_semantic);
    match parsed {
        None => {
            // txt -> b64url fallback (URL-safe base64, no padding).
            core = b64url_encode(raw_input.as_bytes());
            alphabet = BASE64URL;
            prefix = None;
            suffix = None;
            prefix_semantic = false;
        }
        Some(p) => {
            core = p.core;
            alphabet = p.alphabet;
            prefix = p.prefix;
            suffix = p.suffix;
            prefix_semantic = p.prefix_semantic;
        }
    }

    let (tokens, is_truncated) = tokenize_entropy(&core, &alphabet);
    if tokens.is_empty() {
        return Err(RenderError::NoTokens);
    }
    let truncated_bytes: Option<usize> = if is_truncated {
        Some(raw_input.len())
    } else {
        None
    };
    let token_count = tokens.len();

    let fingerprint_core = match (&prefix, prefix_semantic) {
        (Some(p), true) => format!("{p}{core}"),
        _ => core.clone(),
    };

    let primary = compute_fingerprint(&fingerprint_core);
    let ftoks_all = tokenize_fingerprint(&primary);
    let used_ftoks: Vec<Token> = ftoks_all.into_iter().take(token_count).collect();

    let grid = choose_grid(if is_truncated { 22 } else { token_count }, target_ar);
    let median_ftok = median_token(&used_ftoks);
    let quartile_ftoks = quartile_tokens(&used_ftoks);
    let style = select_visual_style(median_ftok.as_ref().expect("non-empty ftoks"));

    let cell_indices = assign_cell_indices(&tokens, &grid, &median_ftok, &used_ftoks);

    // --- geometry ---
    let font_px = font_size_pt * DPI / 72.0;
    let nucleus_w = font_px * 3.0;
    let nucleus_h = font_px * 1.25;
    let box_w = nucleus_w / 8.0;
    let box_h = nucleus_h / 2.0;
    let cell_w = nucleus_w + 2.0 * box_w;
    let cell_h = nucleus_h + 2.0 * box_h;
    let gm = box_h / 2.0;
    let bar_w = 2.0 * box_h;
    let grid_w = cell_w * grid.cols as f64;
    let grid_h = cell_h * grid.rows as f64;

    let inner_w = 1.0 + bar_w + 1.0 + gm + grid_w + gm + 1.0;
    let has_bottom_label = suffix.is_some() || note.is_some();
    let bottom_region = if has_bottom_label { nucleus_h + gm } else { gm };
    let inner_h = 1.0 + gm + nucleus_h + grid_h + bottom_region + 1.0;
    let bounding_w = inner_w + 2.0 * MARGIN;
    let bounding_h = inner_h + 2.0 * MARGIN;

    let grid_left = MARGIN + 1.0 + bar_w + 1.0 + gm;
    let grid_top = MARGIN + 1.0 + gm + nucleus_h;
    let grid_right = grid_left + grid_w;
    let grid_bottom = grid_top + grid_h;

    let cell_count = grid.cols * grid.rows;
    let used_cells: std::collections::HashSet<usize> = cell_indices.iter().copied().collect();

    // --- cell text sizes (keyed on the input alphabet, applied to every
    // cell of it including a short final token; the Crockford middle cells
    // are sized from their own 5-char alphabet below) ---
    let cell_text_pt = if alphabet.bits_per_char == 4 {
        (font_size_pt * 0.75).round_ties_even()
    } else {
        font_size_pt
    };
    let cell_text_px = cell_text_pt * DPI / 72.0;
    let label_text_px = (font_size_pt * 0.75).round_ties_even() * DPI / 72.0;
    let fp_middle_text_px = (font_size_pt * 0.80).round_ties_even() * DPI / 72.0;

    // --- fingerprint-edge cells ---
    let mut fp_edge_cells: std::collections::HashSet<usize> = std::collections::HashSet::new();
    if used_cells.contains(&0) {
        fp_edge_cells.insert(0);
    }
    for q in quartile_ftoks.iter().take(2).flatten() {
        fp_edge_cells.insert(cell_indices[q.index]);
    }

    // --- nucleus bg per token ---
    // token_cells: (token, ftok, ci, nucleus_bg)
    let mut token_cells: Vec<(&Token, &Token, usize, String)> = Vec::with_capacity(token_count);
    for token in &tokens {
        let ci = cell_indices[token.index];
        let nucleus_bg = if is_truncated && (8..=11).contains(&token.index) {
            style.bg_color.clone()
        } else {
            nucleus_colors(token.quant).0
        };
        token_cells.push((token, &used_ftoks[token.index], ci, nucleus_bg));
    }

    // ===================== build SVG =====================
    let mut s = String::with_capacity(8192);
    s.push_str(&format!(
        // font-family is an inherited SVG presentation property: set the
        // monospace chain ONCE here so every descendant <text> inherits it,
        // and each <text> carries only a compact font-size attribute (not the
        // full per-text `style="font-family:...; font-size:Npx;"`). Mirrors the
        // Python anchor's hoist; checker accepts either form.
        "<svg width=\"{w}\" height=\"{h}\" viewBox=\"0 0 {w} {h}\" xmlns=\"http://www.w3.org/2000/svg\" \
         font-family=\"{ff}\" \
         data-entviz-version=\"{ev}\" data-entviz-lib=\"{lib}\" data-input-bytes=\"{ib}\" \
         data-cols=\"{c}\" data-rows=\"{r}\"{trunc}{chr}>",
        ff = esc_attr(MONOSPACE_FONT_FAMILY),
        ev = crate::SPEC_VERSION,
        lib = env!("CARGO_PKG_VERSION"),
        w = n(bounding_w),
        h = n(bounding_h),
        ib = raw_input.len(),
        c = grid.cols,
        r = grid.rows,
        trunc = if is_truncated { " data-truncated=\"true\"" } else { "" },
        chr = characterization_attrs(&characterization),
    ));

    // defs + clipPath
    let digest_hex: String = primary[..8].iter().map(|b| format!("{:02x}", b)).collect();
    let clip_id = format!("grid-clip-{}-{}x{}", digest_hex, grid.cols, grid.rows);
    s.push_str(&format!(
        "<defs><clipPath id=\"{cid}\"><rect x=\"{x}\" y=\"{y}\" width=\"{w}\" height=\"{h}\"/></clipPath></defs>",
        cid = esc_attr(&clip_id),
        x = n(grid_left),
        y = n(grid_top),
        w = n(grid_w),
        h = n(grid_h),
    ));

    // bounding white background — fill only the inner field, leaving the
    // MARGIN quiet ring transparent (issue #31).
    s.push_str(&format!(
        "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"#ffffff\"/>",
        n(MARGIN),
        n(MARGIN),
        n(bounding_w - 2.0 * MARGIN),
        n(bounding_h - 2.0 * MARGIN)
    ));

    // grid channel
    s.push_str("<g data-channel=\"grid\">");
    s.push_str(&format!(
        "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"{}\"/>",
        n(grid_left),
        n(grid_top),
        n(grid_w),
        n(grid_h),
        esc_attr(&style.bg_color)
    ));

    // Layer 1: surround edges. A filled cell's 24-bit surround pattern is
    // emitted as ONE <path> (one subpath per set box) instead of one <rect> per
    // box. The bit pattern + edge color are DECLARED on the cell group below
    // (data-surround-bits / data-edge-color), so a checker recovers the channel
    // from the attribute, not the box geometry; this path is purely pixels. The
    // path MUST stay in this surround layer (painted before the cell groups and
    // the ellipse overlay) so paint order is preserved (the overlay composites
    // over the boxes exactly as before).
    let mut surround_by_cell: std::collections::HashMap<usize, (u32, String)> =
        std::collections::HashMap::new();
    s.push_str("<g>");
    for &(_token, ftok, ci, ref nucleus_bg) in &token_cells {
        let edge_color = if fp_edge_cells.contains(&ci) {
            style.edge_colors[(ftok.quant & 0b11) as usize].clone()
        } else {
            closest_palette_color(nucleus_bg, &edge_color_refs(&style)).to_string()
        };
        let col = ci % grid.cols;
        let row = ci / grid.cols;
        let cell_left = grid_left + col as f64 * cell_w;
        let cell_top = grid_top + row as f64 * cell_h;
        let mut bits = 0u32;
        let mut d = String::new();
        for i in 0..24u32 {
            if (ftok.quant >> i) & 1 == 0 {
                continue;
            }
            bits |= 1 << i;
            let (ox, oy) = box_origin(i, cell_left, cell_top, box_w, box_h);
            d.push_str(&format!(
                "M{} {}h{}v{}h-{}z",
                n(ox),
                n(oy),
                n(box_w),
                n(box_h),
                n(box_w)
            ));
        }
        if !d.is_empty() {
            s.push_str(&format!(
                "<path fill=\"{}\" d=\"{}\"/>",
                esc_attr(&edge_color),
                d
            ));
        }
        surround_by_cell.insert(ci, (bits, edge_color));
    }
    s.push_str("</g>");

    // Layer 2: ellipse overlay (appended inside grid channel)
    draw_ellipse_overlay(
        &mut s,
        &primary,
        &grid,
        grid_left,
        grid_top,
        grid_w,
        grid_h,
        cell_w,
        cell_h,
        &style.bg_color,
        &clip_id,
    );

    // --- min/max ftok cells for the blank map ---
    let mut min_cell = (u32::MAX, 0usize);
    let mut max_cell = (0u32, 0usize);
    for token in &tokens {
        let q = used_ftoks[token.index].quant;
        let ci = cell_indices[token.index];
        if q < min_cell.0 || (q == min_cell.0 && ci > min_cell.1) {
            min_cell = (q, ci);
        }
        if q > max_cell.0 || (q == max_cell.0 && ci > max_cell.1) {
            max_cell = (q, ci);
        }
    }
    let min_cell_idx = min_cell.1;
    let max_cell_idx = max_cell.1;

    // --- blanks + fills ---
    let blank_indices: Vec<usize> = (0..cell_count)
        .filter(|ci| !used_cells.contains(ci))
        .collect();
    let map_cell_idx = blank_indices.iter().copied().min();
    let sole_blank = blank_indices.len() == 1;
    let map_fill = if style.bg_color == "#ffffff" {
        "#e7be00"
    } else {
        "#ffffff"
    };
    let mut blank_fill_color: std::collections::HashMap<usize, String> =
        std::collections::HashMap::new();
    let mut j = 0usize;
    for &bi in &blank_indices {
        if Some(bi) != map_cell_idx || sole_blank {
            let color = style.edge_colors[(primary[32 + j] & 0b11) as usize].clone();
            blank_fill_color.insert(bi, color);
            j += 1;
        }
    }

    // --- quartile marks per cell ---
    let token_by_index: std::collections::HashMap<usize, &Token> =
        tokens.iter().map(|t| (t.index, t)).collect();
    let mut quartile_of_cell: std::collections::HashMap<usize, (usize, String)> =
        std::collections::HashMap::new();
    for (q_idx, q_ftok) in quartile_ftoks.iter().enumerate() {
        if let Some(q) = q_ftok {
            let ci = cell_indices[q.index];
            if let Some(token) = token_by_index.get(&q.index) {
                let fg = nucleus_colors(token.quant).1;
                quartile_of_cell.insert(ci, (q_idx, fg));
            }
        }
    }

    // fingerprint cells (token indices 8..11) for tagging
    let fingerprint_cells: std::collections::HashSet<usize> = if is_truncated {
        (8..12).map(|t| cell_indices[t]).collect()
    } else {
        std::collections::HashSet::new()
    };

    // Layer 3+: per-cell groups in cell-index order
    s.push_str("<g>");
    let fp_border = if style.bg_color == "#ffffff" {
        "#e7be00"
    } else {
        "#ffffff"
    };
    let corner_radius = nucleus_h / 2.0;
    for ci in 0..cell_count {
        let col = ci % grid.cols;
        let row = ci / grid.cols;
        let mut attrs = format!(
            " data-channel=\"cell\" data-cell-index=\"{}\" data-cell-row=\"{}\" data-cell-col=\"{}\"",
            ci, row, col
        );
        let is_blank = !used_cells.contains(&ci);
        if is_blank {
            attrs.push_str(" data-cell-blank=\"true\"");
        }
        if fingerprint_cells.contains(&ci) {
            attrs.push_str(" data-cell-fingerprint=\"true\"");
        }
        let is_map = is_blank && Some(ci) == map_cell_idx;
        if is_map {
            attrs.push_str(" data-cell-blank-map=\"true\"");
        }
        if let Some((q_idx, _)) = quartile_of_cell.get(&ci) {
            attrs.push_str(&format!(" data-cell-quartile=\"{}\"", q_idx + 1));
        }
        // A filled cell declares its surround channel here (hex bit pattern
        // + edge color); the boxes themselves were drawn as a path in the
        // surround layer above. data-edge-color is omitted when no box is set
        // (edge color is then undefined, matching the render model).
        if let Some((bits, edge_color)) = surround_by_cell.get(&ci) {
            attrs.push_str(&format!(" data-surround-bits=\"0x{:x}\"", bits));
            if *bits != 0 {
                attrs.push_str(&format!(" data-edge-color=\"{}\"", esc_attr(edge_color)));
            }
        }
        s.push_str(&format!("<g{}>", attrs));

        if is_blank {
            let nx = grid_left + col as f64 * cell_w + box_w;
            let ny = grid_top + row as f64 * cell_h + box_h;
            let blank_fill: String = if is_map && !sole_blank {
                map_fill.to_string()
            } else {
                blank_fill_color.get(&ci).cloned().unwrap()
            };
            s.push_str(&format!(
                "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" rx=\"{}\" ry=\"{}\" fill=\"{}\" stroke=\"#000000\" stroke-width=\"1\"/>",
                n(nx),
                n(ny),
                n(nucleus_w),
                n(nucleus_h),
                n(corner_radius),
                n(corner_radius),
                esc_attr(&blank_fill),
            ));
            if is_map {
                let sub_w = nucleus_w / grid.cols as f64;
                let sub_h = nucleus_h / grid.rows as f64;
                let dot_r = nucleus_h / 8.0 + font_px / 16.0;
                let (max_cx, max_cy) = sub_center(max_cell_idx, nx, ny, &grid, sub_w, sub_h);
                let (min_cx, min_cy) = sub_center(min_cell_idx, nx, ny, &grid, sub_w, sub_h);
                let (max_row, max_col) = (max_cell_idx / grid.cols, max_cell_idx % grid.cols);
                let (min_row, min_col) = (min_cell_idx / grid.cols, min_cell_idx % grid.cols);
                let plus_arm = dot_r * 1.2;
                let plus_w = (dot_r * 0.55).max(1.0);
                let (min_color, max_color) = if sole_blank {
                    let f = blank_fill_color.get(&map_cell_idx.unwrap()).unwrap();
                    let quant = u32::from_str_radix(&f[1..3], 16).unwrap()
                        | (u32::from_str_radix(&f[3..5], 16).unwrap() << 8)
                        | (u32::from_str_radix(&f[5..7], 16).unwrap() << 16);
                    let mc = nucleus_colors(quant).1;
                    (mc.clone(), mc)
                } else {
                    ("#1d4ed8".to_string(), "#d62828".to_string())
                };
                s.push_str(&format!(
                    "<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"{}\" data-blank-map-min=\"{},{}\"/>",
                    n(min_cx),
                    n(min_cy),
                    n(dot_r),
                    esc_attr(&min_color),
                    min_row,
                    min_col,
                ));
                s.push_str(&format!(
                    "<path d=\"M {},{} H {} M {},{} V {}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{}\" stroke-linecap=\"butt\" data-blank-map-max=\"{},{}\"/>",
                    n(max_cx - plus_arm),
                    n(max_cy),
                    n(max_cx + plus_arm),
                    n(max_cx),
                    n(max_cy - plus_arm),
                    n(max_cy + plus_arm),
                    esc_attr(&max_color),
                    n(plus_w),
                    max_row,
                    max_col,
                ));
            }
        } else {
            // filled cell: nucleus rect, optional border, text
            let (token, _ftok, _ci, nucleus_bg) = token_cells.iter().find(|tc| tc.2 == ci).unwrap();
            let is_fp_middle = is_truncated && (8..=11).contains(&token.index);
            let (bg_color, fg_color) = {
                let r = u32::from_str_radix(&nucleus_bg[1..3], 16).unwrap();
                let g = u32::from_str_radix(&nucleus_bg[3..5], 16).unwrap();
                let b = u32::from_str_radix(&nucleus_bg[5..7], 16).unwrap();
                nucleus_colors(r | (g << 8) | (b << 16))
            };
            let nx = grid_left + col as f64 * cell_w + box_w;
            let ny = grid_top + row as f64 * cell_h + box_h;
            s.push_str(&format!(
                "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"{}\"/>",
                n(nx),
                n(ny),
                n(nucleus_w),
                n(nucleus_h),
                esc_attr(&bg_color)
            ));
            if is_fp_middle {
                s.push_str(&format!(
                    "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"1\"/>",
                    n(nx + 0.5),
                    n(ny + 0.5),
                    n(nucleus_w - 1.0),
                    n(nucleus_h - 1.0),
                    esc_attr(fp_border)
                ));
            }
            let text_px = if is_fp_middle {
                fp_middle_text_px
            } else {
                cell_text_px
            };
            let cx = nx + nucleus_w / 2.0;
            let cy = ny + nucleus_h / 2.0;
            s.push_str(&format!(
                "<text x=\"{}\" y=\"{}\" fill=\"{}\" font-size=\"{}\" text-anchor=\"middle\" dominant-baseline=\"central\">{}</text>",
                n(cx),
                n(cy),
                esc_attr(&fg_color),
                n(text_px),
                esc_text(&token.text)
            ));
            // quartile mark
            if let Some((q_idx, fg)) = quartile_of_cell.get(&ci) {
                let poly = quartile_polygon(*q_idx, nx, ny, nucleus_w, nucleus_h);
                s.push_str(&format!(
                    "<polygon points=\"{}\" fill=\"{}\"/>",
                    poly,
                    esc_attr(fg)
                ));
            }
        }
        s.push_str("</g>");
    }
    s.push_str("</g>"); // nuclei_g
    s.push_str("</g>"); // grid channel

    // color bar
    draw_color_bar(
        &mut s,
        &primary,
        &second_digest(&core),
        &style,
        bar_w,
        bounding_h,
        cell_text_px,
    );

    // labels — the visible top/bottom strips are a pure projection of the
    // entropy characterization through one grammar (render_label), NOT the
    // old per-parser type_name/prefix fusing. `characterization` is the same
    // record already emitted as data-* attributes above; the styled `+hash`
    // marker and the note tspan are applied structurally in draw_label_strips
    // from the truncated/note flags. See docs/spec.md -> "Label strips".
    //
    // The top strip carries a trailing slot echoing the stripped front
    // prefix (0x, bc1, cosmos1, the SSH header, …). The prefix is the only
    // elastic element and is truncated to the character budget the grid leaves
    // on the label line: line_chars = floor(grid_width / (label_px *
    // LABEL_ADVANCE_EM)). LABEL_ADVANCE_EM is a fixed spec constant (NOT the
    // renderer's real font metric) so every implementation truncates
    // identically and the Tier-A label string is reproducible.
    let label_line_chars = ((grid_right - grid_left) / (label_text_px * LABEL_ADVANCE_EM)) as usize;
    let (top_text, _bottom_text) = crate::characterize::render_label(
        &characterization,
        is_truncated,
        suffix.as_deref(),
        note.as_deref(),
        Some(label_line_chars),
    );
    draw_label_strips(
        &mut s,
        grid_left,
        grid_right,
        grid_top,
        grid_bottom,
        nucleus_h,
        &top_text,
        &suffix,
        label_text_px,
        truncated_bytes,
        &note,
    );

    // borders
    let bl = |s: &mut String, x1: f64, y1: f64, x2: f64, y2: f64| {
        s.push_str(&format!(
            "<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"#808080\" stroke-width=\"1\" shape-rendering=\"crispEdges\"/>",
            n(x1), n(y1), n(x2), n(y2)
        ));
    };
    // Frame inset by MARGIN; span endpoints MARGIN..(bounding-MARGIN) so corners
    // stay double-painted (issue #31).
    bl(
        &mut s,
        MARGIN,
        MARGIN + 0.5,
        bounding_w - MARGIN,
        MARGIN + 0.5,
    );
    bl(
        &mut s,
        bounding_w - MARGIN - 0.5,
        MARGIN,
        bounding_w - MARGIN - 0.5,
        bounding_h - MARGIN,
    );
    bl(
        &mut s,
        MARGIN,
        bounding_h - MARGIN - 0.5,
        bounding_w - MARGIN,
        bounding_h - MARGIN - 0.5,
    );
    bl(
        &mut s,
        MARGIN + 0.5,
        MARGIN,
        MARGIN + 0.5,
        bounding_h - MARGIN,
    );
    bl(
        &mut s,
        MARGIN + 1.0 + bar_w + 0.5,
        MARGIN,
        MARGIN + 1.0 + bar_w + 0.5,
        bounding_h - MARGIN,
    );

    s.push_str("</svg>");
    Ok(s)
}

fn edge_color_refs(style: &VisualStyle) -> Vec<&str> {
    style.edge_colors.iter().map(|s| s.as_str()).collect()
}

fn box_origin(i: u32, cell_left: f64, cell_top: f64, bw: f64, bh: f64) -> (f64, f64) {
    if i < 10 {
        (cell_left + i as f64 * bw, cell_top)
    } else if i < 12 {
        (cell_left + 9.0 * bw, cell_top + bh + (i - 10) as f64 * bh)
    } else if i < 22 {
        (cell_left + (21 - i) as f64 * bw, cell_top + 3.0 * bh)
    } else {
        (cell_left, cell_top + bh + (23 - i) as f64 * bh)
    }
}

fn sub_center(
    cell_idx: usize,
    nx: f64,
    ny: f64,
    grid: &Grid,
    sub_w: f64,
    sub_h: f64,
) -> (f64, f64) {
    (
        nx + (cell_idx % grid.cols) as f64 * sub_w + 0.5 * sub_w,
        ny + (cell_idx / grid.cols) as f64 * sub_h + 0.5 * sub_h,
    )
}

fn quartile_polygon(q_idx: usize, nx: f64, ny: f64, w: f64, h: f64) -> String {
    let leg = h / 2.0;
    let (left, top, right, bottom) = (nx, ny, nx + w, ny + h);
    let pts: [(f64, f64); 3] = match q_idx {
        0 => [(left, top), (left + leg, top), (left, top + leg)],
        1 => [(right, top), (right - leg, top), (right, top + leg)],
        2 => [
            (right, bottom),
            (right, bottom - leg),
            (right - leg, bottom),
        ],
        _ => [(left, bottom), (left, bottom - leg), (left + leg, bottom)],
    };
    pts.iter()
        .map(|p| format!("{},{}", n(p.0), n(p.1)))
        .collect::<Vec<_>>()
        .join(" ")
}

// --- ellipse overlay ---
#[allow(clippy::too_many_arguments)]
fn draw_ellipse_overlay(
    s: &mut String,
    digest: &[u8; 64],
    grid: &Grid,
    grid_left: f64,
    grid_top: f64,
    grid_w: f64,
    grid_h: f64,
    cell_w: f64,
    cell_h: f64,
    bg_color: &str,
    clip_id: &str,
) {
    let interior_count = (grid.cols.saturating_sub(1)) * (grid.rows.saturating_sub(1));
    let points: Vec<(f64, f64)> = if interior_count >= 6 {
        let mut p = Vec::new();
        for r in 1..grid.rows {
            for c in 1..grid.cols {
                p.push((grid_left + c as f64 * cell_w, grid_top + r as f64 * cell_h));
            }
        }
        p
    } else {
        let mut p = Vec::new();
        for c in 0..=grid.cols {
            p.push((grid_left + c as f64 * cell_w, grid_top));
        }
        for r in 1..grid.rows {
            p.push((grid_left, grid_top + r as f64 * cell_h));
            p.push((
                grid_left + grid.cols as f64 * cell_w,
                grid_top + r as f64 * cell_h,
            ));
        }
        for c in 0..=grid.cols {
            p.push((
                grid_left + c as f64 * cell_w,
                grid_top + grid.rows as f64 * cell_h,
            ));
        }
        p
    };
    if points.is_empty() {
        return;
    }
    let anchor = points[(digest[60] as usize) % points.len()];
    let grid_right = grid_left + grid_w;
    let grid_bottom = grid_top + grid_h;
    let corners = [
        (grid_left, grid_top),
        (grid_right, grid_top),
        (grid_left, grid_bottom),
        (grid_right, grid_bottom),
    ];
    let d_far = corners
        .iter()
        .map(|c| ((c.0 - anchor.0).powi(2) + (c.1 - anchor.1).powi(2)).sqrt())
        .fold(0.0_f64, f64::max);
    let r_min = 0.22 * d_far;
    let r_max = 0.58 * d_far;
    if r_max <= r_min {
        return;
    }
    let rx = r_min + ((digest[61] % 16) as f64 / 15.0) * (r_max - r_min);
    let ry = r_min + ((digest[62] % 16) as f64 / 15.0) * (r_max - r_min);
    let rotation = ((digest[63] % 16) as f64 / 15.0) * 180.0;
    let (fill, fill_op, edge_op) = overlay_for_bg(bg_color);
    let stroke_w = cell_h / 20.0;
    s.push_str(&format!(
        "<g clip-path=\"url(#{cid})\" data-channel=\"ellipse\" data-ellipse-anchor-x=\"{ax}\" data-ellipse-anchor-y=\"{ay}\" data-ellipse-rx=\"{rx}\" data-ellipse-ry=\"{ry}\" data-ellipse-rotation-deg=\"{rot}\">",
        cid = esc_attr(clip_id),
        ax = n(anchor.0),
        ay = n(anchor.1),
        rx = n(rx),
        ry = n(ry),
        rot = n(rotation),
    ));
    s.push_str(&format!(
        "<ellipse cx=\"{cx}\" cy=\"{cy}\" rx=\"{rx}\" ry=\"{ry}\" transform=\"rotate({rot} {cx} {cy})\" fill=\"{fill}\" stroke=\"{fill}\" fill-opacity=\"{fo}\" stroke-opacity=\"{eo}\" stroke-width=\"{sw}\"/>",
        cx = n(anchor.0),
        cy = n(anchor.1),
        rx = n(rx),
        ry = n(ry),
        rot = n(rotation),
        fill = fill,
        fo = n(fill_op),
        eo = n(edge_op),
        sw = n(stroke_w),
    ));
    s.push_str("</g>");
}

fn overlay_for_bg(bg: &str) -> (&'static str, f64, f64) {
    match bg {
        "#ffffff" => ("#000000", 0.20, 0.30),
        "#e7be00" => ("#000000", 0.20, 0.30),
        "#ff3f2f" => ("#000000", 0.25, 0.35),
        "#2f3fbf" => ("#ffffff", 0.35, 0.45),
        _ => ("#000000", 0.20, 0.30),
    }
}

// --- color bar ---
fn first_appearance(digest: &[u8; 64]) -> [usize; 4] {
    let mut first = [usize::MAX; 4];
    let mut idx = 0;
    for &byte in digest.iter() {
        for shift in [0u32, 2, 4, 6] {
            let p = ((byte >> shift) & 3) as usize;
            if first[p] == usize::MAX {
                first[p] = idx;
            }
            idx += 1;
        }
    }
    let mut order = [0usize, 1, 2, 3];
    order.sort_by_key(|&p| (first[p], p));
    order
}

fn draw_color_bar(
    s: &mut String,
    digest: &[u8; 64],
    second: &[u8; 64],
    style: &VisualStyle,
    bar_w: f64,
    bounding_h: f64,
    cell_text_px: f64,
) {
    let bar_left = MARGIN + 1.0;
    let bar_top = MARGIN + 1.0;
    let bar_height = bounding_h - 2.0 * MARGIN - 2.0;
    let counts = two_bit_counts(digest);
    // usage[edge_colors[i]] = counts[i]
    let edge = &style.edge_colors;
    // first-appearance order of patterns -> colors
    let order = first_appearance(digest);
    let order_pos: std::collections::HashMap<&str, usize> = order
        .iter()
        .enumerate()
        .map(|(i, &p)| (edge[p].as_str(), i))
        .collect();
    let color_order: std::collections::HashMap<&str, usize> = edge
        .iter()
        .enumerate()
        .map(|(i, c)| (c.as_str(), i))
        .collect();

    let mut used: Vec<(String, usize)> = (0..4)
        .filter(|&i| counts[i] > 0)
        .map(|i| (edge[i].clone(), counts[i]))
        .collect();
    if used.is_empty() {
        return;
    }
    used.sort_by_key(|(c, _)| {
        (
            *order_pos.get(c.as_str()).unwrap_or(&4),
            *color_order.get(c.as_str()).unwrap_or(&4),
        )
    });
    let total: f64 = used.iter().map(|(_, nn)| (*nn as f64).powi(4)).sum();

    s.push_str("<g data-channel=\"color-bar\">");
    let bar_cx = bar_left + bar_w / 2.0;
    let mut y = bar_top;
    let last = used.len() - 1;
    for (i, (color, nn)) in used.iter().enumerate() {
        let h = if i == last {
            (bar_top + bar_height) - y
        } else {
            bar_height * (*nn as f64).powi(4) / total
        };
        let letter = band_letter(color);
        let band_attrs = match letter {
            Some(l) => format!(
                " data-color-bar-rank=\"{}\" data-color-bar-band=\"{}\"",
                i, l
            ),
            None => format!(" data-color-bar-rank=\"{}\"", i),
        };
        s.push_str(&format!("<g{}>", band_attrs));
        s.push_str(&format!(
            "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"{}\"/>",
            n(bar_left),
            n(y),
            n(bar_w),
            n(h),
            esc_attr(color)
        ));
        if let Some(l) = letter {
            let r = u32::from_str_radix(&color[1..3], 16).unwrap();
            let g = u32::from_str_radix(&color[3..5], 16).unwrap();
            let b = u32::from_str_radix(&color[5..7], 16).unwrap();
            let fg = nucleus_colors(r | (g << 8) | (b << 16)).1;
            let font_size = cell_text_px;
            // PSY-F7 (accepted design choice): the letter is bottom-anchored
            // within its band. On a very short band (shorter than ~0.78*font_size)
            // the top of the glyph can bleed upward past the band's top edge.
            // This is intentional and deterministic, and matches the Python
            // reference: the band COLOR is the primary discriminator and the
            // letter is a redundant secondary cue, so the bleed is cosmetic.
            let baseline_y = (y + h) - 0.22 * font_size;
            s.push_str(&format!(
                "<text x=\"{}\" y=\"{}\" fill=\"{}\" font-size=\"{}\" text-anchor=\"middle\" data-color-bar-letter=\"true\">{}</text>",
                n(bar_cx),
                n(baseline_y),
                esc_attr(&fg),
                n(font_size),
                esc_text(&l.to_lowercase())
            ));
        }
        s.push_str("</g>");
        y += h;
    }

    // markers
    let k = ((bar_height / 12.0).floor() as i64).clamp(4, 16) as usize;
    let slot_h = bar_height / k as f64;
    let radius = bar_w * 0.17;
    let inset = bar_w * 0.06;
    let left_slot = (second[12] as usize) % k;
    let right_slot = (second[13] as usize) % k;
    for (side, slot) in [("left", left_slot), ("right", right_slot)] {
        let cy = bar_top + (slot as f64 + 0.5) * slot_h;
        let cx = if side == "left" {
            bar_left + inset + radius
        } else {
            bar_left + bar_w - inset - radius
        };
        s.push_str(&format!(
            "<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"#ffffff\" stroke=\"#000000\" stroke-width=\"0.75\" data-bar-marker=\"{}\"/>",
            n(cx),
            n(cy),
            n(radius),
            side
        ));
    }
    s.push_str("</g>");

    // Inject the marker/slot attributes onto the color-bar group opening tag.
    // (Done here by string replacement on the just-emitted group.)
    patch_color_bar_attrs(s, k, left_slot, right_slot);
}

/// Add `data-bar-slots` / `data-bar-marker-*` to the most recent
/// `<g data-channel="color-bar">` opening tag (they must live on the group).
fn patch_color_bar_attrs(s: &mut String, k: usize, left: usize, right: usize) {
    let needle = "<g data-channel=\"color-bar\">";
    if let Some(pos) = s.rfind(needle) {
        let replacement = format!(
            "<g data-channel=\"color-bar\" data-bar-slots=\"{}\" data-bar-marker-left=\"{}\" data-bar-marker-right=\"{}\">",
            k, left, right
        );
        s.replace_range(pos..pos + needle.len(), &replacement);
    }
}

#[allow(clippy::too_many_arguments)]
fn draw_label_strips(
    s: &mut String,
    grid_left: f64,
    grid_right: f64,
    grid_top: f64,
    grid_bottom: f64,
    nucleus_h: f64,
    top_text: &str,
    suffix: &Option<String>,
    text_px: f64,
    truncated_bytes: Option<usize>,
    note: &Option<String>,
) {
    // font-family is inherited from the root <svg>; each label <text> carries
    // only a compact font-size presentation attribute.
    let font_size_attr = format!("font-size=\"{}\"", n(text_px));
    let top_cy = grid_top - nucleus_h / 2.0;
    s.push_str("<g data-channel=\"label-top\">");
    // `top_text` is the render_label projection. When truncated it begins
    // with the loud `+hash ` marker, which is split back out here and rendered
    // bold dark-red, with the projected label following in #666.
    if truncated_bytes.is_some() {
        if let Some(rest) = top_text.strip_prefix(crate::characterize::TRUNC_MARKER) {
            s.push_str(&format!(
                "<text x=\"{}\" y=\"{}\" fill=\"#666666\" {} dominant-baseline=\"central\"><tspan fill=\"#a00000\" font-weight=\"bold\">+hash </tspan>{}</text>",
                n(grid_left),
                n(top_cy),
                font_size_attr,
                esc_text(rest),
            ));
        } else {
            s.push_str(&format!(
                "<text x=\"{}\" y=\"{}\" fill=\"#666666\" {} dominant-baseline=\"central\">{}</text>",
                n(grid_left),
                n(top_cy),
                font_size_attr,
                esc_text(top_text),
            ));
        }
    } else {
        s.push_str(&format!(
            "<text x=\"{}\" y=\"{}\" fill=\"#666666\" {} dominant-baseline=\"central\">{}</text>",
            n(grid_left),
            n(top_cy),
            font_size_attr,
            esc_text(top_text),
        ));
    }
    s.push_str("</g>");

    if suffix.is_some() || note.is_some() {
        let bottom_cy = grid_bottom + nucleus_h / 2.0;
        s.push_str("<g data-channel=\"label-bottom\">");
        s.push_str(&format!(
            "<text x=\"{}\" y=\"{}\" fill=\"#666666\" {} text-anchor=\"end\" dominant-baseline=\"central\">",
            n(grid_right),
            n(bottom_cy),
            font_size_attr,
        ));
        match (suffix, note) {
            (Some(suf), Some(nt)) => {
                s.push_str(&format!("<tspan>...{} </tspan>", esc_text(suf)));
                s.push_str(&format!(
                    "<tspan fill=\"#808080\" data-user-note=\"{}\">({})</tspan>",
                    esc_attr(nt),
                    esc_text(nt)
                ));
            }
            (Some(suf), None) => {
                s.push_str(&format!("...{}", esc_text(suf)));
            }
            (None, Some(nt)) => {
                s.push_str(&format!(
                    "<tspan fill=\"#808080\" data-user-note=\"{}\">({})</tspan>",
                    esc_attr(nt),
                    esc_text(nt)
                ));
            }
            (None, None) => {}
        }
        s.push_str("</text></g>");
    }
}

fn b64url_encode(data: &[u8]) -> String {
    use base64::Engine;
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(data)
}

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

    #[test]
    fn n_emits_compact_plain_decimals() {
        // Compact form: integers without a point, <=3 fractional digits, no
        // trailing zeros, -0 -> 0, and never exponential notation.
        assert_eq!(n(27.0), "27");
        assert_eq!(n(240.0), "240");
        assert_eq!(n(0.5), "0.5");
        assert_eq!(n(131.323_942_158_859_92), "131.324");
        assert_eq!(n(-0.0), "0");
        assert_eq!(n(-0.0004), "0"); // rounds to zero magnitude
        assert_eq!(n(-1.5), "-1.5");
        assert_eq!(n(0.000_000_1), "0"); // would be 1e-7 via Display; must not be exponential
        assert!(!n(0.000_000_1).contains('e'));
        assert!(!n(1234.5).contains('e'));
    }

    #[test]
    fn coordinates_are_compact_plain_decimals() {
        // Every numeric SVG attribute value must be a compact plain decimal
        // (<=3 fractional digits, no exponential notation). Catches any
        // coordinate that bypasses n() (the JS port had exactly such a bug in
        // an ellipse stroke-width). Attribute values are the odd segments when
        // splitting on the quote character.
        let long = "a".repeat(66); // forces a blank-cell map + ellipse overlay
        for input in [
            "0123456789abcdef0123456789abcdef",
            "550e8400-e29b-41d4-a716-446655440000",
            &long,
        ] {
            let svg = render(input, 1.0, 12.0, None).unwrap();
            for (i, token) in svg.split('"').enumerate() {
                if i % 2 == 0 {
                    continue; // tag text, not an attribute value
                }
                if token.parse::<f64>().is_ok() {
                    assert!(
                        !token.contains(['e', 'E']),
                        "exponential notation in {token:?}"
                    );
                    if let Some(frac) = token.split('.').nth(1) {
                        assert!(
                            frac.len() <= 3,
                            "more than 3 fractional digits in {token:?}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn renders_hex256() {
        let svg = render(
            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
            1.0,
            12.0,
            None,
        )
        .unwrap();
        assert!(svg.starts_with("<svg "));
        assert!(svg.contains("data-cols=\"3\""));
        assert!(svg.contains("data-rows=\"4\""));
        assert!(svg.contains("data-channel=\"color-bar\" data-bar-slots="));
        assert!(svg.ends_with("</svg>"));
    }

    #[test]
    fn surround_declared_on_cell_and_path_subpaths_match_bits() {
        // Each filled cell group declares data-surround-bits (parseable as
        // hex) and, when bits != 0, data-edge-color. The surround paths draw
        // exactly one box ('M' subpath) per set bit; summed over all cells the
        // path subpath count must equal the total popcount of declared bits.
        let svg = render(
            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
            1.0,
            12.0,
            None,
        )
        .unwrap();

        // Walk every cell group, parse its declared bits, and confirm
        // data-edge-color presence matches bits != 0.
        let mut total_bits = 0u32;
        let mut saw_cell = false;
        for chunk in svg.split("data-channel=\"cell\"").skip(1) {
            // the group's attributes run until the closing '>' of its open tag
            let tag = &chunk[..chunk.find('>').unwrap()];
            saw_cell = true;
            let bits_attr = extract_attr(tag, "data-surround-bits");
            if let Some(bits_hex) = bits_attr {
                let hex = bits_hex.trim_start_matches("0x");
                let bits = u32::from_str_radix(hex, 16).expect("hex-parseable bits");
                total_bits += bits.count_ones();
                let has_edge = extract_attr(tag, "data-edge-color").is_some();
                assert_eq!(
                    has_edge,
                    bits != 0,
                    "data-edge-color present iff bits != 0 (tag: {tag})"
                );
            }
        }
        assert!(saw_cell, "no cell groups found");
        assert!(total_bits > 0, "no surround bits set");

        // Count 'M' subpaths across every surround <path>. The surround paths
        // are the <path fill="#..." d="M..."> emitted before the cell groups;
        // the only other path (blank-map plus marker) carries data-blank-map-*.
        let mut total_subpaths = 0u32;
        for chunk in svg.split("<path ").skip(1) {
            let tag = &chunk[..chunk.find('>').unwrap()];
            if tag.contains("data-blank-map-") {
                continue;
            }
            if let Some(d) = extract_attr(tag, "d") {
                total_subpaths += d.matches('M').count() as u32;
            }
        }
        assert_eq!(
            total_subpaths, total_bits,
            "surround path subpath count must equal total popcount of declared bits"
        );
    }

    // Tiny attribute extractor for the test above (key="value" within a tag).
    fn extract_attr<'a>(tag: &'a str, key: &str) -> Option<&'a str> {
        let needle = format!("{key}=\"");
        let start = tag.find(&needle)? + needle.len();
        let end = tag[start..].find('"')? + start;
        Some(&tag[start..end])
    }

    #[test]
    fn rejects_bad_eip55() {
        assert!(matches!(
            render(
                "0x5aaeb6053F3E94C9b9A09f33669435E7Ef1BeAed",
                1.0,
                12.0,
                None
            ),
            Err(RenderError::Eip55 { .. })
        ));
    }

    #[test]
    fn bad_eip55_surfaces_first_mismatch_position() {
        // SPEC-F1: the spec MUST identify the first mismatched-case digit; the
        // position must be carried through to RenderError (not collapsed away)
        // and rendered in the Display/CLI message. This is a mixed-case address
        // whose checksum case does NOT match canonical EIP-55.
        let err = render(
            "0x5aaeb6053F3E94C9b9A09f33669435E7Ef1BeAed",
            1.0,
            12.0,
            None,
        )
        .unwrap_err();
        let position = match err {
            RenderError::Eip55 { position } => position,
            other => panic!("expected Eip55, got {other:?}"),
        };
        // Cross-check: the position is the first body index whose case differs
        // from the canonical EIP-55 case, and the Display message names it.
        let msg = err.to_string();
        assert!(
            msg.contains(&position.to_string()),
            "Display message {msg:?} must name the mismatched position {position}"
        );
        assert!(msg.to_lowercase().contains("position"));
    }

    #[test]
    fn rejects_bad_note_and_fontsize() {
        // "two words" is now VALID (printable ASCII, <=10); a tab is not.
        assert!(render("a1b2c3d4e5f6a7b8", 1.0, 12.0, Some("two words")).is_ok());
        assert!(render("a1b2c3d4e5f6a7b8", 1.0, 12.0, Some("ab\tcd")).is_err());
        assert!(render("a1b2c3d4e5f6a7b8", 1.0, 4.0, None).is_err());
        assert!(render("a1b2c3d4e5f6a7b8", 1.0, 40.0, None).is_err());
    }

    // ===================================================================
    // sanitize_note
    // ===================================================================
    #[test]
    fn sanitize_note_cases() {
        assert!(sanitize_note(None).unwrap().is_none());
        assert!(sanitize_note(Some("")).unwrap().is_none()); // empty -> None
        assert_eq!(
            sanitize_note(Some("abc123")).unwrap().as_deref(),
            Some("abc123")
        );
        // Printable ASCII now accepted: spaces and punctuation are valid.
        assert_eq!(
            sanitize_note(Some("two words")).unwrap().as_deref(),
            Some("two words")
        );
        assert_eq!(
            sanitize_note(Some("a.b_c-d!")).unwrap().as_deref(),
            Some("a.b_c-d!")
        );
        // Boundary chars U+0020 (space) and U+007E (tilde) are in range.
        assert_eq!(sanitize_note(Some(" ")).unwrap().as_deref(), Some(" "));
        assert_eq!(sanitize_note(Some("~")).unwrap().as_deref(), Some("~"));
        // Exactly 10 chars is allowed; 11 is rejected (length checked first).
        assert_eq!(
            sanitize_note(Some("0123456789")).unwrap().as_deref(),
            Some("0123456789")
        );
        assert!(matches!(
            sanitize_note(Some("toolongnote")), // 11 chars
            Err(RenderError::Note(_))
        ));
        // Control char (tab) rejected.
        assert!(matches!(
            sanitize_note(Some("ab\tcd")),
            Err(RenderError::Note(_))
        ));
        // Non-ASCII rejected (café — the é is U+00E9).
        assert!(matches!(
            sanitize_note(Some("caf\u{e9}")),
            Err(RenderError::Note(_))
        ));
        // Bidi override (U+202E) and zero-width space (U+200B) rejected.
        assert!(matches!(
            sanitize_note(Some("a\u{202e}b")),
            Err(RenderError::Note(_))
        ));
        assert!(matches!(
            sanitize_note(Some("a\u{200b}b")),
            Err(RenderError::Note(_))
        ));
    }

    #[test]
    fn note_xml_special_chars_are_escaped() {
        // < > & " are valid printable-ASCII note chars now, so they MUST be
        // XML-escaped in both the data-user-note attribute and the text node;
        // no raw "<b>" may appear in the output.
        let svg = render("a1b2c3d4e5f6a7b8", 1.0, 12.0, Some("a<b>&\"x")).unwrap();
        // Text node: < > & escaped (" stays raw — legal in XML text).
        assert!(svg.contains("(a&lt;b&gt;&amp;\"x)"));
        // Attribute: < > & " all escaped.
        assert!(svg.contains("data-user-note=\"a&lt;b&gt;&amp;&quot;x\""));
        // No raw tag leaked.
        assert!(!svg.contains("<b>"));
    }

    // ===================================================================
    // XML escaping + number formatting
    // ===================================================================
    #[test]
    fn escaping_and_number_formatting() {
        assert_eq!(esc_attr("a&b<c>d\"e"), "a&amp;b&lt;c&gt;d&quot;e");
        assert_eq!(esc_text("a&b<c>d\"e"), "a&amp;b&lt;c&gt;d\"e"); // quotes left as-is
        assert_eq!(n(3.0), "3");
        assert_eq!(n(3.5), "3.5");
    }

    #[test]
    fn b64url_encode_no_padding() {
        assert_eq!(b64url_encode(b"foobar"), "Zm9vYmFy");
        // bytes that would normally pad: no '=' present
        assert!(!b64url_encode(b"foo").contains('='));
    }

    // ===================================================================
    // Geometry helpers
    // ===================================================================
    #[test]
    fn box_origin_all_four_ranges() {
        // top row (i<10): moves right along x
        let (x, y) = box_origin(3, 100.0, 200.0, 10.0, 5.0);
        assert_eq!((x, y), (130.0, 200.0));
        // right column (10..12): fixed x, moves down
        let (x, y) = box_origin(10, 100.0, 200.0, 10.0, 5.0);
        assert_eq!((x, y), (190.0, 205.0));
        // bottom row (12..22): moves left along x at bottom
        let (x, y) = box_origin(12, 100.0, 200.0, 10.0, 5.0);
        assert_eq!((x, y), (100.0 + 9.0 * 10.0, 200.0 + 15.0));
        // left column (22..24): the else branch
        let (x, y) = box_origin(22, 100.0, 200.0, 10.0, 5.0);
        assert_eq!(x, 100.0);
        assert!(y > 200.0);
    }

    #[test]
    fn sub_center_positions() {
        let grid = Grid {
            cols: 2,
            rows: 2,
            token_count: 4,
        };
        // cell 0 -> top-left sub-cell center
        let (cx, cy) = sub_center(0, 0.0, 0.0, &grid, 10.0, 10.0);
        assert_eq!((cx, cy), (5.0, 5.0));
        // cell 3 -> bottom-right sub-cell center
        let (cx, cy) = sub_center(3, 0.0, 0.0, &grid, 10.0, 10.0);
        assert_eq!((cx, cy), (15.0, 15.0));
    }

    #[test]
    fn quartile_polygon_all_corners() {
        for q in 0..4 {
            let p = quartile_polygon(q, 0.0, 0.0, 8.0, 4.0);
            // three "x,y" points
            assert_eq!(p.split(' ').count(), 3);
        }
        // q0 anchors at the top-left corner
        assert!(quartile_polygon(0, 0.0, 0.0, 8.0, 4.0).starts_with("0,0"));
    }

    // ===================================================================
    // Color helpers
    // ===================================================================
    #[test]
    fn overlay_for_bg_all_backgrounds() {
        assert_eq!(overlay_for_bg("#ffffff"), ("#000000", 0.20, 0.30));
        assert_eq!(overlay_for_bg("#e7be00"), ("#000000", 0.20, 0.30));
        assert_eq!(overlay_for_bg("#ff3f2f"), ("#000000", 0.25, 0.35));
        assert_eq!(overlay_for_bg("#2f3fbf"), ("#ffffff", 0.35, 0.45));
        // default arm (e.g. black)
        assert_eq!(overlay_for_bg("#000000"), ("#000000", 0.20, 0.30));
    }

    #[test]
    fn band_letter_mapping() {
        assert_eq!(band_letter("#ffffff"), Some("W"));
        assert_eq!(band_letter("#e7be00"), Some("G"));
        assert_eq!(band_letter("#ff3f2f"), Some("R"));
        assert_eq!(band_letter("#2f3fbf"), Some("B"));
        assert_eq!(band_letter("#000000"), Some("K"));
        assert_eq!(band_letter("#123456"), None);
    }

    #[test]
    fn two_bit_counts_and_first_appearance() {
        let mut d = [0u8; 64];
        d[0] = 0b00_01_10_11; // one of each 2-bit pattern in byte 0
        let counts = two_bit_counts(&d);
        // remaining 63 bytes are zero -> pattern 0 dominates
        assert_eq!(counts[1], 1);
        assert_eq!(counts[2], 1);
        assert_eq!(counts[3], 1);
        assert!(counts[0] > 100);
        let order = first_appearance(&d);
        // byte 0 low-to-high: shift 0 -> pattern 11(=3), shift2 -> 10(=2),
        // shift4 -> 01(=1), shift6 -> 00(=0). So 3 appears first.
        assert_eq!(order[0], 3);
        // all four patterns present exactly once in the ordering
        let mut sorted = order;
        sorted.sort();
        assert_eq!(sorted, [0, 1, 2, 3]);
    }

    // ===================================================================
    // assign_cell_indices
    // ===================================================================
    fn tok(index: usize, text: &str, quant: u32) -> Token {
        Token {
            text: text.into(),
            index,
            quant,
        }
    }

    #[test]
    fn assign_cell_indices_identity_when_full() {
        let grid = Grid {
            cols: 2,
            rows: 2,
            token_count: 4,
        };
        let tokens = vec![
            tok(0, "a", 0),
            tok(1, "b", 0),
            tok(2, "c", 0),
            tok(3, "d", 0),
        ];
        let ci = assign_cell_indices(&tokens, &grid, &Some(tokens[0].clone()), &tokens);
        assert_eq!(ci, vec![0, 1, 2, 3]); // token_count >= cell_count
    }

    #[test]
    fn assign_cell_indices_shifts_for_sparse_grid() {
        let grid = Grid {
            cols: 3,
            rows: 2,
            token_count: 3,
        }; // 6 cells, 3 tokens -> all three shifts apply
        let tokens = vec![tok(0, "m", 0), tok(1, "a", 0), tok(2, "z", 0)];
        let median = median_token(&tokens);
        let ci = assign_cell_indices(&tokens, &grid, &median, &tokens);
        assert_eq!(ci.len(), 3);
        // every assigned cell index is in range and distinct
        assert!(ci.iter().all(|&c| c < 6));
        let set: std::collections::HashSet<_> = ci.iter().collect();
        assert_eq!(set.len(), 3);
    }

    // ===================================================================
    // render: error paths + label variants + truncation
    // ===================================================================
    #[test]
    fn render_rejects_input_too_long() {
        let huge = "a".repeat(70_000);
        assert!(matches!(
            render(&huge, 1.0, 12.0, None),
            Err(RenderError::InputTooLong)
        ));
    }

    #[test]
    fn render_rejects_aspect_ratio_out_of_range() {
        assert!(matches!(
            render("a1b2c3d4e5f6a7b8", 200.0, 12.0, None),
            Err(RenderError::AspectRatioRange)
        ));
        assert!(matches!(
            render("a1b2c3d4e5f6a7b8", 0.001, 12.0, None),
            Err(RenderError::AspectRatioRange)
        ));
    }

    #[test]
    fn render_empty_input_has_no_tokens() {
        assert!(matches!(
            render("", 1.0, 12.0, None),
            Err(RenderError::NoTokens)
        ));
    }

    #[test]
    fn render_b64url_detected_label() {
        // '-'/'_' force base64url; scheme=null projects to the encoding
        // short-name `b64url` plus a decoded SIZE. 8 chars * 6 bits = 48 bits.
        let svg = render("ABC-_DEF", 1.0, 12.0, None).unwrap();
        assert!(svg.contains(">b64url, 48-bit</text>"), "svg: {svg}");
    }

    #[test]
    fn render_b64_detected_label() {
        // '+'/'/' force plain base64 -> PRIMARY `b64`, decoded 48-bit.
        let svg = render("ABC+/DEF", 1.0, 12.0, None).unwrap();
        assert!(svg.contains(">b64, 48-bit</text>"), "svg: {svg}");
    }

    #[test]
    fn render_type_with_prefix_label() {
        // Bare 0x-prefixed short hex is scheme=null -> `hex, <bits>`, and
        // the stripped `0x` presentation prefix (parts[0].bind == "none") echoes
        // as the trailing PREFIX slot. It is short, so it is not truncated.
        let svg = render("0xabcdef12", 1.0, 12.0, None).unwrap();
        assert!(svg.contains(">hex, 32-bit, 0x</text>"), "svg: {svg}");
        assert!(!svg.contains("0x..."));
    }

    #[test]
    fn render_suffix_only_bottom_label() {
        // LEI has a suffix but no note -> the (suffix, None) bottom branch, and
        // the top projects to the bare scheme short-name `LEI`.
        let svg = render("5493001KJTIIGC8Y1R12", 1.0, 12.0, None).unwrap();
        assert!(svg.contains("...12"));
        assert!(svg.contains(">LEI</text>"), "svg: {svg}");
        assert!(!svg.contains("data-user-note"));
    }

    #[test]
    fn render_text_fallback_label() {
        // Plain text -> PRIMARY `text` with a utf8 byte SIZE.
        let svg = render("hello world", 1.0, 12.0, None).unwrap();
        assert!(svg.contains(">text, 11-byte</text>"), "svg: {svg}");
    }

    #[test]
    fn render_swhid_semantic_prefix_label() {
        // swhid projects to the self-describing PRIMARY `swh:1:<object>`,
        // no body echo and no trailing `...`.
        let svg = render(
            "swh:1:rev:309cf2674ee7a0749978cf8265ab91a60aea0f7d",
            1.0,
            12.0,
            None,
        )
        .unwrap();
        assert!(svg.contains(">swh:1:rev</text>"), "svg: {svg}");
        assert!(!svg.contains("swh:1:rev:..."));
    }

    #[test]
    fn render_suffix_with_note_bottom_label() {
        // LEI carries a suffix; add a note -> the (suffix, note) bottom branch.
        let svg = render("5493001KJTIIGC8Y1R12", 1.0, 12.0, Some("hi")).unwrap();
        assert!(svg.contains("data-user-note=\"hi\""));
        assert!(svg.contains("...12"));
    }

    #[test]
    fn render_note_only_bottom_label() {
        let svg = render("a1b2c3d4e5f6a7b8", 1.0, 12.0, Some("note1")).unwrap();
        assert!(svg.contains("data-user-note=\"note1\""));
    }

    #[test]
    fn render_large_input_is_truncated() {
        let core = "a".repeat(400);
        let svg = render(&core, 1.0, 12.0, None).unwrap();
        assert!(svg.contains("data-truncated=\"true\""));
        assert!(svg.contains("data-cell-fingerprint=\"true\""));
        assert!(svg.contains("+hash ")); // truncation marker (was "fingerprint of ")
    }

    #[test]
    fn render_is_deterministic() {
        let a = render("0123456789abcdef0123456789abcdef", 1.0, 12.0, None).unwrap();
        let b = render("0123456789abcdef0123456789abcdef", 1.0, 12.0, None).unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn render_is_deterministic_across_shapes_and_params() {
        // TST-F2 / TST-F5: determinism was only proven for one hex-256 input at
        // default params. Render each of several distinct input shapes and
        // parameter combinations twice and assert byte-identical output, so a
        // non-determinism regression on ANY of these paths fails cargo test:
        //   - hex (4 bits/char)             - UUID (dashed)
        //   - base64url text-fallback       - large input (>512 bits, truncation
        //                                       head/middle/tail path)
        //   - non-default font-size + aspect-ratio
        let big_hex: String = "0123456789abcdef".repeat(16); // 256 hex chars -> >512 bits
        let cases: &[(&str, f64, f64, Option<&str>)] = &[
            // hex, default params
            ("0123456789abcdef0123456789abcdef", 1.0, 12.0, None),
            // UUID (dashed) — normalization + semantic-prefix path
            ("550e8400-e29b-41d4-a716-446655440000", 1.0, 12.0, None),
            // text fallback -> base64url (the None-parse branch)
            ("the quick brown fox", 1.0, 12.0, None),
            // large input -> truncation (head + fingerprint-middle + tail)
            (big_hex.as_str(), 1.0, 12.0, None),
            // non-default font size + aspect ratio + a note (bottom strip)
            ("0123456789abcdef0123456789abcdef", 2.5, 9.0, Some("note1")),
            // wide aspect ratio, large font
            ("0123456789abcdef0123456789abcdef0123", 0.4, 24.0, None),
        ];
        for (i, &(input, ar, fs, note)) in cases.iter().enumerate() {
            let a = render(input, ar, fs, note)
                .unwrap_or_else(|e| panic!("case {i} ({input:.16}) failed: {e:?}"));
            let b = render(input, ar, fs, note).unwrap();
            assert_eq!(a, b, "case {i} ({input:.16}) is non-deterministic");
        }
    }

    #[test]
    fn large_input_takes_truncation_path() {
        // Guard the assumption behind the determinism case above: a >512-bit
        // input must actually exercise the head/middle/tail truncation path.
        let big_hex: String = "0123456789abcdef".repeat(16);
        let svg = render(&big_hex, 1.0, 12.0, None).unwrap();
        assert!(
            svg.contains("data-truncated=\"true\""),
            "expected the large-input truncation path to be exercised"
        );
    }

    #[test]
    fn version_stamps_track_crate_and_spec() {
        // MNT-F2 / SPEC-F2: the rendered SVG's data-entviz-lib MUST equal the
        // crate version and data-entviz-version MUST equal SPEC_VERSION, so the
        // stamps can never silently drift from Cargo.toml / crate::SPEC_VERSION.
        let svg = render("0123456789abcdef0123456789abcdef", 1.0, 12.0, None).unwrap();
        assert!(
            svg.contains(&format!(
                "data-entviz-lib=\"{}\"",
                env!("CARGO_PKG_VERSION")
            )),
            "data-entviz-lib must equal CARGO_PKG_VERSION ({})",
            env!("CARGO_PKG_VERSION")
        );
        assert!(
            svg.contains(&format!("data-entviz-version=\"{}\"", crate::SPEC_VERSION)),
            "data-entviz-version must equal SPEC_VERSION ({})",
            crate::SPEC_VERSION
        );
    }

    #[test]
    fn render_hex_uses_smaller_cell_text() {
        // hex (4 bits/char) scales cell text to 0.75; just assert it renders text.
        let svg = render("0123456789abcdef0123456789abcdef", 1.0, 12.0, None).unwrap();
        assert!(svg.contains("<text"));
    }

    #[test]
    fn font_family_hoisted_to_root_every_text_has_font_size() {
        // The monospace chain is set ONCE on the root <svg> (an inherited
        // presentation property), not repeated per <text>. Every <text> carries
        // a compact font-size attribute and NO per-text font-family. Render a
        // payload with a suffix so both label strips are present, plus a UUID
        // for the color-bar letters and cell text.
        for input in [
            "0123456789abcdef0123456789abcdef",
            "550e8400-e29b-41d4-a716-446655440000",
            "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGZ user@example",
        ] {
            let svg = render(input, 1.0, 12.0, None).unwrap();

            // font-family appears exactly once, on the root <svg>, with the
            // documented chain (a stable marker token suffices).
            assert_eq!(
                svg.matches("font-family=").count(),
                1,
                "font-family must appear exactly once (root <svg>) for {input:?}"
            );
            assert_eq!(
                svg.matches("JetBrains").count(),
                1,
                "font chain marker must appear once (root <svg>) for {input:?}"
            );
            // No <text> should carry the legacy `style="font-family:..."`.
            assert!(
                !svg.contains("style=\"font-family"),
                "no <text> should carry a per-text font-family style for {input:?}"
            );

            // Every <text> element must carry a font-size attribute.
            for text_el in svg.split("<text").skip(1) {
                let tag = &text_el[..text_el.find('>').unwrap()];
                assert!(
                    tag.contains("font-size=\""),
                    "<text {tag}> is missing a font-size attribute for {input:?}"
                );
                assert!(
                    !tag.contains("font-family"),
                    "<text {tag}> must not set its own font-family for {input:?}"
                );
            }
        }
    }
}