autumn-web 0.7.0

An opinionated, convention-over-configuration web framework for Rust
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
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
//! Lays a parsed [`Node`](super::html::Node) tree out as PDF pages.
//!
//! Deliberately **not** a CSS box-model layout engine (see [`crate::pdf`]
//! module docs for why): block elements flow top-to-bottom in a single
//! column, tables use naive equal-width columns, and styling is limited to
//! bold/italic via the built-in Helvetica font family. This is enough for
//! scaffold-shaped documents (headings, paragraphs, tables, lists) — not for
//! arbitrary CSS layouts.

use printpdf::{
    BuiltinFont, Color, Line, LinePoint, Op, PdfFontHandle, PdfPage, Point, Pt, Rgb, TextItem,
};

use super::html::Node;
use super::metrics::{char_width_1000em, text_width_pt};

/// Recursion depth cap for walking the parsed node tree — defense in depth
/// against pathologically deep (adversarial or accidental) nesting; the
/// [`super::html`] parser itself is iterative and immune to this, but this
/// layout walker recurses per nesting level for the (normally shallow)
/// element tree it receives.
const MAX_DEPTH: u32 = 512;

/// A4 portrait, matching the default most other frameworks in this space
/// (Rails' `wicked_pdf`, `WeasyPrint`) ship.
const PAGE_WIDTH_PT: f32 = 595.28;
const PAGE_HEIGHT_PT: f32 = 841.89;
const MARGIN_PT: f32 = 50.0;

const BLACK: Color = Color::Rgb(Rgb {
    r: 0.0,
    g: 0.0,
    b: 0.0,
    icc_profile: None,
});

/// One inline run of same-styled text, or an explicit line break.
#[derive(Debug, Clone, PartialEq)]
enum Span {
    Run {
        text: String,
        bold: bool,
        italic: bool,
    },
    Break,
}

/// A single word (already whitespace-split) carrying its own style, or an
/// explicit line break — the unit [`wrap`] packs into lines.
#[derive(Debug, Clone, PartialEq)]
enum Word {
    Text {
        text: String,
        bold: bool,
        italic: bool,
        /// No whitespace separated this word from the previous one in the
        /// source HTML (e.g. `$<strong>42.00</strong>`, where "$" and
        /// "42.00" are adjacent spans with nothing between them) — render
        /// with no space before it. [`wrap`] still breaks a line here if the
        /// glued pair doesn't fit together (see `unbreakable` below for the
        /// one case where it must not).
        glue: bool,
        /// A literal NBSP (`&nbsp;`) sits at this glue boundary — trailing
        /// on the previous span's text, or leading on this one. Unlike
        /// ordinary `glue` (two adjacent spans with nothing between them,
        /// where a line break is an acceptable fallback if they don't fit),
        /// an NBSP is the source HTML explicitly asking for these two words
        /// to never separate across a line break — so [`wrap`] must move
        /// this word *and* the one it's glued to together, rather than
        /// breaking between them on overflow. Always implies `glue`.
        unbreakable: bool,
    },
    Break,
}

#[derive(Debug, Clone, PartialEq)]
struct TableRow {
    /// `(cell spans, is_header)`.
    cells: Vec<(Vec<Span>, bool)>,
}

#[derive(Debug, Clone, PartialEq)]
enum Block {
    Heading(u8, Vec<Span>),
    Paragraph(Vec<Span>),
    ListItem { marker: String, spans: Vec<Span> },
    Rule,
    Table(Vec<TableRow>),
}

/// Recognized block-level tags that flush any pending implicit paragraph and
/// start a new block. Everything else (span, a, unknown tags, ...) is either
/// a recognized inline style or a transparent passthrough.
fn heading_level(tag: &str) -> Option<u8> {
    match tag {
        "h1" => Some(1),
        "h2" => Some(2),
        "h3" => Some(3),
        "h4" => Some(4),
        "h5" => Some(5),
        "h6" => Some(6),
        _ => None,
    }
}

/// Tags whose content is never rendered as visible text, even though the
/// generic "unrecognized tag = transparent passthrough" rule would otherwise
/// walk into them. A full server-rendered page (the natural input for
/// `Pdf::from_html` when it isn't a purpose-built Maud fragment) commonly
/// carries a `<head>` (with `<title>`/`<meta>`/`<link>`) and inline
/// `<script>`/`<style>` blocks; without this, their raw source text would be
/// emitted into the PDF ahead of (or interleaved with) the actual content.
fn is_non_rendered(tag: &str) -> bool {
    matches!(
        tag,
        "script" | "style" | "noscript" | "template" | "head" | "title"
    )
}

/// Tags that are block-level when a browser lays them out, but that can turn
/// up *inside* a context this renderer represents as flat [`Span`]s rather
/// than nested [`Block`]s — a list item's or table cell's content
/// (`<li><p>First</p><p>Second</p></li>`, a `<td>` with multiple
/// paragraphs). `inline_spans` can't give these their own [`Block`] the way
/// `flatten_blocks` does for a top-level `<div>`, but it can still keep
/// their text from gluing directly onto whatever comes before/after by
/// inserting a line break around them — the smallest change that stops
/// `<li><p>First</p><p>Second</p></li>` from rendering as "`FirstSecond`".
fn is_block_boundary_in_inline_context(tag: &str) -> bool {
    heading_level(tag).is_some()
        || matches!(
            tag,
            "p" | "div"
                | "blockquote"
                | "li"
                | "dl"
                | "dt"
                | "dd"
                | "section"
                | "article"
                | "main"
                | "header"
                | "footer"
                | "nav"
                | "aside"
                // A nested `<table>` (e.g. `<td><table>...</table></td>`) has
                // no dedicated `Block::Table` path here — `extract_table_rows`
                // only runs on a *top-level* table — so without this, its
                // `table`/`tr`/`td`/`th` structure fell through to the
                // generic transparent-wrapper case and glued adjacent cells'
                // text directly together (`<td>A</td><td>B</td>` rendering
                // as "AB"). Not a real nested table (no grid/borders), but
                // keeps each cell's content from merging into its neighbor.
                | "table"
                | "thead"
                | "tbody"
                | "tfoot"
                | "tr"
                | "td"
                | "th"
                // `<hr>` (e.g. `<li>Before<hr>After</li>`) is a void
                // element (no children to recurse into), and this context
                // has no `Block::Rule` to give it the way `flatten_blocks`
                // does for a top-level `<hr>` — but it still needs to keep
                // "Before" and "After" from gluing into "BeforeAfter". A
                // line break is the closest flat-span equivalent of a rule.
                | "hr"
        )
}

/// Push a line break unless `out` is empty or already ends with one —
/// avoids emitting consecutive/leading [`Span::Break`]s when several block
/// boundaries are adjacent.
fn push_block_break(out: &mut Vec<Span>) {
    if !matches!(out.last(), None | Some(Span::Break)) {
        out.push(Span::Break);
    }
}

/// Drop a trailing [`Span::Break`] left over from [`push_block_break`]
/// wrapping the *last* nested block in a finished span list (a list item, a
/// table cell, ...) — nothing follows it, so it would only render as a
/// stray blank line.
fn trim_trailing_break(spans: &mut Vec<Span>) {
    if matches!(spans.last(), Some(Span::Break)) {
        spans.pop();
    }
}

/// Walk `nodes` collecting inline [`Span`]s, tracking bold/italic state
/// through `strong`/`b` and `em`/`i`, translating `br` to [`Span::Break`],
/// and treating any other tag (including unrecognized ones) as a transparent
/// container — so a scaffold view's wrapper `<div>`/`<span>` markup degrades
/// to its text content instead of being dropped.
fn inline_spans(nodes: &[Node], bold: bool, italic: bool, depth: u32, out: &mut Vec<Span>) {
    if depth > MAX_DEPTH {
        return;
    }
    for node in nodes {
        match node {
            Node::Text(text) => {
                if !text.is_empty() {
                    out.push(Span::Run {
                        text: text.clone(),
                        bold,
                        italic,
                    });
                }
            }
            Node::Element { tag, children } => match tag.as_str() {
                "br" => out.push(Span::Break),
                "strong" | "b" => inline_spans(children, true, italic, depth + 1, out),
                "em" | "i" => inline_spans(children, bold, true, depth + 1, out),
                _ if is_non_rendered(tag) => {}
                "ul" => {
                    push_block_break(out);
                    inline_list_items(children, false, bold, italic, depth + 1, out);
                    push_block_break(out);
                }
                "ol" => {
                    push_block_break(out);
                    inline_list_items(children, true, bold, italic, depth + 1, out);
                    push_block_break(out);
                }
                _ if is_block_boundary_in_inline_context(tag) => {
                    push_block_break(out);
                    inline_spans(children, bold, italic, depth + 1, out);
                    push_block_break(out);
                }
                _ => inline_spans(children, bold, italic, depth + 1, out),
            },
        }
    }
}

/// Like [`extract_list_items`], but emits each item's marker + content as
/// flat [`Span`]s (with a line break between items) instead of
/// [`Block::ListItem`]s. `inline_spans` can't produce nested `Block`s — it's
/// the leaf-level representation already used for a list item's or table
/// cell's own content — so a `<ul>`/`<ol>` nested inside one (e.g.
/// `<li>Parent<ul><li>Child</li></ul></li>`) used to fall through to the
/// generic transparent-wrapper case, which recursed into the inner `<li>`
/// via the same `is_block_boundary_in_inline_context` handling as a stray
/// `<p>` — a line break plus bare text, no marker, no list semantics at
/// all. Not real nested-list layout (no indentation), but keeps each item's
/// bullet/number instead of losing it — same degrade philosophy as
/// `inline_spans`'s other block-boundary handling.
///
/// `bold`/`italic` are the ambient style `inline_spans` was already
/// carrying at the point it found this `<ul>`/`<ol>` (e.g. `true` for a
/// list nested inside a `<th>`, which `inline_spans` starts bold) — applied
/// to both the marker and, via a plain pass-through to the recursive
/// `inline_spans` call below, each item's own content, exactly like
/// `inline_spans` already threads it through every other nested tag.
fn inline_list_items(
    nodes: &[Node],
    ordered: bool,
    bold: bool,
    italic: bool,
    depth: u32,
    out: &mut Vec<Span>,
) {
    if depth > MAX_DEPTH {
        return;
    }
    let mut index = 0u32;
    for node in nodes {
        let Node::Element { tag, children } = node else {
            continue;
        };
        if tag != "li" {
            continue;
        }
        index += 1;
        if index > 1 {
            push_block_break(out);
        }
        let marker = if ordered {
            format!("{index}. ")
        } else {
            "\u{2022} ".to_owned()
        };
        out.push(Span::Run {
            text: marker,
            bold,
            italic,
        });
        // If this item's content starts with a block boundary (e.g.
        // `<li><p>Child</p></li>`), `inline_spans` pushes a break *before*
        // it — normally correct (separating one block from the one before
        // it), but here `out` already ends with the marker's own `Run`, so
        // that leading break lands directly between the marker and its
        // first line of content instead of before a preceding sibling,
        // splitting them across two lines. Strip exactly that one leading
        // break (never more — anything after it is legitimate inter-block
        // spacing within the item's own content).
        let content_start = out.len();
        inline_spans(children, bold, italic, depth + 1, out);
        if out.get(content_start) == Some(&Span::Break) {
            out.remove(content_start);
        }
    }
}

fn extract_table_rows(nodes: &[Node], depth: u32, out: &mut Vec<TableRow>) {
    if depth > MAX_DEPTH {
        return;
    }
    for node in nodes {
        let Node::Element { tag, children } = node else {
            continue;
        };
        match tag.as_str() {
            "tr" => {
                let mut cells = Vec::new();
                for cell in children {
                    let Node::Element {
                        tag: cell_tag,
                        children: cell_children,
                    } = cell
                    else {
                        continue;
                    };
                    let is_header = cell_tag == "th";
                    if is_header || cell_tag == "td" {
                        let mut spans = Vec::new();
                        // `cell_children` is two levels below `tr`'s `depth`
                        // (tr -> td/th -> cell_children).
                        inline_spans(cell_children, is_header, false, depth + 2, &mut spans);
                        trim_trailing_break(&mut spans);
                        cells.push((spans, is_header));
                    }
                }
                out.push(TableRow { cells });
            }
            // Structural wrappers (thead/tbody/tfoot) — descend without
            // emitting a row themselves.
            "thead" | "tbody" | "tfoot" => extract_table_rows(children, depth + 1, out),
            _ if is_non_rendered(tag) => {}
            // Anything else inside a <table> (most commonly <caption>, or a
            // stray text-bearing tag) isn't a row — but its text must still
            // render somewhere, matching this renderer's "unknown tags pass
            // their text through transparently" contract (see module docs).
            // A single-cell row is the simplest way to surface it without a
            // dedicated non-tabular-content block type.
            _ => {
                let mut spans = Vec::new();
                inline_spans(children, false, false, depth + 1, &mut spans);
                trim_trailing_break(&mut spans);
                if !spans.is_empty() {
                    out.push(TableRow {
                        cells: vec![(spans, false)],
                    });
                }
            }
        }
    }
}

fn extract_list_items(nodes: &[Node], ordered: bool, depth: u32, out: &mut Vec<Block>) {
    if depth > MAX_DEPTH {
        return;
    }
    let mut index = 0u32;
    for node in nodes {
        let Node::Element { tag, children } = node else {
            continue;
        };
        if tag != "li" {
            continue;
        }
        index += 1;
        let marker = if ordered {
            format!("{index}.")
        } else {
            "\u{2022}".to_owned()
        };
        let mut spans = Vec::new();
        inline_spans(children, false, false, depth + 1, &mut spans);
        trim_trailing_break(&mut spans);
        out.push(Block::ListItem { marker, spans });
    }
}

/// Flatten a parsed node tree into a flow of [`Block`]s. Consecutive inline
/// content not wrapped in a block tag (bare text, `<span>`, `<strong>`, ... at
/// the top level) is collected into an implicit paragraph, matching how a
/// browser would flow loose text.
fn flatten_blocks(nodes: &[Node], depth: u32, out: &mut Vec<Block>) {
    if depth > MAX_DEPTH {
        return;
    }
    let mut pending: Vec<Span> = Vec::new();
    let flush = |pending: &mut Vec<Span>, out: &mut Vec<Block>| {
        if !pending.is_empty() {
            out.push(Block::Paragraph(std::mem::take(pending)));
        }
    };

    for node in nodes {
        match node {
            Node::Text(text) => {
                // Pushed even when whitespace-only: a text node between two
                // loose inline elements (`<span>Hello</span> <span>world</span>`)
                // carries the one significant space HTML collapses runs of
                // whitespace to — dropping it here would make `words_of`
                // glue the surrounding words together with no space at all.
                // A whitespace-only span still contributes zero *words* (see
                // `words_of`), so this never emits a visible extra blank
                // line — it only preserves the separator.
                if !text.is_empty() {
                    pending.push(Span::Run {
                        text: text.clone(),
                        bold: false,
                        italic: false,
                    });
                }
            }
            Node::Element { tag, children } => {
                if let Some(level) = heading_level(tag) {
                    flush(&mut pending, out);
                    let mut spans = Vec::new();
                    inline_spans(children, true, false, depth + 1, &mut spans);
                    trim_trailing_break(&mut spans);
                    out.push(Block::Heading(level, spans));
                    continue;
                }
                match tag.as_str() {
                    // `p`/`li` cannot legally nest another block element in
                    // HTML (a nested block inside them is already malformed
                    // input), so flattening their content to one implicit
                    // paragraph is a reasonable degrade — and `li`'s normal
                    // path is `extract_list_items` below, not here; this arm
                    // only sees a stray `<li>` outside a `<ul>`/`<ol>`.
                    // `dt`/`dd` (a description list's term/value pair) are
                    // the same shape: each is its own block-level unit whose
                    // content is normally inline, so it gets its own
                    // paragraph rather than gluing onto its sibling term or
                    // value — without this, `<dl><dt>Title</dt><dd>My
                    // Post</dd>...</dl>` (as emitted by scaffold detail
                    // views, e.g. a `property_list` widget) renders as one
                    // run of unbroken text with no row boundaries at all.
                    "p" | "li" | "dt" | "dd" => {
                        flush(&mut pending, out);
                        let mut spans = Vec::new();
                        inline_spans(children, false, false, depth + 1, &mut spans);
                        trim_trailing_break(&mut spans);
                        out.push(Block::Paragraph(spans));
                    }
                    // `div`/`blockquote`/`dl` commonly wrap *other block
                    // elements* (`<div><h1>...</h1><p>...</p></div>`,
                    // `<blockquote><p>...</p></blockquote>`, a `<dl>`'s
                    // `<dt>`/`<dd>` children) — recursing through
                    // `flatten_blocks` (rather than flattening every
                    // descendant through `inline_spans` into one paragraph,
                    // which would merge a heading and two paragraphs into a
                    // single run of unbroken text) lets nested block tags
                    // still produce their own blocks. When the children are
                    // purely inline (e.g. `<div><span>hi</span></div>`),
                    // `flatten_blocks`'s own pending/flush accumulator
                    // produces exactly the same single implicit paragraph
                    // this used to build directly. HTML5's semantic
                    // sectioning/landmark elements (`section`/`article`/
                    // `main`/`header`/`footer`/`nav`/`aside`) commonly wrap
                    // block content the same way a `<div>` does — without
                    // them here, adjacent elements of loose text
                    // (`<main><section>Summary</section><section>Details</section></main>`,
                    // and equally `<aside>Summary</aside><aside>Details</aside>`)
                    // fell through to the generic transparent-passthrough
                    // arm and accumulated into one pending paragraph with no
                    // separator (`SummaryDetails`).
                    "div" | "blockquote" | "dl" | "section" | "article" | "main" | "header"
                    | "footer" | "nav" | "aside" => {
                        flush(&mut pending, out);
                        flatten_blocks(children, depth + 1, out);
                    }
                    "hr" => {
                        flush(&mut pending, out);
                        out.push(Block::Rule);
                    }
                    "table" => {
                        flush(&mut pending, out);
                        let mut rows = Vec::new();
                        extract_table_rows(children, depth + 1, &mut rows);
                        out.push(Block::Table(rows));
                    }
                    "ul" => {
                        flush(&mut pending, out);
                        extract_list_items(children, false, depth + 1, out);
                    }
                    "ol" => {
                        flush(&mut pending, out);
                        extract_list_items(children, true, depth + 1, out);
                    }
                    "br" => pending.push(Span::Break),
                    "strong" | "b" => inline_spans(children, true, false, depth + 1, &mut pending),
                    "em" | "i" => inline_spans(children, false, true, depth + 1, &mut pending),
                    _ if is_non_rendered(tag) => {}
                    // Transparent passthrough: unknown/inline wrapper tags
                    // (span, a, ...) flow their children into the current
                    // implicit paragraph rather than being dropped.
                    _ => flatten_into_pending(children, depth + 1, &mut pending, out),
                }
            }
        }
    }
    flush(&mut pending, out);
}

/// Like [`flatten_blocks`], but for a transparent inline wrapper: nested
/// block tags still start real blocks (flushing `pending` first), while
/// inline content keeps accumulating into the caller's `pending` buffer.
fn flatten_into_pending(nodes: &[Node], depth: u32, pending: &mut Vec<Span>, out: &mut Vec<Block>) {
    if depth > MAX_DEPTH {
        return;
    }
    // Reuse `flatten_blocks` by giving it a scratch buffer, then splice: if
    // it only ever produced inline text (no nested block tags fired), that
    // text lives in blocks as trailing paragraphs — simplest correct
    // approach is to just recurse the same tag-matching logic directly.
    for node in nodes {
        match node {
            Node::Text(text) => {
                // See the matching comment in `flatten_blocks` — a
                // whitespace-only text node is a significant separator
                // between loose inline elements, not noise to discard.
                if !text.is_empty() {
                    pending.push(Span::Run {
                        text: text.clone(),
                        bold: false,
                        italic: false,
                    });
                }
            }
            Node::Element { tag, children } => {
                if heading_level(tag).is_some()
                    || matches!(
                        tag.as_str(),
                        "p" | "div"
                            | "li"
                            | "blockquote"
                            | "hr"
                            | "table"
                            | "ul"
                            | "ol"
                            | "dl"
                            | "dt"
                            | "dd"
                            | "section"
                            | "article"
                            | "main"
                            | "header"
                            | "footer"
                            | "nav"
                            | "aside"
                    )
                {
                    if !pending.is_empty() {
                        out.push(Block::Paragraph(std::mem::take(pending)));
                    }
                    flatten_blocks(std::slice::from_ref(node), depth, out);
                } else {
                    match tag.as_str() {
                        "br" => pending.push(Span::Break),
                        "strong" | "b" => inline_spans(children, true, false, depth + 1, pending),
                        "em" | "i" => inline_spans(children, false, true, depth + 1, pending),
                        _ if is_non_rendered(tag) => {}
                        _ => flatten_into_pending(children, depth + 1, pending, out),
                    }
                }
            }
        }
    }
}

/// Non-breaking space variants this renderer treats identically to a
/// literal `&nbsp;` (U+00A0) for line-breaking purposes: U+2007 FIGURE
/// SPACE and U+202F NARROW NO-BREAK SPACE, both common in localized
/// number formatting (aligned digit columns; French-style thousands
/// separators, e.g. `10 000`) — and, like U+00A0, whitespace per
/// Unicode's `White_Space` property, so a blanket `char::is_whitespace()`
/// check alone can't tell them apart from an ordinary breakable space.
/// Purely a line-breaking concern: whether the glyph itself renders
/// correctly is the same already-documented base-14/WinAnsi-encoding
/// limitation that applies to any character outside that set (CJK,
/// emoji, ...) — unaffected by this.
const fn is_non_breaking_space(c: char) -> bool {
    matches!(c, '\u{00A0}' | '\u{2007}' | '\u{202F}')
}

/// Flatten `spans` into words, splitting each run's text on whitespace and
/// tracking, per word, whether it was directly adjacent (no whitespace) to
/// the previous span's text — see [`Word::Text::glue`]. A span whose text is
/// entirely whitespace (or empty) breaks any glue run without itself
/// emitting a word.
fn words_of(spans: &[Span]) -> Vec<Word> {
    let mut words = Vec::new();
    let mut glue_next = false;
    // Whether the pending `glue_next` boundary is specifically an NBSP —
    // i.e. the previous span's text ended with a literal U+00A0 — as
    // opposed to two spans with plain nothing (no whitespace at all)
    // between them. See [`Word::Text::unbreakable`].
    let mut glue_next_unbreakable = false;
    for span in spans {
        match span {
            Span::Break => {
                words.push(Word::Break);
                glue_next = false;
                glue_next_unbreakable = false;
            }
            Span::Run { text, bold, italic } => {
                // Must agree with the split predicate below on what counts as
                // a "real" (breakable) whitespace boundary — NBSP doesn't,
                // since it's deliberately kept *inside* the resulting token
                // rather than split off. Using the blanket `char::is_whitespace`
                // here (which NBSP also satisfies) would say a span starting/
                // ending with NBSP has a "real" separator at that edge, gluing
                // it to nothing — so `wrap` inserts its own extra plain space
                // next to a token that already renders the NBSP as one, and
                // allows a line break at a boundary the NBSP was meant to make
                // unbreakable.
                let is_breakable_ws = |c: char| c.is_whitespace() && !is_non_breaking_space(c);
                let starts_with_ws = text.starts_with(is_breakable_ws);
                let ends_with_ws = text.ends_with(is_breakable_ws);
                let starts_with_nbsp = text.starts_with(is_non_breaking_space);
                let ends_with_nbsp = text.ends_with(is_non_breaking_space);
                let mut emitted_any = false;
                // Split on breakable whitespace only — NBSP and its other
                // non-breaking variants (`&nbsp;`/U+00A0, U+2007, U+202F —
                // see `is_non_breaking_space`) satisfy `char::is_whitespace()`
                // so `split_whitespace()` would treat them as an ordinary word
                // separator, discarding the entire point of a *non*-breaking
                // space: it stays inside the resulting token instead, so a
                // line can never break between the words it joins (it still
                // renders as a real space — `char_width_1000em` gives it the
                // same width as a plain space — the token is just atomic).
                for (i, w) in text
                    .split(is_breakable_ws)
                    .filter(|w| !w.is_empty())
                    .enumerate()
                {
                    let glue = i == 0 && glue_next && !starts_with_ws;
                    words.push(Word::Text {
                        text: w.to_owned(),
                        bold: *bold,
                        italic: *italic,
                        glue,
                        unbreakable: glue && (glue_next_unbreakable || starts_with_nbsp),
                    });
                    emitted_any = true;
                }
                glue_next = emitted_any && !ends_with_ws;
                glue_next_unbreakable = emitted_any && ends_with_nbsp;
            }
        }
    }
    words
}

/// A word already positioned within a wrapped line: `(text, bold, italic,
/// glue)`, where `glue` means "no space before this word" — see
/// [`Word::Text::glue`].
type StyledWord = (String, bool, bool, bool);

/// Split `text` into the fewest possible chunks that each fit within
/// `max_width_pt`, breaking at character boundaries (not word boundaries —
/// this is only used for a single token that's already too wide to fit on a
/// line by itself, e.g. a long URL/hash/identifier with no internal
/// whitespace to break at).
///
/// An embedded non-breaking space (`&nbsp;`/U+00A0, or one of the other
/// variants [`is_non_breaking_space`] recognizes, kept inside the token by
/// `words_of` — see [`Word::Text::unbreakable`] for the same rule at a
/// *span* boundary) must never sit at a chunk boundary on *either* side: as
/// the last character of one chunk, it isolates whatever follows onto the
/// next; as the first character of a chunk, it isolates whatever precedes
/// it onto the previous *and* leaves a rendered leading space at the start
/// of the new line — both indistinguishable from an ordinary space
/// wrapping there, exactly what a non-breaking space forbids. Consecutive
/// ones chain: `A&nbsp;B&nbsp;C`
/// has *no* legal split point anywhere between `A` and `C`, so when the
/// natural per-character boundary would land inside that chain, the whole
/// chain (back to the nearest ordinary, non-NBSP-adjacent character) moves
/// to the *next* chunk together — the same "relocate the whole unbreakable
/// run, not just its last word" rule [`wrap`] applies to a glued run of
/// *words*, applied here at the character level via an equivalent
/// incrementally-tracked `run_start`/`run_width` (not recomputed by
/// rescanning `current` on every overflow, for the same reason `wrap`'s
/// `run_width` isn't: a long chain of NBSP-glued characters must stay
/// linear, not quadratic, in the number of overflow events).
///
/// Always makes progress: a chunk always gets at least one character even if
/// that character alone exceeds `max_width_pt` — the sole exception being a
/// chunk that's entirely one NBSP-connected chain with no earlier split
/// point to relocate to, which is left overflowing rather than split
/// mid-chain, the same as an entire line that's one unbreakable run in
/// [`wrap`].
///
/// `first_chunk_max_width_pt` is the width budget for *only* the first
/// produced chunk; every later chunk uses `max_width_pt`. The plain
/// oversized-token case in [`wrap`] (and every direct caller below) passes
/// the same value for both — a fresh line has the full column width
/// available. [`split_oversized_glued_word`] passes a *narrower* value for
/// the first chunk specifically: that chunk is appended to a line that
/// already has other content on it, so sizing it against the full column
/// width the way the rest of this function already does would produce a
/// first chunk that, combined with what's already on the line, still
/// overflows well past the column — not the character-level wrapping this
/// function exists to provide.
fn split_into_fitting_chunks(
    text: &str,
    font_size_pt: f32,
    bold: bool,
    first_chunk_max_width_pt: f32,
    max_width_pt: f32,
) -> Vec<String> {
    let mut chunks = Vec::new();
    let mut current = String::new();
    let mut current_width = 0.0f32;
    // Byte index into `current` (always a char boundary) where the
    // NBSP-connected run ending at `current`'s last character begins, and
    // that run's width — see the function docs above.
    let mut run_start = 0usize;
    let mut run_width = 0.0f32;
    for ch in text.chars() {
        let ch_width = f32::from(char_width_1000em(ch, bold)) / 1000.0 * font_size_pt;
        let connected = is_non_breaking_space(ch) || current.ends_with(is_non_breaking_space);
        let limit = if chunks.is_empty() {
            first_chunk_max_width_pt
        } else {
            max_width_pt
        };
        if !current.is_empty() && current_width + ch_width > limit {
            if connected {
                if run_start > 0 {
                    let tail = current.split_off(run_start);
                    chunks.push(std::mem::take(&mut current));
                    current = tail;
                    current_width = run_width;
                    run_start = 0;
                }
                // Else the whole chunk built so far is one NBSP-connected
                // chain with nowhere earlier to split — accept the
                // overflow rather than break mid-chain.
            } else {
                chunks.push(std::mem::take(&mut current));
                current_width = 0.0;
                run_start = 0;
                run_width = 0.0;
            }
        }
        if connected {
            run_width += ch_width;
        } else {
            run_start = current.len();
            run_width = ch_width;
        }
        current.push(ch);
        current_width += ch_width;
    }
    if !current.is_empty() {
        chunks.push(current);
    }
    chunks
}

/// Greedily word-wrap `words` to `max_width_pt`, honoring explicit
/// [`Word::Break`]s. Each returned line is a list of [`StyledWord`]s in
/// left-to-right order; the caller positions each word itself rather than
/// this function merging same-style runs, keeping the wrapping logic simple
/// and easy to verify. A glued word is kept on the same line as the word
/// before it whenever it fits — but if it wouldn't (e.g. two large,
/// differently-styled runs immediately adjacent in the source HTML with no
/// whitespace between them), the line still breaks before it, the same as
/// an ordinary word boundary would; the only difference glue makes is that
/// no rendered space is inserted, which a line break doesn't need anyway.
///
/// [`Word::Text::unbreakable`] words are held to a stricter rule: an NBSP
/// means the source HTML explicitly forbids a line break at that boundary,
/// so on overflow the *entire* unbreakable run built up so far (tracked via
/// `run_start`/`run_width`, not just the word that doesn't fit) moves to the
/// next line together, rather than splitting between the run and the new
/// word the way ordinary glue would.
///
/// A single word wider than `max_width_pt` on its own (a long URL, hash, or
/// identifier with nowhere to break) is character-wrapped via
/// [`split_into_fitting_chunks`] instead of being left to overflow the page
/// or table-cell boundary.
///
/// If an NBSP-glued (unbreakable) word is itself individually oversized,
/// [`wrap`] calls this to character-split it while keeping the first chunk
/// glued to whatever `current` already holds — `w` is that word's own
/// (already-known-oversized) width, counted into `*current_width` before
/// this runs, so `*current_width - w` is the width of whatever's already
/// on the line the first chunk must still fit alongside. That's the width
/// budget passed to [`split_into_fitting_chunks`] for its first chunk
/// specifically (see that function's `first_chunk_max_width_pt` docs) —
/// without it, the first chunk was sized against the *full* column width
/// the same as every later chunk, so appending it to an already-nonempty
/// line could still send the combined line well past `max_width_pt`,
/// defeating the character-wrapping this function exists to provide.
/// Returns `true` and leaves `current`/`current_width`/`lines` updated
/// (first chunk appended and flushed, remaining chunks distributed, last
/// one left as the new `current`) if splitting actually produced more
/// than one chunk; returns `false` with nothing touched if
/// [`split_into_fitting_chunks`] returned only one chunk (nothing left to
/// split — e.g. the whole word is one NBSP-connected chain with no earlier
/// split point, see that function's own accepted-overflow fallback), so the
/// caller can fall through to its plain glue-the-whole-word-as-is path.
/// Extracted out of [`wrap`] purely to keep that function's line count
/// down — this has no state of its own beyond its `&mut` parameters.
#[allow(clippy::too_many_arguments)]
fn split_oversized_glued_word(
    text: &str,
    bold: bool,
    italic: bool,
    w: f32,
    font_size_pt: f32,
    max_width_pt: f32,
    current: &mut Vec<StyledWord>,
    current_width: &mut f32,
    lines: &mut Vec<Vec<StyledWord>>,
) -> bool {
    let existing_width = (*current_width - w).max(0.0);
    let mut chunks = split_into_fitting_chunks(
        text,
        font_size_pt,
        bold,
        (max_width_pt - existing_width).max(0.0),
        max_width_pt,
    )
    .into_iter();
    let first = chunks
        .next()
        .expect("split_into_fitting_chunks never returns empty chunks for non-empty text");
    let rest: Vec<String> = chunks.collect();
    if rest.is_empty() {
        return false;
    }
    let first_w = text_width_pt(&first, font_size_pt, bold);
    *current_width = *current_width - w + first_w;
    current.push((first, bold, italic, true));
    lines.push(std::mem::take(current));
    let last = rest.len() - 1;
    for (i, chunk) in rest.into_iter().enumerate() {
        let chunk_w = text_width_pt(&chunk, font_size_pt, bold);
        if i == last {
            *current_width = chunk_w;
            *current = vec![(chunk, bold, italic, false)];
        } else {
            lines.push(vec![(chunk, bold, italic, false)]);
        }
    }
    true
}

/// Handles an NBSP-glued (`unbreakable`) word once the caller ([`wrap`])
/// has already confirmed `unbreakable` is set and `current` isn't empty —
/// the two preconditions for this word needing glued-run handling instead
/// of the plain word-wrap path below. An unbreakable word must never be
/// split away from whatever it's glued to just because it also happens to
/// be individually too wide for one line on its own, so on overflow the
/// *entire* unbreakable run built up so far (tracked via `run_start`/
/// `run_width`, not just this word) relocates to a fresh line together,
/// rather than splitting between the run and this word the way ordinary
/// glue would; if there's nowhere better to put it (`run_start == 0`, the
/// run already spans the whole line from its start), the overflow is
/// accepted instead of looping forever.
///
/// The NBSP boundary only forbids a break *right there*, though — it says
/// nothing about the rest of this word if it's *also* individually wider
/// than a whole line (e.g. a still-open `<strong>` run glued via `&nbsp;`
/// to 100 characters of unbroken text). Left whole, that's not just
/// suboptimal, it's the entire remaining run rendered as one unsplit,
/// unbounded-width token — overflowing and clipped, not merely spilling a
/// little past the margin. [`split_oversized_glued_word`] character-splits
/// it the same way the ordinary oversized-token branch in [`wrap`] does,
/// just keeping the first chunk glued right here; see its docs for the
/// `false` fallback (nothing left to split) this falls through from.
///
/// Extracted out of [`wrap`] purely to keep that function's line count
/// down — this has no state of its own beyond its `&mut` parameters.
#[allow(clippy::too_many_arguments)]
fn handle_unbreakable_word(
    text: &str,
    bold: bool,
    italic: bool,
    w: f32,
    font_size_pt: f32,
    max_width_pt: f32,
    current: &mut Vec<StyledWord>,
    current_width: &mut f32,
    run_start: &mut usize,
    run_width: &mut f32,
    lines: &mut Vec<Vec<StyledWord>>,
) {
    let new_run_width = *run_width + w;
    let prefix_width = *current_width - *run_width;
    if *run_start > 0 && prefix_width + new_run_width > max_width_pt {
        let tail = current.split_off(*run_start);
        lines.push(std::mem::take(current));
        *current = tail;
        *current_width = new_run_width;
        *run_start = 0;
    } else {
        *current_width = prefix_width + new_run_width;
    }
    if w > max_width_pt
        && !text.is_empty()
        && split_oversized_glued_word(
            text,
            bold,
            italic,
            w,
            font_size_pt,
            max_width_pt,
            current,
            current_width,
            lines,
        )
    {
        *run_start = 0;
        *run_width = *current_width;
        return;
    }
    current.push((text.to_owned(), bold, italic, true));
    *run_width = new_run_width;
}

fn wrap(words: &[Word], max_width_pt: f32, font_size_pt: f32) -> Vec<Vec<StyledWord>> {
    let space_w = text_width_pt(" ", font_size_pt, false);
    let mut lines = Vec::new();
    let mut current: Vec<StyledWord> = Vec::new();
    let mut current_width = 0.0f32;
    // Index into `current` where the active unbreakable (NBSP-glued) run
    // begins, and that run's total width — tracked incrementally (not
    // recomputed by summing `current[run_start..]` on each word) so a long
    // chain of NBSP-glued words stays linear, not quadratic, in the number
    // of words — see the `long_run_of_unterminated_*` lint on this module
    // for why that class of bug matters here.
    let mut run_start = 0usize;
    let mut run_width = 0.0f32;

    for word in words {
        match word {
            Word::Break => {
                lines.push(std::mem::take(&mut current));
                current_width = 0.0;
                run_start = 0;
                run_width = 0.0;
            }
            Word::Text {
                text,
                bold,
                italic,
                glue,
                unbreakable,
            } => {
                let w = text_width_pt(text, font_size_pt, *bold);
                // See `handle_unbreakable_word`'s docs for why this needs
                // its own path, checked *before* the oversized-token
                // branch below — an unbreakable (NBSP-glued) word must
                // never be split away from whatever it's glued to just
                // because it also happens to be individually too wide for
                // one line on its own.
                if *unbreakable && !current.is_empty() {
                    handle_unbreakable_word(
                        text,
                        *bold,
                        *italic,
                        w,
                        font_size_pt,
                        max_width_pt,
                        &mut current,
                        &mut current_width,
                        &mut run_start,
                        &mut run_width,
                        &mut lines,
                    );
                    continue;
                }
                if w > max_width_pt && !text.is_empty() {
                    if !current.is_empty() {
                        lines.push(std::mem::take(&mut current));
                        current_width = 0.0;
                    }
                    let chunks = split_into_fitting_chunks(
                        text,
                        font_size_pt,
                        *bold,
                        max_width_pt,
                        max_width_pt,
                    );
                    let last = chunks.len().saturating_sub(1);
                    for (i, chunk) in chunks.into_iter().enumerate() {
                        let chunk_w = text_width_pt(&chunk, font_size_pt, *bold);
                        if i == last {
                            current_width = chunk_w;
                            current = vec![(chunk, *bold, *italic, false)];
                        } else {
                            lines.push(vec![(chunk, *bold, *italic, false)]);
                        }
                    }
                    run_start = 0;
                    run_width = current_width;
                    continue;
                }
                let mut glued = *glue && !current.is_empty();
                // Glued words skip the space width (nothing renders between
                // them and the previous word) but otherwise get the same
                // fit check as any other word — a glued run that doesn't
                // fit still breaks the line, it just doesn't gain a
                // rendered space by doing so.
                let needed = if current.is_empty() || glued {
                    w
                } else {
                    w + space_w
                };
                if !current.is_empty() && current_width + needed > max_width_pt {
                    lines.push(std::mem::take(&mut current));
                    current_width = 0.0;
                    glued = false;
                }
                current_width += if current.is_empty() || glued {
                    w
                } else {
                    w + space_w
                };
                run_start = current.len();
                run_width = w;
                current.push((text.clone(), *bold, *italic, glued));
            }
        }
    }
    if !current.is_empty() {
        lines.push(current);
    }
    lines
}

const fn builtin_font(bold: bool, italic: bool) -> BuiltinFont {
    match (bold, italic) {
        (false, false) => BuiltinFont::Helvetica,
        (true, false) => BuiltinFont::HelveticaBold,
        (false, true) => BuiltinFont::HelveticaOblique,
        (true, true) => BuiltinFont::HelveticaBoldOblique,
    }
}

/// Accumulates [`Op`]s across pages, handling page breaks.
struct Writer {
    pages: Vec<PdfPage>,
    ops: Vec<Op>,
    /// Distance in points from the top margin down to the current baseline.
    y_from_top: f32,
    content_width: f32,
}

impl Writer {
    fn new() -> Self {
        Self {
            pages: Vec::new(),
            ops: Vec::new(),
            y_from_top: 0.0,
            content_width: (-2.0f32).mul_add(MARGIN_PT, PAGE_WIDTH_PT),
        }
    }

    /// PDF y (from the bottom-left origin) for the current cursor.
    fn cursor_y_pt(&self) -> f32 {
        PAGE_HEIGHT_PT - MARGIN_PT - self.y_from_top
    }

    fn ensure_space(&mut self, height_needed: f32) {
        let max_y = (-2.0f32).mul_add(MARGIN_PT, PAGE_HEIGHT_PT);
        if self.y_from_top + height_needed > max_y && self.y_from_top > 0.0 {
            self.new_page();
        }
    }

    fn new_page(&mut self) {
        let ops = std::mem::take(&mut self.ops);
        self.pages.push(PdfPage::new(
            Pt(PAGE_WIDTH_PT).into(),
            Pt(PAGE_HEIGHT_PT).into(),
            ops,
        ));
        self.y_from_top = 0.0;
    }

    /// Draw one word at an explicit x offset (from the left margin) on the
    /// current line.
    fn draw_word(&mut self, x_from_left: f32, text: &str, bold: bool, italic: bool, size: f32) {
        self.ops.push(Op::StartTextSection);
        self.ops.push(Op::SetFont {
            font: PdfFontHandle::Builtin(builtin_font(bold, italic)),
            size: Pt(size),
        });
        self.ops.push(Op::SetFillColor { col: BLACK });
        self.ops.push(Op::SetTextCursor {
            pos: Point {
                x: Pt(MARGIN_PT + x_from_left),
                y: Pt(self.cursor_y_pt()),
            },
        });
        self.ops.push(Op::ShowText {
            items: vec![TextItem::Text(text.to_owned())],
        });
        self.ops.push(Op::EndTextSection);
    }

    /// Render `lines` (as produced by [`wrap`]) starting at `x_offset` from
    /// the left margin, within `width`, advancing the cursor by one
    /// `line_height` per line.
    ///
    /// `break_pages` controls whether this may itself trigger a page break
    /// per line: pass `true` for ordinary top-level flow (paragraphs,
    /// headings, list items), and `false` when called once per *column*
    /// from [`draw_table`](Self::draw_table) — there, the row as a whole
    /// already had its space reserved up front (see that method), and a
    /// page break triggered by one column midway through would flush the
    /// page and reset the cursor to the top of the new one, but the caller's
    /// saved `y_from_top` for the *next* column would then be stale (from
    /// the old, already-flushed page), corrupting that column's vertical
    /// position. Not breaking here just lets a single row that's taller
    /// than a whole page overflow past the bottom margin instead — visually
    /// imperfect, but not a page-break/coordinate-corrupting bug.
    fn draw_lines(
        &mut self,
        lines: &[Vec<StyledWord>],
        x_offset: f32,
        font_size: f32,
        line_height: f32,
        break_pages: bool,
    ) {
        let space_w = text_width_pt(" ", font_size, false);
        for line in lines {
            if break_pages {
                self.ensure_space(line_height);
            }
            let mut x = x_offset;
            let mut first = true;
            for (text, bold, italic, glue) in line {
                if !first && !glue {
                    x += space_w;
                }
                self.draw_word(x, text, *bold, *italic, font_size);
                x += text_width_pt(text, font_size, *bold);
                first = false;
            }
            self.y_from_top += line_height;
        }
    }

    fn draw_spans(&mut self, spans: &[Span], font_size: f32, line_height: f32, space_after: f32) {
        let words = words_of(spans);
        if words.is_empty() {
            return;
        }
        let lines = wrap(&words, self.content_width, font_size);
        self.draw_lines(&lines, 0.0, font_size, line_height, true);
        self.y_from_top += space_after;
    }

    fn draw_rule(&mut self) {
        self.ensure_space(14.0);
        let y = self.cursor_y_pt() - 4.0;
        self.ops.push(Op::SetOutlineColor { col: BLACK });
        self.ops.push(Op::SetOutlineThickness { pt: Pt(0.75) });
        self.ops.push(Op::DrawLine {
            line: Line {
                points: vec![
                    LinePoint {
                        p: Point {
                            x: Pt(MARGIN_PT),
                            y: Pt(y),
                        },
                        bezier: false,
                    },
                    LinePoint {
                        p: Point {
                            x: Pt(MARGIN_PT + self.content_width),
                            y: Pt(y),
                        },
                        bezier: false,
                    },
                ],
                is_closed: false,
            },
        });
        self.y_from_top += 14.0;
    }

    /// Draw `rows` as a naive equal-width-column table.
    ///
    /// Known limitation: a single row is never split across a page
    /// boundary — `ensure_space(row_height)` below reserves room for the
    /// *whole* row up front, and if `row_height` alone exceeds a full page
    /// (e.g. one cell wraps to dozens of lines of a long description), that
    /// reservation is a no-op (see [`ensure_space`](Self::ensure_space)) and
    /// [`draw_lines`](Self::draw_lines) is deliberately told not to page-break
    /// mid-column (`break_pages: false`, see its docs) to avoid corrupting
    /// later columns' position. The row's content past the bottom margin is
    /// then clipped — present in the source and in `extract_text`'s output,
    /// but not visible in the rendered PDF. Splitting one oversized row
    /// across pages with all columns advancing in lockstep is a real
    /// layout-engine feature this deliberately-simple renderer doesn't
    /// attempt (see the module docs on scope); tables sized for realistic
    /// scaffold content (invoice line items, a handful of columns) never
    /// approach this limit.
    // Column/row counts are bounded by how many cells a template author
    // writes into one table (never remotely close to f32's 24-bit mantissa),
    // so the usize/f32 conversions below can't meaningfully lose precision.
    #[allow(clippy::cast_precision_loss)]
    fn draw_table(&mut self, rows: &[TableRow]) {
        const FONT_SIZE: f32 = 10.5;
        const LINE_HEIGHT: f32 = 14.0;
        const CELL_PADDING: f32 = 4.0;

        let n_cols = rows.iter().map(|r| r.cells.len()).max().unwrap_or(0);
        if n_cols == 0 {
            return;
        }
        let col_width = self.content_width / n_cols as f32;

        for row in rows {
            let wrapped: Vec<Vec<Vec<StyledWord>>> = row
                .cells
                .iter()
                .map(|(spans, _)| wrap(&words_of(spans), col_width - CELL_PADDING, FONT_SIZE))
                .collect();
            let row_lines = wrapped.iter().map(Vec::len).max().unwrap_or(1).max(1);
            let row_height = row_lines as f32 * LINE_HEIGHT;
            self.ensure_space(row_height);
            for (col, lines) in wrapped.iter().enumerate() {
                let x_offset = col as f32 * col_width;
                let saved_y = self.y_from_top;
                self.draw_lines(lines, x_offset, FONT_SIZE, LINE_HEIGHT, false);
                self.y_from_top = saved_y;
            }
            self.y_from_top += row_height;
        }
        self.y_from_top += 6.0;
    }

    fn draw_block(&mut self, block: &Block) {
        match block {
            Block::Heading(level, spans) => {
                let size = match level {
                    1 => 22.0,
                    2 => 18.0,
                    3 => 16.0,
                    4 => 14.0,
                    5 => 12.5,
                    _ => 11.5,
                };
                self.draw_spans(spans, size, size * 1.3, size * 0.5);
            }
            Block::Paragraph(spans) => {
                self.draw_spans(spans, 11.0, 14.5, 10.0);
            }
            Block::ListItem { marker, spans } => {
                // A fixed 16pt indent fits every bullet/low-numbered marker
                // this renderer draws ("•", "1." .. "9.") comfortably, but
                // an ordered list's marker keeps growing with its index —
                // "100." alone is already ~21pt at 11pt Helvetica, wider
                // than the indent, so content wrapped at a fixed 16pt
                // overlapped the marker instead of starting after it. Grow
                // the indent (and thus the content's wrap width) to fit
                // whichever marker this specific item actually has.
                const MIN_INDENT: f32 = 16.0;
                const MARKER_GAP: f32 = 4.0;
                const LINE_HEIGHT: f32 = 14.5;
                self.ensure_space(LINE_HEIGHT);
                self.draw_word(0.0, marker, false, false, 11.0);
                let indent = (text_width_pt(marker, 11.0, false) + MARKER_GAP).max(MIN_INDENT);
                let words = words_of(spans);
                let lines = wrap(&words, self.content_width - indent, 11.0);
                if lines.is_empty() {
                    // An empty item (`<li></li>`, or one whose only content
                    // was skipped, e.g. `<li><script>...</script></li>`)
                    // has no lines for `draw_lines` to advance `y_from_top`
                    // by — it only adds `line_height` per *line drawn*, and
                    // there are none — so without this, only the fixed 4pt
                    // spacer below would separate this marker from the next
                    // item's, landing them almost on top of each other.
                    self.y_from_top += LINE_HEIGHT;
                } else {
                    self.draw_lines(&lines, indent, 11.0, LINE_HEIGHT, true);
                }
                self.y_from_top += 4.0;
            }
            Block::Rule => self.draw_rule(),
            Block::Table(rows) => self.draw_table(rows),
        }
    }

    fn finish(mut self) -> Vec<PdfPage> {
        // Always emit at least one (possibly empty) page.
        if self.pages.is_empty() || self.y_from_top > 0.0 || !self.ops.is_empty() {
            self.new_page();
        }
        self.pages
    }
}

/// Render a parsed HTML-subset document as one or more [`PdfPage`]s.
pub(super) fn render_pages(html: &str) -> Vec<PdfPage> {
    let nodes = super::html::parse(html);
    let mut blocks = Vec::new();
    flatten_blocks(&nodes, 0, &mut blocks);

    let mut writer = Writer::new();
    for block in &blocks {
        writer.draw_block(block);
    }
    writer.finish()
}

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

    #[test]
    fn wrap_breaks_long_text_into_multiple_lines() {
        let words = words_of(&[Span::Run {
            text: "the quick brown fox jumps over the lazy dog".to_owned(),
            bold: false,
            italic: false,
        }]);
        let lines = wrap(&words, 80.0, 12.0);
        assert!(lines.len() > 1, "expected wrapping at a narrow width");
        for line in &lines {
            let width: f32 = line
                .iter()
                .map(|(t, b, _, _)| text_width_pt(t, 12.0, *b))
                .sum();
            assert!(width <= 80.0 + 1.0, "line exceeds max width: {width}");
        }
    }

    #[test]
    fn oversized_single_token_is_character_wrapped_not_overflowed() {
        // Regression: a single word wider than the whole column/page (a long
        // URL, hash, or identifier with no whitespace to break at) used to
        // be placed on its own line unsplit, overflowing past the boundary.
        let words = words_of(&[Span::Run {
            text: "https://example.com/a/very/long/path/that/has/no/spaces/anywhere/at/all"
                .to_owned(),
            bold: false,
            italic: false,
        }]);
        let lines = wrap(&words, 80.0, 12.0);
        assert!(
            lines.len() > 1,
            "expected the token to be split across lines"
        );
        for line in &lines {
            let width: f32 = line
                .iter()
                .map(|(t, b, _, _)| text_width_pt(t, 12.0, *b))
                .sum();
            assert!(width <= 80.0 + 1.0, "line exceeds max width: {width}");
        }
        let reassembled: String = lines
            .iter()
            .flat_map(|line| line.iter().map(|(t, ..)| t.as_str()))
            .collect();
        assert_eq!(
            reassembled, "https://example.com/a/very/long/path/that/has/no/spaces/anywhere/at/all",
            "splitting must not drop or reorder any characters"
        );
    }

    #[test]
    fn oversized_token_does_not_split_immediately_adjacent_to_an_embedded_nbsp() {
        // Regression: an oversized token (already too wide for one line, so
        // it goes through `split_into_fitting_chunks`'s plain character
        // splitter) that happens to contain an embedded NBSP had no NBSP
        // awareness — if the natural per-character width boundary fell
        // right after the NBSP, it ended up as the last character of one
        // chunk and whatever followed it started the next, breaking
        // exactly the boundary NBSP forbids. A first fix moved the NBSP
        // itself to the next chunk instead, which merely relocated the
        // forbidden break to *before* the NBSP (leaving a rendered leading
        // space at the start of the next line, and still splitting the
        // pair) — the character before the NBSP must move along with it.
        // A repro matching the reported one: 67 `A`s followed by `&nbsp;B`
        // — the 67 As plus the NBSP fit within the content width, but
        // adding `B` doesn't, so the naive split lands right after the
        // NBSP.
        let text = format!("{}\u{00A0}B", "A".repeat(67));
        let font_size_pt = 11.0;
        let max_width_pt = text_width_pt(&"A".repeat(67), font_size_pt, false)
            + text_width_pt("\u{00A0}", font_size_pt, false)
            + 0.5;
        let chunks =
            split_into_fitting_chunks(&text, font_size_pt, false, max_width_pt, max_width_pt);
        assert!(
            chunks
                .iter()
                .all(|c| !c.starts_with('\u{00A0}') && !c.ends_with('\u{00A0}')),
            "no chunk boundary may sit immediately before or after an NBSP, got {chunks:?}"
        );
        let reassembled: String = chunks.concat();
        assert_eq!(
            reassembled, text,
            "splitting must not drop or reorder any characters"
        );
    }

    #[test]
    fn oversized_token_does_not_split_around_other_unicode_non_breaking_space_variants() {
        // Same regression as the U+00A0 case above, for U+2007/U+202F —
        // see `is_non_breaking_space`.
        for nbsp in ['\u{2007}', '\u{202F}'] {
            let text = format!("{}{nbsp}B", "A".repeat(67));
            let font_size_pt = 11.0;
            let max_width_pt = text_width_pt(&"A".repeat(67), font_size_pt, false)
                + text_width_pt(&nbsp.to_string(), font_size_pt, false)
                + 0.5;
            let chunks =
                split_into_fitting_chunks(&text, font_size_pt, false, max_width_pt, max_width_pt);
            assert!(
                chunks
                    .iter()
                    .all(|c| !c.starts_with(nbsp) && !c.ends_with(nbsp)),
                "U+{:04X}: no chunk boundary may sit immediately before or after it, got \
                 {chunks:?}",
                nbsp as u32
            );
            let reassembled: String = chunks.concat();
            assert_eq!(
                reassembled, text,
                "U+{:04X}: splitting must not drop or reorder any characters",
                nbsp as u32
            );
        }
    }

    #[test]
    fn oversized_token_does_not_split_when_the_incoming_character_is_the_nbsp() {
        // Regression: overflow can be triggered by the NBSP *arriving* as
        // the current character, not just by it already sitting at the end
        // of the accumulated chunk — `current` doesn't yet end with an
        // NBSP at that point, so the existing NBSP-adjacency guard (keyed
        // off `current.ends_with(NBSP)`) never fired, and the boundary
        // landed right before the NBSP the same way it used to land right
        // after one. A repro matching the reported one: 67 `A`s followed
        // by `i&nbsp;B` — the As plus `i` fit within the content width,
        // but adding the NBSP doesn't, so the naive split lands right
        // before it.
        let text = format!("{}i\u{00A0}B", "A".repeat(67));
        let font_size_pt = 11.0;
        let max_width_pt = text_width_pt(&"A".repeat(67), font_size_pt, false)
            + text_width_pt("i", font_size_pt, false)
            + 0.5;
        let chunks =
            split_into_fitting_chunks(&text, font_size_pt, false, max_width_pt, max_width_pt);
        assert!(
            chunks
                .iter()
                .all(|c| !c.starts_with('\u{00A0}') && !c.ends_with('\u{00A0}')),
            "no chunk boundary may sit immediately before or after an NBSP, got {chunks:?}"
        );
        let reassembled: String = chunks.concat();
        assert_eq!(
            reassembled, text,
            "splitting must not drop or reorder any characters"
        );
    }

    #[test]
    fn oversized_token_moves_the_entire_nbsp_connected_chain_not_just_one_neighbor() {
        // Regression: when an oversized token contains *multiple* NBSPs,
        // the previous fix only pulled one preceding character back before
        // emitting the chunk — if that character was itself connected to
        // an earlier NBSP, the emitted chunk still ended in that earlier
        // NBSP, just relocating which NBSP boundary got broken rather than
        // fixing the underlying bug. A repro matching the reported one: 66
        // `A`s followed by `&nbsp;B&nbsp;C` — the As plus the first NBSP
        // plus `B` fit within the content width, but adding the second
        // NBSP doesn't, so the naive split used to land the first chunk
        // right after the first NBSP, breaking that boundary too.
        let text = format!("{}\u{00A0}B\u{00A0}C", "A".repeat(66));
        let font_size_pt = 11.0;
        let max_width_pt = text_width_pt(&"A".repeat(66), font_size_pt, false)
            + text_width_pt("\u{00A0}B", font_size_pt, false)
            + 0.5;
        let chunks =
            split_into_fitting_chunks(&text, font_size_pt, false, max_width_pt, max_width_pt);
        assert!(
            chunks
                .iter()
                .all(|c| !c.starts_with('\u{00A0}') && !c.ends_with('\u{00A0}')),
            "no chunk boundary may sit immediately before or after an NBSP, got {chunks:?}"
        );
        let reassembled: String = chunks.concat();
        assert_eq!(
            reassembled, text,
            "splitting must not drop or reorder any characters"
        );
    }

    #[test]
    fn oversized_token_narrower_than_max_width_is_left_whole() {
        // A word that fits on its own line (even if it wouldn't fit
        // alongside other content already on the current line) must not be
        // needlessly split.
        let words = words_of(&[Span::Run {
            text: "short".to_owned(),
            bold: false,
            italic: false,
        }]);
        let lines = wrap(&words, 80.0, 12.0);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].len(), 1);
        assert_eq!(lines[0][0].0, "short");
    }

    #[test]
    fn wrap_honors_explicit_break() {
        let words = vec![
            Word::Text {
                text: "a".to_owned(),
                bold: false,
                italic: false,
                glue: false,
                unbreakable: false,
            },
            Word::Break,
            Word::Text {
                text: "b".to_owned(),
                bold: false,
                italic: false,
                glue: false,
                unbreakable: false,
            },
        ];
        let lines = wrap(&words, 1000.0, 12.0);
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn non_breaking_space_keeps_its_words_on_one_line() {
        // Regression: `&nbsp;` decodes to U+00A0, which satisfies
        // `char::is_whitespace()` — `split_whitespace()` treated it as an
        // ordinary word separator, discarding its entire point (a line must
        // never break between the words it joins). `words_of` must keep an
        // NBSP-joined run as a single atomic token instead.
        let words = words_of(&[Span::Run {
            text: "Invoice\u{00A0}#42".to_owned(),
            bold: false,
            italic: false,
        }]);
        assert_eq!(
            words,
            vec![Word::Text {
                text: "Invoice\u{00A0}#42".to_owned(),
                bold: false,
                italic: false,
                glue: false,
                unbreakable: false,
            }],
            "NBSP must not split the run into two breakable words"
        );
        // Even at a width that fits neither word comfortably alongside the
        // other, the pair must stay on one line — same as any other single
        // token, just with a real (not zero-width) space rendered in it.
        let narrow_width = text_width_pt("Invoice\u{00A0}#42", 12.0, false) + 1.0;
        let lines = wrap(&words, narrow_width, 12.0);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].len(), 1);
        assert_eq!(lines[0][0].0, "Invoice\u{00A0}#42");
    }

    #[test]
    fn other_unicode_non_breaking_space_variants_also_keep_their_words_on_one_line() {
        // Regression: `is_breakable_ws`/`words_of`'s NBSP handling only
        // exempted U+00A0 — but U+2007 FIGURE SPACE and U+202F NARROW
        // NO-BREAK SPACE are both whitespace per Unicode's `White_Space`
        // property (so `char::is_whitespace()` alone can't tell them
        // apart from an ordinary breakable space) and both common in
        // localized number formatting (aligned digit columns; French-style
        // thousands separators like `10 000`) — without special-casing
        // them the same way as U+00A0, a line could break inside such a
        // number.
        for nbsp in ['\u{2007}', '\u{202F}'] {
            let text = format!("10{nbsp}000");
            let words = words_of(&[Span::Run {
                text: text.clone(),
                bold: false,
                italic: false,
            }]);
            assert_eq!(
                words,
                vec![Word::Text {
                    text: text.clone(),
                    bold: false,
                    italic: false,
                    glue: false,
                    unbreakable: false,
                }],
                "U+{:04X} must not split the run into two breakable words, got {words:?}",
                nbsp as u32
            );
            let narrow_width = text_width_pt(&text, 12.0, false) + 1.0;
            let lines = wrap(&words, narrow_width, 12.0);
            assert_eq!(
                lines.len(),
                1,
                "U+{:04X}: the number must stay on one line, got {lines:?}",
                nbsp as u32
            );
        }
    }

    #[test]
    fn non_breaking_space_leading_a_styled_span_still_glues_to_the_previous_word() {
        // Regression: `Hello<strong>&nbsp;world</strong>` — the leading NBSP
        // stays inside the second span's token (`"\u{00A0}world"`, per the
        // fix above), but `starts_with_ws`/`ends_with_ws` used the blanket
        // `char::is_whitespace()` predicate, which NBSP also satisfies. That
        // treated the span boundary as a "real" separator and set `glue:
        // false` — so `wrap` would insert its own plain space next to a
        // token that already renders the NBSP as one (a visible double
        // space), and would allow a line break exactly where the NBSP was
        // meant to forbid one.
        let words = words_of(&[
            Span::Run {
                text: "Hello".to_owned(),
                bold: false,
                italic: false,
            },
            Span::Run {
                text: "\u{00A0}world".to_owned(),
                bold: true,
                italic: false,
            },
        ]);
        assert_eq!(
            words,
            vec![
                Word::Text {
                    text: "Hello".to_owned(),
                    bold: false,
                    italic: false,
                    glue: false,
                    unbreakable: false,
                },
                Word::Text {
                    text: "\u{00A0}world".to_owned(),
                    bold: true,
                    italic: false,
                    glue: true,
                    unbreakable: true,
                },
            ],
            "the NBSP-led word must glue to the previous word, not add a second separator"
        );
    }

    #[test]
    fn glued_run_that_cannot_fit_still_breaks_the_line() {
        // Regression: two adjacently-styled runs with no whitespace between
        // them (e.g. `<strong>...</strong><em>...</em>`) were always kept on
        // one line regardless of size, because the fit check was skipped
        // entirely for glued words — each individually fit under
        // `max_width_pt`, but their combined width could run to nearly
        // double it, clipping the second run past the column/page boundary.
        let words = vec![
            Word::Text {
                text: "WWWW".to_owned(),
                bold: false,
                italic: false,
                glue: false,
                unbreakable: false,
            },
            Word::Text {
                text: "WWWW".to_owned(),
                bold: false,
                italic: false,
                glue: true,
                unbreakable: false,
            },
        ];
        let max_width_pt = 50.0;
        let word_width = text_width_pt("WWWW", 12.0, false);
        assert!(
            word_width <= max_width_pt,
            "fixture word must fit alone on a line"
        );
        assert!(
            word_width * 2.0 > max_width_pt,
            "fixture pair must not fit together on one line"
        );
        let lines = wrap(&words, max_width_pt, 12.0);
        assert_eq!(
            lines.len(),
            2,
            "the glued word must move to its own line rather than overflow"
        );
        assert_eq!(lines[0], vec![("WWWW".to_owned(), false, false, false)]);
        assert_eq!(
            lines[1],
            vec![("WWWW".to_owned(), false, false, false)],
            "the word that moved to a new line is no longer glued to anything on it"
        );
    }

    #[test]
    fn unbreakable_nbsp_pair_moves_together_when_it_does_not_fit() {
        // Regression: `Hello<strong>&nbsp;world</strong>` after earlier text
        // that leaves room for "Hello" but not the NBSP-glued "world" — the
        // overflow branch used to treat this exactly like ordinary glue
        // (`glued_run_that_cannot_fit_still_breaks_the_line` above), pushing
        // "Prefix Hello" together as a finished line and placing the
        // NBSP-led word alone on the next line — splitting the exact
        // boundary NBSP forbids a break at. An NBSP pair that doesn't fit
        // must move to the new line *together*, not split.
        let words = vec![
            Word::Text {
                text: "WWWW".to_owned(), // stands in for "Prefix"
                bold: false,
                italic: false,
                glue: false,
                unbreakable: false,
            },
            Word::Text {
                text: "WWWW".to_owned(), // stands in for "Hello"
                bold: false,
                italic: false,
                glue: false,
                unbreakable: false,
            },
            Word::Text {
                text: "WWWW".to_owned(), // stands in for NBSP-led "world"
                bold: false,
                italic: false,
                glue: true,
                unbreakable: true,
            },
        ];
        let word_width = text_width_pt("WWWW", 12.0, false);
        let space_w = text_width_pt(" ", 12.0, false);
        // Fits "Prefix Hello" (two words + one space) but not a third glued
        // "WWWW" on top of that; a fresh line fits the NBSP pair alone
        // (two words, no space between them).
        let max_width_pt = 2.0f32.mul_add(word_width, space_w) + 0.5;
        let lines = wrap(&words, max_width_pt, 12.0);
        assert_eq!(
            lines.len(),
            2,
            "the NBSP pair must move to a new line rather than splitting across two"
        );
        assert_eq!(
            lines[0],
            vec![("WWWW".to_owned(), false, false, false)],
            "only the unrelated prefix word stays on the first line"
        );
        assert_eq!(
            lines[1],
            vec![
                ("WWWW".to_owned(), false, false, false),
                ("WWWW".to_owned(), false, false, true),
            ],
            "the NBSP-glued pair must move together onto the second line"
        );
    }

    #[test]
    fn unbreakable_word_that_is_individually_oversized_stays_glued_to_its_predecessor() {
        // Regression: `Hello<strong>&nbsp;` followed by a long unbroken run
        // of characters is individually wider than a whole line on its
        // own. Fixed in two rounds:
        // 1. The oversized-token branch used to run *before* the
        //    unbreakable check, so it unconditionally flushed `current`
        //    ("Hello") as its own finished line (losing the glue to the
        //    NBSP-led word) and then character-split the oversized word
        //    with no notion of the NBSP boundary at all. Fixed by checking
        //    `unbreakable` first.
        // 2. That first fix then went too far the other way: it glued the
        //    *entire* oversized word onto "Hello" with no splitting at
        //    all, so the whole run rendered as one unsplit, unbounded
        //    token — overflowing and clipped, not merely spilling a
        //    little past the margin. The NBSP only forbids a break right
        //    at its own boundary; the rest of the run has no such
        //    constraint, so it's still character-split — just with its
        //    first chunk kept glued to "Hello", the same protected
        //    boundary as before.
        let words = vec![
            Word::Text {
                text: "Hello".to_owned(),
                bold: false,
                italic: false,
                glue: false,
                unbreakable: false,
            },
            Word::Text {
                text: format!("\u{00A0}{}", "A".repeat(100)),
                bold: true,
                italic: false,
                glue: true,
                unbreakable: true,
            },
        ];
        let max_width_pt = 495.0; // a typical paragraph content width
        let word_width = text_width_pt(&format!("\u{00A0}{}", "A".repeat(100)), 11.0, true);
        assert!(
            word_width > max_width_pt,
            "fixture word must be individually oversized"
        );
        let lines = wrap(&words, max_width_pt, 11.0);
        assert!(
            lines.len() > 1,
            "the oversized NBSP-led word must still be character-split across multiple \
             lines instead of left whole, got {lines:?}"
        );
        assert_eq!(
            lines[0][0],
            ("Hello".to_owned(), false, false, false),
            "\"Hello\" must not be flushed onto its own line ahead of the glued word"
        );
        assert!(
            lines[0][1].0.starts_with('\u{00A0}'),
            "the first chunk of the NBSP-led word must stay glued (with its NBSP intact) \
             right after \"Hello\", got {:?}",
            lines[0][1]
        );
        assert!(
            lines[0][1].3,
            "the first chunk of the NBSP-led word must still render glued (no rendered \
             space before it)"
        );
        // Every line, including the first (whose first chunk is sized
        // against the space actually remaining after "Hello", not the
        // full column — see `oversized_glued_word_first_chunk_is_sized_to_the_remaining_line_width`
        // for the regression this guards), must actually fit.
        for (i, line) in lines.iter().enumerate() {
            let line_width: f32 = line
                .iter()
                .map(|(text, bold, _, _)| text_width_pt(text, 11.0, *bold))
                .sum();
            assert!(
                line_width <= max_width_pt,
                "line {i} exceeds max_width_pt ({line_width} > {max_width_pt}): {line:?}"
            );
        }
        let rejoined: String = lines
            .iter()
            .flat_map(|line| line.iter().map(|(text, ..)| text.as_str()))
            .collect();
        assert_eq!(
            rejoined,
            format!("Hello\u{00A0}{}", "A".repeat(100)),
            "splitting into chunks must not drop or duplicate any characters"
        );
    }

    #[test]
    fn oversized_glued_word_first_chunk_is_sized_to_the_remaining_line_width() {
        // Regression: the character-split fix above sized the *first*
        // chunk against the full `max_width_pt`, the same as every later
        // chunk — but the first chunk is appended to a line that already
        // has other content on it, so sizing it against the full column
        // still overflowed by roughly however wide that existing content
        // was. 40 "A"s (~294pt at this font size) followed by an
        // NBSP-glued run of "<strong>&nbsp;" + 100 more "A"s used to
        // produce a first chunk sized to ~489pt — combined with the
        // 40-"A" prefix, well past the 495pt column, with only later
        // chunks actually respecting `max_width_pt`.
        let words = vec![
            Word::Text {
                text: "A".repeat(40),
                bold: false,
                italic: false,
                glue: false,
                unbreakable: false,
            },
            Word::Text {
                text: format!("\u{00A0}{}", "A".repeat(100)),
                bold: true,
                italic: false,
                glue: true,
                unbreakable: true,
            },
        ];
        let max_width_pt = 495.0;
        let lines = wrap(&words, max_width_pt, 11.0);
        for (i, line) in lines.iter().enumerate() {
            let line_width: f32 = line
                .iter()
                .map(|(text, bold, _, _)| text_width_pt(text, 11.0, *bold))
                .sum();
            assert!(
                line_width <= max_width_pt,
                "line {i} exceeds max_width_pt ({line_width} > {max_width_pt}): {line:?}"
            );
        }
        let rejoined: String = lines
            .iter()
            .flat_map(|line| line.iter().map(|(text, ..)| text.as_str()))
            .collect();
        assert_eq!(
            rejoined,
            format!("{}\u{00A0}{}", "A".repeat(40), "A".repeat(100)),
            "splitting into chunks must not drop or duplicate any characters"
        );
    }

    #[test]
    fn adjacent_spans_with_no_whitespace_render_with_no_space_between() {
        // Regression: "$" and a separately-styled "42.00" right next to it
        // (e.g. `$<strong>42.00</strong>`, this feature's own flagship
        // money-formatting example) used to always get a space inserted
        // between them by word-based layout, rendering "$ 42.00".
        let words = words_of(&[
            Span::Run {
                text: "$".to_owned(),
                bold: false,
                italic: false,
            },
            Span::Run {
                text: "42.00".to_owned(),
                bold: true,
                italic: false,
            },
        ]);
        let lines = wrap(&words, 1000.0, 12.0);
        assert_eq!(lines.len(), 1);
        assert_eq!(
            lines[0],
            vec![
                ("$".to_owned(), false, false, false),
                ("42.00".to_owned(), true, false, true),
            ]
        );
    }

    #[test]
    fn spans_separated_by_whitespace_still_get_a_space() {
        let words = words_of(&[
            Span::Run {
                text: "Total:".to_owned(),
                bold: false,
                italic: false,
            },
            Span::Run {
                text: " ".to_owned(),
                bold: false,
                italic: false,
            },
            Span::Run {
                text: "$42.00".to_owned(),
                bold: true,
                italic: false,
            },
        ]);
        let lines = wrap(&words, 1000.0, 12.0);
        assert_eq!(
            lines[0],
            vec![
                ("Total:".to_owned(), false, false, false),
                ("$42.00".to_owned(), true, false, false),
            ]
        );
    }

    #[test]
    fn flatten_blocks_groups_bare_text_as_implicit_paragraph() {
        let nodes = super::super::html::parse("hello <strong>world</strong>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        assert!(matches!(&blocks[0], Block::Paragraph(_)));
    }

    #[test]
    fn flatten_blocks_recognizes_headings_paragraphs_and_tables() {
        let nodes = super::super::html::parse(
            "<h1>Invoice</h1><p>Hello</p><table><tr><th>A</th></tr><tr><td>1</td></tr></table>",
        );
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 3);
        assert!(matches!(&blocks[0], Block::Heading(1, _)));
        assert!(matches!(&blocks[1], Block::Paragraph(_)));
        assert!(matches!(&blocks[2], Block::Table(rows) if rows.len() == 2));
    }

    #[test]
    fn table_caption_text_is_not_silently_dropped() {
        // Regression: `<caption>` (or any non-row table child) matched the
        // `extract_table_rows` catch-all with no fallback, discarding its
        // text — contradicting this renderer's "unknown tags still render
        // their text" contract.
        let nodes = super::super::html::parse(
            "<table><caption>Grand Total</caption><tr><td>1</td></tr></table>",
        );
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        let Block::Table(rows) = &blocks[0] else {
            panic!("expected a table block")
        };
        assert_eq!(rows.len(), 2, "caption becomes an extra row, not lost");
        let caption_text: String = rows[0]
            .cells
            .iter()
            .flat_map(|(spans, _)| spans)
            .map(|s| match s {
                Span::Run { text, .. } => text.clone(),
                Span::Break => String::new(),
            })
            .collect();
        assert_eq!(caption_text, "Grand Total");
    }

    #[test]
    fn unknown_wrapper_tags_pass_through_transparently() {
        let nodes = super::super::html::parse(r#"<div class="card"><span>hi</span></div>"#);
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        assert!(
            matches!(&blocks[0], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "hi".to_owned(), bold: false, italic: false,
            }])
        );
    }

    #[test]
    fn div_wrapper_preserves_nested_block_structure() {
        // Regression: `<div>` used to flatten every descendant through
        // `inline_spans` into one paragraph, merging a heading and two
        // paragraphs into a single unbroken run of text ("TitleFirstSecond")
        // — exactly the "one div wraps the whole page body" shape a typical
        // Maud layout function produces.
        let nodes = super::super::html::parse("<div><h1>Title</h1><p>First</p><p>Second</p></div>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(
            blocks.len(),
            3,
            "expected 3 separate blocks, got {blocks:?}"
        );
        assert!(
            matches!(&blocks[0], Block::Heading(1, spans) if spans == &[Span::Run {
                text: "Title".to_owned(), bold: true, italic: false,
            }])
        );
        assert!(
            matches!(&blocks[1], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "First".to_owned(), bold: false, italic: false,
            }])
        );
        assert!(
            matches!(&blocks[2], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "Second".to_owned(), bold: false, italic: false,
            }])
        );
    }

    #[test]
    fn blockquote_wrapper_preserves_nested_paragraph() {
        let nodes = super::super::html::parse("<blockquote><p>Quote text</p></blockquote>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        assert!(
            matches!(&blocks[0], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "Quote text".to_owned(), bold: false, italic: false,
            }])
        );
    }

    #[test]
    fn semantic_sectioning_elements_keep_adjacent_blocks_separate() {
        // Regression: `section`/`article`/`main`/`header`/`footer` weren't
        // in the "wraps other block elements" arm alongside `div`, so they
        // fell through to the generic transparent-passthrough case — two
        // adjacent `<section>`s of loose text accumulated into the same
        // pending paragraph with no separator at all.
        let nodes = super::super::html::parse(
            "<main><section>Summary</section><section>Details</section></main>",
        );
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(
            blocks.len(),
            2,
            "expected 2 separate paragraphs, got {blocks:?}"
        );
        assert!(
            matches!(&blocks[0], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "Summary".to_owned(), bold: false, italic: false,
            }])
        );
        assert!(
            matches!(&blocks[1], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "Details".to_owned(), bold: false, italic: false,
            }])
        );
    }

    #[test]
    fn nav_and_aside_keep_adjacent_blocks_separate() {
        // Same bug as `semantic_sectioning_elements_keep_adjacent_blocks_separate`,
        // reported again for `nav`/`aside` after the first fix.
        let nodes = super::super::html::parse("<aside>Summary</aside><aside>Details</aside>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(
            blocks.len(),
            2,
            "expected 2 separate paragraphs, got {blocks:?}"
        );
        assert!(
            matches!(&blocks[0], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "Summary".to_owned(), bold: false, italic: false,
            }])
        );
        assert!(
            matches!(&blocks[1], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "Details".to_owned(), bold: false, italic: false,
            }])
        );
    }

    #[test]
    fn list_item_with_nested_paragraphs_keeps_them_separate() {
        // Regression: `<li>`'s content goes through `inline_spans`, which
        // had no notion of a block boundary — `<li><p>First</p><p>Second</p></li>`
        // rendered "FirstSecond" with no separator at all (worse than plain
        // whitespace collapsing: there wasn't even a space).
        let nodes = super::super::html::parse("<ul><li><p>First</p><p>Second</p></li></ul>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        let Block::ListItem { spans, .. } = &blocks[0] else {
            panic!("expected a list item block");
        };
        assert_eq!(
            spans,
            &[
                Span::Run {
                    text: "First".to_owned(),
                    bold: false,
                    italic: false,
                },
                Span::Break,
                Span::Run {
                    text: "Second".to_owned(),
                    bold: false,
                    italic: false,
                },
            ],
            "nested paragraphs must be line-break separated, with no trailing break"
        );
    }

    #[test]
    fn hr_inside_a_list_item_still_separates_adjacent_text() {
        // Regression: `<hr>` is a void element (no children), so it wasn't
        // in `is_block_boundary_in_inline_context` and fell through to the
        // generic transparent-wrapper case in `inline_spans` — recursing
        // into its (empty) children produced nothing, and no break was
        // inserted either, so `<li>Before<hr>After</li>` rendered
        // "BeforeAfter" with the rule silently vanishing.
        let nodes = super::super::html::parse("<ul><li>Before<hr>After</li></ul>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        let Block::ListItem { spans, .. } = &blocks[0] else {
            panic!("expected a list item block");
        };
        assert_eq!(
            spans,
            &[
                Span::Run {
                    text: "Before".to_owned(),
                    bold: false,
                    italic: false,
                },
                Span::Break,
                Span::Run {
                    text: "After".to_owned(),
                    bold: false,
                    italic: false,
                },
            ],
            "hr must still separate the text around it, not vanish and glue them together"
        );
    }

    #[test]
    fn nested_list_inside_a_list_item_keeps_its_markers() {
        // Regression: `<li>`'s content goes through `inline_spans`, which had
        // no explicit handling for a nested `<ul>`/`<ol>` — it fell through
        // to the generic transparent-wrapper case, so `<ul><li>Parent<ul><li>Child</li></ul></li></ul>`
        // reduced the inner `<li>` to a bare line break plus text, with no
        // bullet and no list semantics at all.
        let nodes = super::super::html::parse("<ul><li>Parent<ul><li>Child</li></ul></li></ul>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        let Block::ListItem { marker, spans } = &blocks[0] else {
            panic!("expected a list item block");
        };
        assert_eq!(marker, "\u{2022}");
        assert_eq!(
            spans,
            &[
                Span::Run {
                    text: "Parent".to_owned(),
                    bold: false,
                    italic: false,
                },
                Span::Break,
                Span::Run {
                    text: "\u{2022} ".to_owned(),
                    bold: false,
                    italic: false,
                },
                Span::Run {
                    text: "Child".to_owned(),
                    bold: false,
                    italic: false,
                },
            ],
            "the nested item must keep its own bullet marker instead of losing all list semantics"
        );
    }

    #[test]
    fn list_nested_inside_a_table_header_cell_stays_bold() {
        // Regression: `inline_spans`'s `"ul"`/`"ol"` branch called
        // `inline_list_items` without passing through the ambient
        // `bold`/`italic` it had just been called with — so
        // `<th><ul><li>Header</li></ul></th>`, where `extract_table_rows`
        // starts `inline_spans` with `bold: true` for a `<th>` cell, lost
        // that bold styling for both the list's marker and its item text,
        // even though the same content would stay bold if it weren't
        // wrapped in a list.
        let nodes =
            super::super::html::parse("<table><tr><th><ul><li>Header</li></ul></th></tr></table>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        let Block::Table(rows) = &blocks[0] else {
            panic!("expected a table block");
        };
        assert_eq!(rows.len(), 1);
        let (spans, is_header) = &rows[0].cells[0];
        assert!(is_header);
        assert_eq!(
            spans,
            &[
                Span::Run {
                    text: "\u{2022} ".to_owned(),
                    bold: true,
                    italic: false,
                },
                Span::Run {
                    text: "Header".to_owned(),
                    bold: true,
                    italic: false,
                },
            ],
            "both the list marker and its item content must stay bold inside a <th>, got {spans:?}"
        );
    }

    #[test]
    fn nested_list_item_marker_stays_beside_paragraph_wrapped_content() {
        // Regression: `inline_list_items` pushes the marker `Run` directly
        // into `out`, then calls `inline_spans` for the item's content —
        // when that content starts with a block boundary (here `<p>`),
        // `inline_spans` pushes a break *before* it, which is correct when
        // something precedes it but here lands directly between the
        // marker and its own first line, splitting `<li><p>Child</p></li>`
        // into the marker alone on one line and "Child" on the next.
        let nodes =
            super::super::html::parse("<ul><li>Parent<ul><li><p>Child</p></li></ul></li></ul>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        let Block::ListItem { marker, spans } = &blocks[0] else {
            panic!("expected a list item block");
        };
        assert_eq!(marker, "\u{2022}");
        assert_eq!(
            spans,
            &[
                Span::Run {
                    text: "Parent".to_owned(),
                    bold: false,
                    italic: false,
                },
                Span::Break,
                Span::Run {
                    text: "\u{2022} ".to_owned(),
                    bold: false,
                    italic: false,
                },
                Span::Run {
                    text: "Child".to_owned(),
                    bold: false,
                    italic: false,
                },
            ],
            "the nested marker must stay on the same line as its paragraph-wrapped content"
        );
    }

    #[test]
    fn table_cell_with_nested_paragraphs_keeps_them_separate() {
        // Same bug as `list_item_with_nested_paragraphs_keeps_them_separate`,
        // reported for `<td>`/`<th>` cell content.
        let nodes = super::super::html::parse("<table><tr><td><p>A</p><p>B</p></td></tr></table>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        let Block::Table(rows) = &blocks[0] else {
            panic!("expected a table block");
        };
        assert_eq!(rows.len(), 1);
        let (spans, is_header) = &rows[0].cells[0];
        assert!(!is_header);
        assert_eq!(
            spans,
            &[
                Span::Run {
                    text: "A".to_owned(),
                    bold: false,
                    italic: false,
                },
                Span::Break,
                Span::Run {
                    text: "B".to_owned(),
                    bold: false,
                    italic: false,
                },
            ],
            "nested paragraphs inside a cell must be line-break separated, with no trailing break"
        );
    }

    #[test]
    fn nested_table_inside_a_cell_keeps_its_rows_and_cells_separate() {
        // Regression: a `<table>` nested inside a `<td>` has no dedicated
        // `Block::Table` path (only a top-level table gets one) — its inner
        // `table`/`tr`/`td` nodes used to fall through `inline_spans`'s
        // generic transparent-wrapper case, so adjacent cells' text glued
        // directly together with no separator: `<td>A</td><td>B</td>`
        // rendered as "AB".
        let nodes = super::super::html::parse(
            "<table><tr><td><table><tr><td>A</td><td>B</td></tr></table></td></tr></table>",
        );
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        let Block::Table(rows) = &blocks[0] else {
            panic!("expected a table block");
        };
        assert_eq!(rows.len(), 1);
        let (spans, is_header) = &rows[0].cells[0];
        assert!(!is_header);
        assert_eq!(
            spans,
            &[
                Span::Run {
                    text: "A".to_owned(),
                    bold: false,
                    italic: false,
                },
                Span::Break,
                Span::Run {
                    text: "B".to_owned(),
                    bold: false,
                    italic: false,
                },
            ],
            "the nested table's cells must be line-break separated, not glued into \"AB\""
        );
    }

    #[test]
    fn omitted_p_close_before_a_table_still_produces_a_real_table_block() {
        // Regression: without an implied close, `<p>Intro<table>...</table>`
        // nested the table *inside* the still-open `<p>`, so `flatten_blocks`'s
        // `"p"` arm sent the whole thing through `inline_spans` — which has
        // no notion of a table — flattening its rows/cells into bare inline
        // text ("IntroAB") instead of a real `Block::Table`.
        let nodes = super::super::html::parse(
            "<p>Intro</p><table><tr><td>A</td><td>B</td></tr></table><p>After</p>",
        );
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(
            blocks.len(),
            3,
            "expected 3 separate blocks (p, table, p), got {blocks:?}"
        );
        assert!(
            matches!(&blocks[0], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "Intro".to_owned(), bold: false, italic: false,
            }])
        );
        let Block::Table(rows) = &blocks[1] else {
            panic!("expected a real table block, got {:?}", blocks[1]);
        };
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].cells.len(), 2, "expected two separate cells");
        assert!(
            matches!(&blocks[2], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "After".to_owned(), bold: false, italic: false,
            }])
        );
    }

    #[test]
    fn omitted_head_close_before_body_does_not_discard_the_whole_document() {
        // Regression: without an implied close, `<body>` nested *inside* the
        // still-open `<head>` — and `head` is in `is_non_rendered`, so its
        // entire subtree (which would now include `<body>`) was discarded
        // wholesale, dropping the whole visible document, not just one
        // element's structure.
        let nodes = super::super::html::parse(
            "<html><head><title>X</title><body><p>Visible</p></body></html>",
        );
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(
            blocks.len(),
            1,
            "expected the <body>'s <p> to survive, got {blocks:?}"
        );
        assert!(
            matches!(&blocks[0], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "Visible".to_owned(), bold: false, italic: false,
            }])
        );
    }

    #[test]
    fn description_list_terms_and_values_keep_their_own_blocks() {
        // Regression: `<dl>`/`<dt>`/`<dd>` (as emitted by scaffold detail
        // views — e.g. a `property_list` widget) fell through the generic
        // "unknown tag = transparent passthrough" rule with no block
        // separation at all, so `<dl><dt>Title</dt><dd>My Post</dd>
        // <dt>Published</dt><dd>true</dd></dl>` rendered as one glued run,
        // "TitleMy PostPublishedtrue", instead of four separate rows.
        let nodes = super::super::html::parse(
            "<dl><dt>Title</dt><dd>My Post</dd><dt>Published</dt><dd>true</dd></dl>",
        );
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        let texts: Vec<String> = blocks
            .iter()
            .map(|block| {
                let Block::Paragraph(spans) = block else {
                    panic!("expected a paragraph block, got {block:?}")
                };
                spans
                    .iter()
                    .map(|span| match span {
                        Span::Run { text, .. } => text.as_str(),
                        Span::Break => "",
                    })
                    .collect()
            })
            .collect();
        assert_eq!(texts, vec!["Title", "My Post", "Published", "true"]);
    }

    #[test]
    fn description_list_inside_a_transparent_wrapper_still_keeps_blocks_separate() {
        // Regression: `flatten_into_pending` (the path a `<dl>` takes when
        // nested inside an unrecognized transparent wrapper, e.g.
        // `<span><dl>...</dl></span>`) keeps its own separate block-tag
        // list rather than sharing `flatten_blocks`'s — it was missed when
        // `dl`/`dt`/`dd` were added there, so this path still glued terms
        // and values together despite the top-level fix.
        let nodes =
            super::super::html::parse("<span><dl><dt>Title</dt><dd>My Post</dd></dl></span>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        let texts: Vec<String> = blocks
            .iter()
            .map(|block| {
                let Block::Paragraph(spans) = block else {
                    panic!("expected a paragraph block, got {block:?}")
                };
                spans
                    .iter()
                    .map(|span| match span {
                        Span::Run { text, .. } => text.as_str(),
                        Span::Break => "",
                    })
                    .collect()
            })
            .collect();
        assert_eq!(texts, vec!["Title", "My Post"]);
    }

    #[test]
    fn whitespace_between_loose_inline_elements_is_not_dropped() {
        // Regression: a whitespace-only text node separating two loose
        // inline elements used to be filtered out entirely (treated the
        // same as insignificant whitespace between block tags), so
        // `words_of` never saw a boundary and glued the two words together
        // ("Helloworld" instead of "Hello world").
        let nodes = super::super::html::parse("<span>Hello</span> <span>world</span>");
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        let Block::Paragraph(spans) = &blocks[0] else {
            panic!("expected a paragraph block")
        };
        let words = words_of(spans);
        assert_eq!(
            words,
            vec![
                Word::Text {
                    text: "Hello".to_owned(),
                    bold: false,
                    italic: false,
                    glue: false,
                    unbreakable: false,
                },
                Word::Text {
                    text: "world".to_owned(),
                    bold: false,
                    italic: false,
                    glue: false,
                    unbreakable: false,
                },
            ],
            "the space between the two spans must survive as a real word boundary"
        );
    }

    #[test]
    fn script_and_style_content_is_never_rendered() {
        // Regression: `<script>`/`<style>` (and `<head>`/`<title>`) matched
        // the generic "unrecognized tag = transparent passthrough" rule,
        // so a full server-rendered page's inline CSS/JS source text was
        // emitted into the PDF as visible content.
        let nodes = super::super::html::parse(
            "<head><title>Ignored</title><style>body { color: red; }</style></head>\
             <script>alert('hi');</script><p>Visible</p>",
        );
        let mut blocks = Vec::new();
        flatten_blocks(&nodes, 0, &mut blocks);
        assert_eq!(blocks.len(), 1);
        assert!(
            matches!(&blocks[0], Block::Paragraph(spans) if spans == &[Span::Run {
                text: "Visible".to_owned(), bold: false, italic: false,
            }])
        );
    }

    #[test]
    fn render_pages_produces_at_least_one_page_for_empty_input() {
        let pages = render_pages("");
        assert_eq!(pages.len(), 1);
    }

    #[test]
    fn deeply_nested_wrapper_tags_do_not_overflow_the_stack() {
        let mut html = String::new();
        for _ in 0..50_000 {
            html.push_str("<span>");
        }
        html.push_str("hi");
        for _ in 0..50_000 {
            html.push_str("</span>");
        }
        // Must not panic/overflow; content beyond MAX_DEPTH is allowed to be
        // dropped (defense-in-depth against adversarial input), so this only
        // asserts it completes and still produces at least one page.
        let pages = render_pages(&html);
        assert!(!pages.is_empty());
    }

    #[test]
    fn ordered_list_marker_wide_enough_to_overlap_the_fixed_indent_gets_more_room() {
        // Regression: the indent between a list marker and its item's
        // content was a fixed 16pt, which fits every bullet/low-numbered
        // marker comfortably ("•", "1." .. "9.") but not an ordered list
        // marker whose digits keep growing — "100." alone is already
        // ~21pt at 11pt Helvetica, wider than the indent, so content wrapped
        // at a fixed 16pt started underneath the marker's own text instead
        // of after it.
        let mut writer = Writer::new();
        let marker = "100.".to_owned();
        writer.draw_block(&Block::ListItem {
            marker: marker.clone(),
            spans: vec![Span::Run {
                text: "Item".to_owned(),
                bold: false,
                italic: false,
            }],
        });
        let cursor_xs: Vec<f32> = writer
            .ops
            .iter()
            .filter_map(|op| match op {
                Op::SetTextCursor { pos } => Some(pos.x.0),
                _ => None,
            })
            .collect();
        assert_eq!(
            cursor_xs.len(),
            2,
            "expected one cursor position for the marker and one for the item's text"
        );
        let (marker_x, content_x) = (cursor_xs[0], cursor_xs[1]);
        let marker_width = text_width_pt(&marker, 11.0, false);
        assert!(
            content_x - marker_x >= marker_width,
            "content (x={content_x}) must start at or past the end of the marker \
             (x={marker_x} + width={marker_width}), not overlap it"
        );
    }

    #[test]
    fn empty_list_item_still_reserves_a_full_line() {
        // Regression: `draw_lines` only advances `y_from_top` per *line it
        // draws* — an empty item (`<li></li>`, or one whose only content was
        // skipped) produces zero wrapped lines, so only the fixed 4pt
        // spacer after it separated its marker from the next item's,
        // placing the two markers almost on top of each other instead of on
        // their own lines.
        let mut writer = Writer::new();
        writer.draw_block(&Block::ListItem {
            marker: "\u{2022}".to_owned(),
            spans: vec![],
        });
        let advance = writer.y_from_top;
        assert!(
            advance >= 14.5,
            "an empty list item must still advance a full line's height, got {advance}"
        );
    }

    #[test]
    fn render_pages_paginates_long_content() {
        use std::fmt::Write as _;

        let mut html = String::new();
        for i in 0..200 {
            let _ = write!(html, "<p>Line number {i}</p>");
        }
        let pages = render_pages(&html);
        assert!(pages.len() > 1, "expected multiple pages for long content");
    }
}