yog-book 0.65.0

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

use std::collections::{BTreeMap, HashMap};
use yog_gfx::GfxContext;
use yog_ui::{Align, FlexDir, Stretch, UiRoot, widget};

use crate::state::BookViewState;
use crate::theme::BookTheme;
use crate::{Book, BookPage};

// Patchouli-compatible book texture layout (512×256 sprite sheet).
// UV coordinates are in pixels on a 512×256 sheet.
// The full open-book background occupies 272×180 at UV (0,0).
pub const BOOK_TEX_W: f32 = 512.0;
pub const BOOK_TEX_H: f32 = 256.0;
// Open-book dimensions in texture-space
pub const BK_W: f32 = 272.0;
pub const BK_H: f32 = 180.0;
// Per-page dimensions and offsets (in book-local coords)
pub const PAGE_W: f32 = 116.0;
pub const PAGE_H: f32 = 156.0;
pub const TOP_PAD: f32 = 18.0; // vertical space above page text area
pub const LEFT_X: f32 = 15.0; // left page X inside book
pub const RIGHT_X: f32 = 141.0; // right page X inside book
// Separator strip UV origin on the sprite sheet
pub const SEP_U: f32 = 140.0;
pub const SEP_V: f32 = 180.0;
pub const SEP_W: f32 = 110.0;
pub const SEP_H: f32 = 3.0;
/// Room (GUI px) the book keeps free around it before it scales down.
const SCREEN_MARGIN: f32 = 16.0;
/// Smallest the book scales on a tiny screen.
const MIN_SCALE: f32 = 0.4;

// ── Embedded textures ─────────────────────────────────────────────────────────

/// The book's sprite sheet (cover, pages, separators, nameplate).
pub static BOOK_PNG: &[u8] = include_bytes!("../assets/book_brown.png");
/// The crafting-grid sprite sheet.
pub static CRAFTING_PNG: &[u8] = include_bytes!("../assets/crafting.png");
/// The book's own words (`yog.book.*`) per language, as the loader's jars
/// ship them in `assets/yog/lang/` (for hosts without them, like Yog-IDLE).
pub static LANG: &[(&str, &str)] = &[
    ("en_us", include_str!("../assets/lang/en_us.json")),
    ("ru_ru", include_str!("../assets/lang/ru_ru.json")),
];
/// The image source the book draws [`BOOK_PNG`] as: the loader ships it
/// as `assets/yog/textures/gui/book/book.png` (Yog-IDLE resolves it to
/// the bytes).
pub const BOOK_SHEET: &str = "yog:gui/book/book";
/// The image source the book draws [`CRAFTING_PNG`] as.
pub const CRAFTING_SHEET: &str = "yog:gui/book/crafting";

// ── Background sprite (texture blit, drawn before yog-ui) ────────────────────

#[derive(Clone, PartialEq)]
pub(crate) enum SpriteSheet {
    Book,
    Crafting,
    /// Any image source (a recipe layout's).
    Image(String),
}

/// A subrect blit from one of the embedded sprite sheets, drawn before yog-ui.
#[derive(Clone)]
pub(crate) struct BgSprite {
    pub sheet: SpriteSheet,
    /// Source rect in pixels on the sheet.
    pub u: f32,
    pub v: f32,
    pub uw: f32,
    pub uh: f32,
    /// Destination on screen.
    pub x: f32,
    pub y: f32,
    pub w: f32,
    pub h: f32,
}

// ── Pending overlay draw commands ─────────────────────────────────────────────

/// Draws a mod's picture (`BookPage::Drawn`): `(ctx, drawer, data, [x, y, w, h])`.
pub type PageDrawer<'a> = &'a mut dyn FnMut(&GfxContext, &str, &yog_data::Value, [f32; 4]);

#[derive(Clone)]
pub(crate) enum OverlayCmd {
    /// A mod's picture: its drawer (`BookPage::Drawn`) draws `data` in the box.
    Drawn {
        drawer: String,
        data: yog_data::Value,
        x: f32,
        y: f32,
        w: f32,
        h: f32,
    },
    /// One of `items` at a time, a new one every second (an ingredient's
    /// alternatives); tags (`#…`) are skipped.
    McItems {
        items: Vec<String>,
        x: f32,
        y: f32,
        w: f32,
        h: f32,
    },
    /// Blocks in 3D, turning.
    Blocks {
        blocks: Vec<((i32, i32, i32), String)>,
        x: f32,
        y: f32,
        w: f32,
        h: f32,
    },
    /// A living entity standing in the box.
    Entity {
        entity: String,
        x: f32,
        y: f32,
        w: f32,
        h: f32,
    },
    /// MC default-font text rendered via draw2d (e.g. nameplate title/subtitle).
    McText {
        text: String,
        x: f32,
        y: f32,
        color: u32,
    },
    /// Item icon rendered through our GL pipeline from an MC-managed texture.
    McItem {
        item_id: String,
        x: f32,
        y: f32,
        w: f32,
        h: f32,
    },
    /// Flat texture icon blitted as-is (16×16), for icon strings that name a
    /// texture resource directly rather than an item — matches Patchouli's
    /// `BookIcon.from`: any icon string ending in `.png` is a raw texture,
    /// everything else is parsed as an item stack.
    McTexture {
        path: String,
        x: f32,
        y: f32,
        w: f32,
        h: f32,
    },
}

/// Push a book-author-supplied icon (category/entry icon field) as the right
/// overlay kind. Matches Patchouli's `BookIcon.from(String)`: `.png` → raw
/// texture blit, anything else → item stack render.
fn push_icon(overlays: &mut Vec<OverlayCmd>, icon: &str, x: f32, y: f32, w: f32, h: f32) {
    if icon.ends_with(".png") {
        overlays.push(OverlayCmd::McTexture {
            path: icon.to_string(),
            x,
            y,
            w,
            h,
        });
    } else {
        overlays.push(OverlayCmd::McItem {
            item_id: icon.to_string(),
            x,
            y,
            w,
            h,
        });
    }
}

// ── Recipe visuals (parsed from registered recipe JSON) ───────────────────────

/// A recipe as a book shows it: its kind (which [`crate::layout`] draws
/// it), each slot's ingredients (each one's alternatives; empty: none),
/// result and values.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct RecipeVis {
    pub kind: String,
    pub slots: BTreeMap<String, Vec<Vec<String>>>,
    pub output: String,
    pub count: u32,
    /// `time`, `experience`, a mod kind's `values` — for a layout's texts.
    pub values: BTreeMap<String, String>,
}

/// An ingredient in Yog's recipe format: an id, a `#tag`, or an array of
/// those (any of them).
fn ingredient(v: &yog_data::Value) -> Vec<String> {
    use yog_data::Value;
    match v {
        Value::Str(s) => vec![s.clone()],
        Value::Ref(r) => vec![r.id.clone()],
        Value::Tag(r) => vec![format!("#{}", r.id)],
        Value::List(a) => a.iter().flat_map(ingredient).collect(),
        _ => Vec::new(),
    }
}

/// A recipe in Yog's own format (what a `.yrecipe` says, ids resolved —
/// see `yog_registry::Recipe`), as the book shows it.
fn parse_recipe(v: &yog_data::Value) -> Option<RecipeVis> {
    use yog_data::Value;
    let kind = v.get("type")?.as_str()?.to_owned();
    let output = match v.get("result")? {
        Value::Ref(r) => r.id.clone(),
        r => r.as_str()?.to_owned(),
    };
    let count = v.get("count").and_then(|c| c.as_i64()).unwrap_or(1).max(0) as u32;
    let mut slots = BTreeMap::new();
    let mut values = BTreeMap::new();
    let text = |x: &Value| match x {
        Value::Int(i) => i.to_string(),
        Value::Float(f) => f.to_string(),
        Value::Bool(b) => b.to_string(),
        x => x.as_str().map(str::to_owned).unwrap_or_default(),
    };
    match kind.as_str() {
        "shaped" => {
            // The pattern's cells by position on the 3×3 grid.
            let key = v.get("key")?.as_map()?;
            let mut grid = vec![Vec::new(); 9];
            for (r, row) in v.get("pattern")?.as_list()?.iter().filter_map(|p| p.as_str()).take(3).enumerate() {
                let mut buf = [0u8; 4];
                for (c, ch) in row.chars().take(3).enumerate() {
                    grid[r * 3 + c] = key.get(ch.encode_utf8(&mut buf)).map(ingredient).unwrap_or_default();
                }
            }
            slots.insert("grid".into(), grid);
        }
        "shapeless" => {
            slots.insert("grid".into(), v.get("ingredients")?.as_list()?.iter().map(ingredient).collect());
        }
        "smelting" | "blasting" | "smoking" | "campfire_cooking" | "stonecutting" => {
            slots.insert("input".into(), vec![ingredient(v.get("ingredient")?)]);
            let default_time = match kind.as_str() {
                "smelting" => Some(200),
                "blasting" | "smoking" => Some(100),
                "campfire_cooking" => Some(600),
                _ => None,
            };
            if let Some(t) = v.get("cook_time").and_then(|t| t.as_i64()).or(default_time) {
                values.insert("time".into(), t.to_string());
            }
            if let Some(x) = v.get("experience") {
                values.insert("experience".into(), text(x));
            }
        }
        "smithing" => {
            for part in ["template", "base", "addition"] {
                slots.insert(part.into(), vec![v.get(part).map(ingredient).unwrap_or_default()]);
            }
        }
        _ => {
            // A mod's own kind: named slots, values.
            for (name, list) in v.get("slots").and_then(|s| s.as_map()).into_iter().flat_map(|m| m.iter()) {
                slots.insert(name.to_string(), list.as_list().into_iter().flatten().map(ingredient).collect());
            }
            for (name, x) in v.get("values").and_then(|s| s.as_map()).into_iter().flat_map(|m| m.iter()) {
                values.insert(name.to_string(), text(x));
            }
        }
    }
    Some(RecipeVis { kind, slots, output, count, values })
}

/// Normalize icon ids like "yog:item/ruby" / "yog:block/x" to registry item
/// ids ("yog:ruby") accepted by the MC item renderer.
fn normalize_item_id(id: &str) -> String {
    let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
    let name = path
        .trim_start_matches("item/")
        .trim_start_matches("block/");
    format!("{ns}:{name}")
}

/// The image source of a book's sheet: its own (`book_texture`, a sheet
/// laid out as [`BOOK_PNG`]; `ns:textures/x.png` and `ns:x` alike) or Yog's.
fn book_sheet(texture: &str) -> String {
    let t = texture.trim();
    if t.is_empty() || t == "yog:gui/book" {
        return BOOK_SHEET.to_string();
    }
    let (ns, path) = t.split_once(':').unwrap_or(("minecraft", t));
    let path = path.strip_prefix("textures/").unwrap_or(path);
    format!("{ns}:{}", path.strip_suffix(".png").unwrap_or(path))
}

/// The game's translations: item names and the book's own words (set with the translator).
static ITEM_NAMES: std::sync::RwLock<Option<Translator>> = std::sync::RwLock::new(None);

type Translator = fn(&str) -> Option<String>;

/// The book's own word `yog.book.<key>` in the game's language (`%s`:
/// `arg`), else English.
fn word(key: &str, arg: &str) -> String {
    let k = format!("yog.book.{key}");
    let tr = *ITEM_NAMES.read().unwrap_or_else(|e| e.into_inner());
    let text = tr.and_then(|tr| tr(&k)).filter(|t| *t != k).or_else(|| {
        // English, from the shipped file.
        static EN: std::sync::LazyLock<HashMap<String, String>> =
            std::sync::LazyLock::new(|| serde_json::from_str(LANG[0].1).unwrap_or_default());
        EN.get(&k).cloned()
    });
    let text = text.unwrap_or(k);
    text.replace("%s", arg)
}

/// "staff/oak" → "Oak Staff".
fn name_from_path(path: &str) -> String {
    path.rsplit('/')
        .flat_map(|seg| seg.split('_'))
        .filter(|w| !w.is_empty())
        .map(|w| {
            let mut c = w.chars();
            match c.next() {
                Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// `n` as the game's language counts editions: "1st" in English (its
/// `yog.book.ordinals`), plain "1" where it has none.
fn ordinal(n: u32) -> String {
    let suffixes = word("ordinals", "");
    let s: Vec<&str> = suffixes.split_whitespace().collect();
    if s.len() < 4 {
        return n.to_string();
    }
    let i = match (n % 100, n % 10) {
        (11..=13, _) => 0,
        (_, 1) => 1,
        (_, 2) => 2,
        (_, 3) => 3,
        _ => 0,
    };
    format!("{n}{}", s[i])
}

/// An entity's name: the game's (`entity.<ns>.<path>`), else one made
/// from its id.
fn entity_name(id: &str) -> String {
    let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
    let k = format!("entity.{ns}.{}", path.replace('/', "."));
    let tr = *ITEM_NAMES.read().unwrap_or_else(|e| e.into_inner());
    tr.and_then(|tr| tr(&k))
        .filter(|t| *t != k)
        .unwrap_or_else(|| name_from_path(path))
}

/// An item's name: the game's (`item.<ns>.<path>`, else `block.…`), else
/// one made from its id — "hexcasting:staff/oak" → "Oak Staff".
fn pretty_item_name(id: &str) -> String {
    let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
    if let Some(tr) = *ITEM_NAMES.read().unwrap_or_else(|e| e.into_inner()) {
        let key = path.replace('/', ".");
        for kind in ["item", "block"] {
            let k = format!("{kind}.{ns}.{key}");
            if let Some(name) = tr(&k).filter(|n| *n != k) {
                return name;
            }
        }
    }
    name_from_path(path)
}

// ── BookRenderer ──────────────────────────────────────────────────────────────

pub struct BookRenderer {
    pub book: Book,
    pub state: BookViewState,
    pub theme: BookTheme,
    recipes: HashMap<String, RecipeVis>,
    /// Per entry: which page as written each shown page came from.
    origins: HashMap<String, Vec<usize>>,
    /// The book as written (localized), before its text flowed.
    written: Book,
    /// Flowed with the host's own text metrics (else estimated ones).
    measured: bool,
    /// When the renderer was made: what animations count from.
    start: std::time::Instant,
    pub ui: Option<UiRoot>,
    bg_sprites: Vec<BgSprite>,
    overlays: Vec<OverlayCmd>,
    dirty: bool,
    last_sw: f32,
    last_sh: f32,
    /// i18n books: the untranslated book, the translator and the language
    /// probe (the book name's text) the shown book was made for.
    source: Option<Book>,
    translator: Option<fn(&str) -> Option<String>>,
    probe: Option<Option<String>>,
}

impl BookRenderer {
    pub fn new(book: Book) -> Self {
        let theme = BookTheme::default().with_nameplate(&book.nameplate_color);
        let written = styled(&book);
        let (flowed, origins) = flow_traced(written.clone());
        // Translated, it's flowed again from the book as written: flowing
        // its keys would split them.
        let source = book.i18n.then_some(book);
        let book = flowed;
        Self {
            book,
            origins,
            written,
            measured: false,
            start: std::time::Instant::now(),
            state: BookViewState::default(),
            theme,
            recipes: HashMap::new(),
            ui: None,
            bg_sprites: Vec::new(),
            overlays: Vec::new(),
            dirty: true,
            last_sw: 0.0,
            last_sh: 0.0,
            translator: None,
            probe: None,
            source,
        }
    }

    /// The book it draws (its long texts flowed onto more pages).
    pub fn book(&self) -> &Book {
        &self.book
    }

    /// The game's translations: items' names in recipe titles, and, for
    /// [`Book::i18n`] books, the book's texts — translation keys, looked up
    /// with `tr` (unknown keys stay as they are) and re-looked up whenever
    /// the language changes.
    pub fn set_translator(&mut self, tr: fn(&str) -> Option<String>) {
        *ITEM_NAMES.write().unwrap_or_else(|e| e.into_inner()) = Some(tr);
        if self.book.i18n {
            self.translator = Some(tr);
            self.probe = None;
        }
    }

    /// Re-translates the book when the language changed since last time.
    fn localize(&mut self) {
        let (Some(src), Some(tr)) = (&self.source, self.translator) else {
            return;
        };
        let probe = Some(tr(&src.name));
        if probe == self.probe {
            return;
        }
        let accent = src.accent.clone();
        self.written = src.localized(|k| {
            crate::markup::resolve(&tr(k).unwrap_or_else(|| k.to_string()), &accent)
        });
        (self.book, self.origins) = flow_traced(self.written.clone());
        self.probe = probe;
        self.dirty = true;
    }

    pub fn handle_event(&mut self, ev: &str) {
        if self.state.handle(ev, &self.book) {
            self.dirty = true;
        }
    }

    /// Register a recipe (Yog's recipe, as Yog Data) so recipe pages can
    /// render it visually. Unknown recipe types are ignored.
    pub fn add_recipe(&mut self, id: impl Into<String>, recipe: &yog_data::Value) {
        if let Some(vis) = parse_recipe(recipe) {
            self.recipes.insert(id.into(), vis);
            self.dirty = true;
        }
    }

    /// Lays the book out for a `sw`×`sh` screen (when something changed);
    /// the book's rect.
    fn prepare(&mut self, sw: f32, sh: f32) -> (f32, f32, f32, f32) {
        // Render at Patchouli-native size (272×180 GUI pixels). Scale DOWN only
        // if the screen is smaller; never scale up (MC font is designed for 1×).
        let scale = ((sw - SCREEN_MARGIN) / BK_W)
            .min((sh - SCREEN_MARGIN) / BK_H)
            .clamp(MIN_SCALE, 1.0);
        let bw = BK_W * scale;
        let bh = BK_H * scale;
        let bx = (sw - bw) / 2.0;
        let by = (sh - bh) / 2.0;

        self.localize();
        // Rebuild widget tree if dirty or screen resized.
        if self.dirty || sw != self.last_sw || sh != self.last_sh {
            let (root, bg_sprites, overlays) = build_ui(
                &self.book,
                &self.state,
                &self.theme,
                &self.recipes,
                bx,
                by,
                bw,
                bh,
            );
            self.ui = Some(root);
            self.bg_sprites = bg_sprites;
            self.overlays = overlays;
            self.dirty = false;
            self.last_sw = sw;
            self.last_sh = sh;
        }
        if let Some(ui) = &mut self.ui
            && ui.needs_layout
        {
            ui.layout(sw, sh);
        }
        (bx, by, bw, bh)
    }

    /// Draws the book into a `sw`×`sh` screen — all of it through
    /// `draw2d` (its sprite sheets as the image sources [`BOOK_SHEET`] and
    /// [`CRAFTING_SHEET`]).
    /// Draws the book; mods' pictures (`BookPage::Drawn`) are left empty —
    /// see [`BookRenderer::render_with`].
    pub fn render(&mut self, ctx: &GfxContext, sw: f32, sh: f32) {
        self.render_with(ctx, sw, sh, &mut |_, _, _, _| {});
    }

    /// Draws the book, mods' pictures with `draw(ctx, drawer, data, [x, y,
    /// w, h])` (screen pixels) — the game calls the mod that registered
    /// `drawer`.
    pub fn render_with(&mut self, ctx: &GfxContext, sw: f32, sh: f32, draw: PageDrawer<'_>) {
        // Text flows by the host's own font metrics once it can measure.
        yog_ui::text::use_host_metrics(ctx);
        if !self.measured {
            self.measured = true;
            self.reflow();
        }
        let (bx, by, bw, bh) = self.prepare(sw, sh);
        let d2 = ctx.draw2d();
        let book_sheet = book_sheet(&self.book.book_texture);
        d2.image_region(
            &book_sheet,
            bx,
            by,
            bw,
            bh,
            [0.0, 0.0, BK_W, BK_H],
            0xFFFF_FFFF,
        );
        for spr in &self.bg_sprites {
            let sheet = match &spr.sheet {
                SpriteSheet::Book => &book_sheet,
                SpriteSheet::Crafting => CRAFTING_SHEET,
                SpriteSheet::Image(source) => source.as_str(),
            };
            d2.image_region(
                sheet,
                spr.x,
                spr.y,
                spr.w,
                spr.h,
                [spr.u, spr.v, spr.uw, spr.uh],
                0xFFFF_FFFF,
            );
        }
        if let Some(ui) = &mut self.ui {
            ui.render(ctx);
        }
        // Animations: entities and structures turn (Patchouli's pace), an
        // ingredient's alternatives take turns every second.
        let t = self.start.elapsed().as_secs_f32();
        for ov in &self.overlays {
            match *ov {
                OverlayCmd::Drawn {
                    ref drawer,
                    ref data,
                    x,
                    y,
                    w,
                    h,
                } => draw(ctx, drawer, data, [x, y, w, h]),
                OverlayCmd::Entity {
                    ref entity,
                    x,
                    y,
                    w,
                    h,
                } => d2.entity(entity, x, y, w, h, -30.0 + t * 30.0, 0.0),
                OverlayCmd::Blocks {
                    ref blocks,
                    x,
                    y,
                    w,
                    h,
                } => {
                    let list: Vec<((i32, i32, i32), &str)> =
                        blocks.iter().map(|(p, b)| (*p, b.as_str())).collect();
                    d2.blocks(&list, x, y, w, h, -45.0 + t * 20.0, 30.0);
                }
                _ => {}
            }
        }
        // Item stacks and MC-font text last: item rendering changes GL state.
        self.draw_mc_overlays(ctx);
    }

    fn draw_mc_overlays(&self, ctx: &GfxContext) {
        let second = self.start.elapsed().as_secs() as usize;
        for ov in &self.overlays {
            match *ov {
                OverlayCmd::McItems {
                    ref items,
                    x,
                    y,
                    w,
                    h,
                } => {
                    let shown: Vec<&String> =
                        items.iter().filter(|i| !i.starts_with('#')).collect();
                    if !shown.is_empty() {
                        let item = shown[second % shown.len()];
                        ctx.draw2d().item(&normalize_item_id(item), x, y, w.min(h));
                    }
                }
                OverlayCmd::McItem {
                    ref item_id,
                    x,
                    y,
                    w,
                    h,
                } => {
                    ctx.draw2d()
                        .item(&normalize_item_id(item_id), x, y, w.min(h));
                }
                OverlayCmd::McText {
                    ref text,
                    x,
                    y,
                    color,
                } => {
                    ctx.draw2d().text(text, x, y, color, false);
                }
                OverlayCmd::McTexture {
                    ref path,
                    x,
                    y,
                    w,
                    h,
                } => {
                    // Standalone icon texture, not an atlas region — drawn
                    // whole, scaled into the icon box.
                    ctx.draw2d().image(path, x, y, w, h);
                }
                _ => {}
            }
        }
    }

    /// The page shown moves by itself (an entity, a structure, an
    /// ingredient's alternatives): the host should keep redrawing it.
    pub fn animated(&self) -> bool {
        self.overlays.iter().any(|o| match o {
            OverlayCmd::Entity { .. } | OverlayCmd::Blocks { .. } => true,
            OverlayCmd::McItems { items, .. } => {
                items.iter().filter(|i| !i.starts_with('#')).count() > 1
            }
            _ => false,
        })
    }

    /// A click at `(x, y)` (screen GUI pixels, as last rendered): what it
    /// hit does its thing. The action it was (`"next_page"`, `"entry:3"`,
    /// …), if any.
    pub fn click(&mut self, x: f32, y: f32) -> Option<String> {
        let ui = self.ui.as_ref()?;
        let hit = yog_ui::layout::hit_test(&ui.layout_root, x, y)?;
        let action = hit.on_click.clone()?;
        self.handle_event(&action);
        Some(action)
    }

    /// Shows `entry` (an entry id) at `page` — its page as written, not
    /// counting the pages long text flowed onto — as a reader would have
    /// got there; `false` if there's no such entry.
    pub fn show(&mut self, entry: &str, page: usize) -> bool {
        let Some(e) = self.book.entries.iter().find(|e| e.id == entry) else {
            return false;
        };
        let Some(cat) = self.book.categories.iter().position(|c| c.id == e.category) else {
            return false;
        };
        self.state.cat = cat;
        self.state.at_home = false;
        let in_cat = self.state.entries_in_cat(&self.book);
        let Some(i) = in_cat.iter().position(|x| x.id == entry) else {
            return false;
        };
        let shown = self
            .origins
            .get(entry)
            .and_then(|o| o.iter().position(|&w| w >= page))
            .unwrap_or(page);
        self.state.entry = i;
        self.state.page = shown.min(e.pages.len().saturating_sub(1));
        self.dirty = true;
        true
    }

    /// The entry shown (its id) and the page of it as written, or `None`
    /// on the landing and list pages.
    pub fn shown(&self) -> Option<(String, usize)> {
        if self.state.at_home {
            return None;
        }
        let e = self.state.current_entry(&self.book)?;
        let page = self
            .origins
            .get(&e.id)
            .and_then(|o| o.get(self.state.page))
            .copied()
            .unwrap_or(self.state.page);
        Some((e.id.clone(), page))
    }

    /// Flows the text again (the metrics changed), keeping the reader's place.
    fn reflow(&mut self) {
        let at = self.shown();
        (self.book, self.origins) = flow_traced(self.written.clone());
        self.dirty = true;
        if let Some((entry, page)) = at {
            self.show(&entry, page);
        }
    }

    /// Replaces the book (an edit), keeping the reader where they were.
    pub fn set_book(&mut self, book: Book) {
        let at = self.shown();
        self.written = styled(&book);
        self.probe = None;
        self.source = book.i18n.then_some(book);
        (self.book, self.origins) = flow_traced(self.written.clone());
        self.localize();
        self.theme = BookTheme::default().with_nameplate(&self.book.nameplate_color);
        self.dirty = true;
        match at {
            Some((entry, page)) if self.show(&entry, page) => {}
            _ => {
                if self.state.cat >= self.book.categories.len() {
                    self.state = BookViewState::default();
                }
            }
        }
    }
}

// ── UI builder ────────────────────────────────────────────────────────────────

thread_local! {
    /// The scale the book is drawn at (≤ 1): its text is drawn at it too,
    /// so it stays on the page however small the book gets.
    static TEXT_SCALE: std::cell::Cell<f32> = const { std::cell::Cell::new(1.0) };
}

fn text_scale() -> f32 {
    TEXT_SCALE.with(|s| s.get())
}

/// Book label: MC font, no drop-shadow (Patchouli draws book text shadowless).
fn lbl(text: impl Into<String>) -> widget::Widget {
    widget::label(text).shadow(false).font_scale(text_scale())
}
/// Book button: no drop-shadow.
fn btn(text: impl Into<String>) -> widget::Widget {
    widget::button(text).shadow(false).font_scale(text_scale())
}

/// A title: one line, shrunk (down to half size, then cut short) to fit
/// the page's width.
fn title_lbl(text: impl Into<String>) -> widget::Widget {
    let text = text.into();
    // As wide as the page's inside (less its padding), so `align` can centre it.
    let w = PAGE_W - 10.0;
    let fit = (w / yog_ui::text::str_width(&text, 1.0)).clamp(0.5, 1.0);
    widget::label(text)
        .shadow(false)
        .font_scale(text_scale() * fit)
        .no_wrap()
        .ellipsis()
        .w(w * text_scale())
}

// ── Flowing text ──────────────────────────────────────────────────────────────

/// Width of a page's text, in book pixels.
const TEXT_W: f32 = PAGE_W - 8.0;
/// Height a page's body has for text, in book pixels: the page less its
/// title and separator, the page navigation and the padding.
const BODY_H: f32 = PAGE_H - 22.0 - 12.0 - 14.0;

/// A multiblock page's view of its structure, and its name's height (with
/// the gap under it), in book pixels.
const MB_VIEW: f32 = 70.0;
const MB_NAME_H: f32 = 14.0;

/// How much of the body a page's own content takes above its text.
fn content_above_text(page: &BookPage) -> Option<f32> {
    Some(match page {
        BookPage::Text { title: Some(_), .. } => 22.0,
        BookPage::Text { .. } => 0.0,
        BookPage::Spotlight { .. } => 40.0,
        // (A crafting grid's height: a furnace's is less.)
        BookPage::Recipe { .. } => 80.0,
        BookPage::Image { .. } | BookPage::Entity { .. } => 104.0,
        BookPage::Drawn { title, height, caption, .. } => {
            let title = if title.is_some() { 14.0 } else { 0.0 };
            let picture = if *height > 0.0 { height + 4.0 } else { 0.0 };
            title + picture + if caption.is_some() { 14.0 } else { 0.0 }
        }
        BookPage::Multiblock { name, .. } => {
            MB_VIEW + 4.0 + if name.is_some() { MB_NAME_H } else { 0.0 }
        }
        BookPage::Relations { entries, .. } => 12.0 + entries.len() as f32 * 10.0,
        _ => return None,
    })
}

fn page_text_mut(page: &mut BookPage) -> Option<&mut String> {
    match page {
        BookPage::Text { text, .. } => Some(text),
        BookPage::Spotlight { text, .. }
        | BookPage::Recipe { text, .. }
        | BookPage::Image { text, .. }
        | BookPage::Entity { text, .. }
        | BookPage::Multiblock { text, .. }
        | BookPage::Relations { text, .. }
        | BookPage::Drawn { text, .. } => text.as_mut(),
        _ => None,
    }
}

/// `book` with its texts' own words (see [`crate::markup`]) as Yog text's.
fn styled(book: &Book) -> Book {
    book.localized(|t| crate::markup::resolve(t, &book.accent))
}

/// Text that doesn't fit its page goes on to new text pages after it.
#[cfg(test)]
fn flow(book: Book) -> Book {
    flow_traced(book).0
}

/// [`flow`], and for each entry where each of its pages came from: the
/// index of the page in the book as written.
fn flow_traced(mut book: Book) -> (Book, HashMap<String, Vec<usize>>) {
    let mut origins = HashMap::new();
    let line_h = yog_ui::text::LINE_H + yog_ui::text::LINE_GAP;
    let fits = |h: f32| (((h + yog_ui::text::LINE_GAP) / line_h).floor() as usize).max(1);
    for entry in &mut book.entries {
        let mut pages = Vec::with_capacity(entry.pages.len());
        let mut from = Vec::with_capacity(entry.pages.len());
        for (written, page) in std::mem::take(&mut entry.pages).into_iter().enumerate() {
            let split = split_page(page, &book.page_types, &fits);
            from.extend(std::iter::repeat_n(written, split.len()));
            pages.extend(split);
        }
        entry.pages = pages;
        origins.insert(entry.id.clone(), from);
    }
    (book, origins)
}

/// A mod's page's room for its text: the property its last text shows
/// (`<BookText text="{x:Bind text}"/>`, nothing else in it), and the
/// height the rest of the page takes, in book pixels.
fn custom_text(page: &crate::page_type::CustomPage, types: &[crate::page_type::PageType]) -> Option<(String, f32)> {
    use crate::page_type::PageElement as E;
    let t = types.iter().find(|t| t.id == page.kind)?;
    let line_h = yog_ui::text::LINE_H + yog_ui::text::LINE_GAP;
    let shown: Vec<&E> = t.body.iter().filter(|el| match el {
        E::Header { visible, .. } | E::Text { visible, .. } | E::Item { visible, .. } | E::Image { visible, .. } | E::Drawn { visible, .. } => t.visible(page, visible),
        E::Spacer { .. } => true,
    }).collect();
    let at = shown.iter().rposition(|el| matches!(el, E::Text { .. }))?;
    let E::Text { text, .. } = shown[at] else { return None };
    let name = text.trim().strip_prefix("{x:Bind ")?.strip_suffix('}')?.trim();
    if !matches!(page.fields.get(name), Some(yog_data::Value::Str(_))) {
        return None;
    }
    let others: f32 = shown.iter().enumerate().filter(|(i, _)| *i != at).map(|(_, el)| match el {
        E::Header { .. } => 14.0,
        E::Text { text, .. } => t.text(page, text).split('\n').map(|p| yog_ui::text::wrap_text(p, TEXT_W, 1.0).len().max(1)).sum::<usize>() as f32 * line_h + 4.0,
        E::Item { .. } => 20.0,
        E::Image { height, .. } | E::Drawn { height, .. } | E::Spacer { height } => height + 4.0,
    }).sum();
    Some((name.to_string(), others))
}

/// `page`, and the text pages its overflowing text goes on to.
fn split_page(mut page: BookPage, types: &[crate::page_type::PageType], fits: &dyn Fn(f32) -> usize) -> Vec<BookPage> {
    let (above, text) = match &mut page {
        BookPage::Custom(c) => {
            let Some((name, above)) = custom_text(c, types) else { return vec![page] };
            let Some(yog_data::Value::Str(text)) = c.fields.get_mut(&name) else { return vec![page] };
            (above, text)
        }
        _ => {
            let Some(above) = content_above_text(&page) else {
                return vec![page];
            };
            let Some(text) = page_text_mut(&mut page) else {
                return vec![page];
            };
            (above, text)
        }
    };
    let lines: Vec<String> = text
        .split('\n')
        .flat_map(|para| {
            if para.is_empty() {
                vec![String::new()]
            } else {
                yog_ui::text::wrap_text(para, TEXT_W, 1.0)
            }
        })
        .collect();
    let first = fits(BODY_H - above);
    if lines.len() <= first {
        return vec![page];
    }
    *text = lines[..first].join("\n");
    let rest: Vec<BookPage> = lines[first..]
        .chunks(fits(BODY_H))
        .map(|chunk| BookPage::Text {
            text: chunk.join("\n"),
            title: None,
            font: None,
            font_size: None,
        })
        .collect();
    std::iter::once(page).chain(rest).collect()
}

/// Build the yog-ui widget tree + bg sprites + overlay commands for the current book state.
/// `bx/by/bw/bh` are the screen-space book rect (same values used to blit the bg texture).
fn build_ui(
    book: &Book,
    state: &BookViewState,
    theme: &BookTheme,
    recipes: &HashMap<String, RecipeVis>,
    bx: f32,
    by: f32,
    bw: f32,
    bh: f32,
) -> (UiRoot, Vec<BgSprite>, Vec<OverlayCmd>) {
    let mut bg_sprites: Vec<BgSprite> = Vec::new();
    let mut overlays: Vec<OverlayCmd> = Vec::new();

    // Scale from Patchouli's fixed BK_W×BK_H coordinate space → actual bw×bh.
    let sx = bw / BK_W;
    TEXT_SCALE.with(|s| s.set(sx));
    let sy = bh / BK_H;

    // In book-local: left page starts at x=LEFT_X, right at RIGHT_X, both y=TOP_PAD.
    let pw = PAGE_W * sx;
    let ph = PAGE_H * sy;
    let spine_gap = (RIGHT_X - LEFT_X - PAGE_W) * sx; // ≈10px scaled

    // Content x/y in screen space (for SVG overlay positioning).
    let lx = bx + LEFT_X * sx;
    let rx = bx + RIGHT_X * sx;
    let py = by + TOP_PAD * sy;

    // Separator x offset within a page: centered = PAGE_W/2 - SEP_W/2 = 58-55 = 3.
    let sep_cx = (PAGE_W / 2.0 - SEP_W / 2.0) * sx; // = 3*sx

    if state.at_home {
        // Nameplate banner: book-local (-8, 12) from LEFT_PAGE_X, size 140×31.
        bg_sprites.push(BgSprite {
            sheet: SpriteSheet::Book,
            u: 0.0,
            v: 180.0,
            uw: 140.0,
            uh: 31.0,
            x: bx + (LEFT_X - 8.0) * sx,
            y: by + 12.0 * sy,
            w: 140.0 * sx,
            h: 31.0 * sy,
        });
    }
    // Separator on the right page below its header ("Categories" or the
    // category name; y=12 page-local), centered.
    bg_sprites.push(BgSprite {
        sheet: SpriteSheet::Book,
        u: SEP_U,
        v: SEP_V,
        uw: SEP_W,
        uh: SEP_H,
        x: rx + sep_cx,
        y: by + (TOP_PAD + 12.0) * sy,
        w: SEP_W * sx,
        h: (SEP_H * sy).max(1.0),
    });

    let (left_page, right_page) = if state.at_home {
        let l = build_landing_left(book, theme, pw, ph, sx, sy, bx, by, &mut overlays);
        let r = build_categories_right(book, state, theme, pw, ph, rx, py, sx, sy, &mut overlays);
        (l, r)
    } else {
        let l = build_entry_left(
            book,
            state,
            theme,
            recipes,
            pw,
            ph,
            lx,
            py,
            sx,
            sy,
            sep_cx,
            &mut bg_sprites,
            &mut overlays,
        );
        let r = build_entries_right(book, state, theme, pw, ph, rx, py, sx, sy, &mut overlays);
        (l, r)
    };

    // Root row spans the full book width.
    // padding-left = LEFT_X*sx offsets both pages from the left cover edge.
    // padding-top  = TOP_PAD*sy offsets from the header banner.
    // spine_gap spacer sits between the two pages.
    // gap must be 0: analytic overlay positions assume pages sit exactly at
    // LEFT_X / RIGHT_X — any flex gap would shift widgets (and their focus
    // highlights) away from the absolutely-positioned icons.
    let root_widget = widget::panel(FlexDir::Row)
        .w(bw)
        .h(bh)
        .gap(0.0)
        .padding(TOP_PAD * sy, 0.0, 0.0, LEFT_X * sx)
        .child(left_page)
        .child(widget::spacer().w(spine_gap)) // spine gap
        .child(right_page);

    // Outer shell: positions the book on screen via a full-screen transparent Row.
    // We use a Column + Row arrangement to apply top/left offsets without margin support.
    let outer = widget::panel(FlexDir::Column)
        .w(bw)
        .h(bh)
        .child(root_widget);

    // Screen-level container: positions book at (bx, by).
    // bx offset via padding, by offset via padding-top.
    // Note: layout computes from (0,0), so we pass bx/by into the UiRoot manually
    // by wrapping in a full-screen panel with the right padding.
    let screen_root = widget::panel(FlexDir::Row)
        .padding(by, 0.0, 0.0, bx)
        .child(outer);

    let ui = UiRoot::new(&book.id, screen_root);
    (ui, bg_sprites, overlays)
}

// ── Left page: landing (home view) ───────────────────────────────────────────

fn build_landing_left(
    book: &Book,
    theme: &BookTheme,
    page_w: f32,
    page_h: f32,
    sx: f32,
    sy: f32,
    bx: f32,
    by: f32,
    overlays: &mut Vec<OverlayCmd>,
) -> widget::Widget {
    // Patchouli: title at book-local (13, 16), subtitle at (24, 24).
    // These overlap the nameplate sprite which is above/within the page top.
    overlays.push(OverlayCmd::McText {
        text: book.name.clone(),
        x: bx + 13.0 * sx,
        y: by + 16.0 * sy,
        color: theme.nameplate,
    });
    // Its edition ("1st Edition"), else its subtitle — as Patchouli.
    let second = match book.version {
        0 => book.subtitle.clone(),
        n => Some(word("edition", &ordinal(n))),
    };
    if let Some(text) = second {
        overlays.push(OverlayCmd::McText {
            text,
            x: bx + 24.0 * sx,
            y: by + 24.0 * sy,
            color: theme.nameplate,
        });
    }

    // Widget content: landing text + entry count.
    // Landing text starts at page-local y=25 (= book-local y=43).
    // We push it down with top padding = 25*sy.
    let mut col = widget::panel(FlexDir::Column)
        .w(page_w)
        .h(page_h)
        .padding(25.0 * sy, 6.0, 4.0, 4.0)
        .gap(0.0);

    // As small as it takes to fit above the entry count.
    let fit = landing_fit(&book.landing_text);
    for para in book.landing_text.split('\n') {
        if para.is_empty() {
            col = col.child(widget::spacer().h(4.0 * sy));
        } else {
            col = col.child(lbl(para).color(theme.text).font_scale(text_scale() * fit));
        }
    }

    let total = book.entries.len();
    col = col.child(widget::spacer().flex(1.0));
    col = col.child(
        title_lbl(word("entry_count", &total.to_string()))
            .color(theme.nav)
            .h(9.0 * sy)
            .align(Align::Center),
    );
    col
}

/// The scale (≤ 1) the landing text fits its page at.
fn landing_fit(text: &str) -> f32 {
    use yog_ui::text::{LINE_GAP, LINE_H, line_count};
    let room = PAGE_H - 25.0 - 4.0 - 9.0 - 2.0;
    let height = |scale: f32| -> f32 {
        text.split('\n')
            .map(|p| match p.is_empty() {
                true => 4.0,
                false => line_count(p, TEXT_W, scale) as f32 * (LINE_H * scale + LINE_GAP),
            })
            .sum()
    };
    let mut scale = 1.0;
    while scale > 0.6 && height(scale) > room {
        scale -= 0.05;
    }
    scale
}

// ── Right page: category list (home view) ────────────────────────────────────

fn build_categories_right(
    book: &Book,
    state: &BookViewState,
    theme: &BookTheme,
    page_w: f32,
    page_h: f32,
    rx: f32,
    py: f32,
    sx: f32,
    sy: f32,
    overlays: &mut Vec<OverlayCmd>,
) -> widget::Widget {
    // Patchouli right-page layout (landing):
    //   "Categories" header at page-local y=0, centered
    //   Separator at page-local y=12 (drawn as bg sprite, not here)
    //   4-column 24×24 icon grid starting at page-local (10, 25)
    let cell_w = 24.0 * sx;
    let cell_h = 24.0 * sy;
    let grid_pad_left = 10.0 * sx;
    let header_h = 9.0 * sy;

    let mut col = widget::panel(FlexDir::Column)
        .w(page_w)
        .h(page_h)
        .padding(0.0, 4.0, 4.0, 0.0)
        .gap(0.0);

    col = col.child(
        title_lbl(word("categories", ""))
            .color(theme.divider)
            .h(header_h)
            .align(Align::Center)
            .no_wrap(),
    );
    // Gap covering the separator region up to grid start (page-local y=25).
    col = col.child(widget::spacer().h(25.0 * sy - header_h));

    // 4-column icon grid; icons drawn as GL overlays at exact Patchouli positions.
    let cats = &book.categories;
    let icon_s = 16.0 * sx.min(sy);
    let mut row_i = 0usize;
    loop {
        let row_start = row_i * 4;
        if row_start >= cats.len() {
            break;
        }
        let mut row =
            widget::panel(FlexDir::Row)
                .h(cell_h)
                .gap(0.0)
                .padding(0.0, 0.0, 0.0, grid_pad_left);
        for col_i in 0..4 {
            let idx = row_start + col_i;
            if idx >= cats.len() {
                break;
            }
            let cat = &cats[idx];
            let selected = !state.at_home && idx == state.cat;
            let bg = if selected { theme.nav_selected_bg } else { 0 };

            if let Some(icon_id) = &cat.icon {
                push_icon(
                    overlays,
                    icon_id,
                    rx + (10.0 + col_i as f32 * 24.0 + 4.0) * sx,
                    py + (25.0 + row_i as f32 * 24.0 + 4.0) * sy,
                    icon_s,
                    icon_s,
                );
            }
            let cell = widget::panel(FlexDir::Column)
                .w(cell_w)
                .h(cell_h)
                .bg(bg)
                .on_click(format!("cat:{}", idx))
                .id(format!("book_cat_{}", idx));
            row = row.child(cell);
        }
        col = col.child(row);
        row_i += 1;
    }
    col
}

// ── Left page: entry content (entry view) ────────────────────────────────────

fn build_entry_left(
    book: &Book,
    state: &BookViewState,
    theme: &BookTheme,
    recipes: &HashMap<String, RecipeVis>,
    page_w: f32,
    page_h: f32,
    ox: f32,
    oy: f32,
    sx: f32,
    sy: f32,
    sep_cx: f32,
    bg_sprites: &mut Vec<BgSprite>,
    overlays: &mut Vec<OverlayCmd>,
) -> widget::Widget {
    let entry = state.current_entry(book);
    let page = entry.and_then(|e| e.pages.get(state.page));
    let page_count = state.page_count(book);
    let title_text = entry.map(|e| e.name.as_str()).unwrap_or("");

    // Patchouli PageText page 0:
    //   title centered at page-local (PAGE_W/2, 0)
    //   separator at page-local (0, 12)  → centered ≡ sep_cx offset
    //   text body at page-local (0, 22)
    let title_h = 9.0 * sy;
    let sep_h_px = (SEP_H * sy).max(1.0);
    let sep_y = oy + 12.0 * sy;
    let body_oy = oy + 22.0 * sy;

    bg_sprites.push(BgSprite {
        sheet: SpriteSheet::Book,
        u: SEP_U,
        v: SEP_V,
        uw: SEP_W,
        uh: SEP_H,
        x: ox + sep_cx,
        y: sep_y,
        w: SEP_W * sx,
        h: sep_h_px,
    });

    let page_label = format!("{}/{}", state.page + 1, page_count);
    let nav = widget::panel(FlexDir::Row)
        .h(12.0 * sy)
        .gap(4.0)
        .padding(0.0, 2.0, 0.0, 2.0)
        .child(
            btn("â—€")
                .w(12.0 * sx)
                .h(12.0 * sy)
                .color(theme.nav)
                .on_click("prev_page")
                .id("prev_page"),
        )
        .child(
            lbl(&page_label)
                .color(theme.nav)
                .flex(1.0)
                .align(Align::Center),
        )
        .child(
            btn("⌂")
                .w(12.0 * sx)
                .h(12.0 * sy)
                .color(theme.nav)
                .on_click("home")
                .id("book_home"),
        )
        .child(
            btn("â–¶")
                .w(12.0 * sx)
                .h(12.0 * sy)
                .color(theme.nav)
                .on_click("next_page")
                .id("next_page"),
        );

    let page_body = build_page(
        page,
        state.page,
        theme,
        recipes,
        &book.layouts,
        &book.page_types,
        bg_sprites,
        overlays,
        ox,
        body_oy,
        sx,
        sy,
    );

    widget::panel(FlexDir::Column)
        .w(page_w)
        .h(page_h)
        .padding(0.0, 6.0, 4.0, 4.0)
        .gap(0.0)
        .child(
            title_lbl(title_text)
                .color(theme.title)
                .h(title_h)
                .align(Align::Center)
                .no_wrap(),
        )
        .child(widget::spacer().h((12.0 - 9.0) * sy)) // gap: title end → sep start
        .child(widget::spacer().h(sep_h_px)) // height occupied by sep sprite
        .child(widget::spacer().h((22.0 - 12.0 - SEP_H) * sy)) // gap: sep end → body
        .child(page_body)
        .child(nav)
}

// ── Right page: entry list for selected category (entry view) ─────────────────

fn build_entries_right(
    book: &Book,
    state: &BookViewState,
    theme: &BookTheme,
    page_w: f32,
    page_h: f32,
    rx: f32,
    py: f32,
    sx: f32,
    sy: f32,
    overlays: &mut Vec<OverlayCmd>,
) -> widget::Widget {
    let entries = state.entries_visible(book);
    let cat_name = book
        .categories
        .get(state.cat)
        .map(|c| c.name.as_str())
        .map(str::to_string)
        .unwrap_or_else(|| word("entries", ""));
    let spread_count = state.list_spread_count(book);

    // Patchouli GuiBookEntryList layout (right page):
    //   category name at page-local y=0, centered
    //   separator at page-local y=12 (drawn as bg sprite in build_ui)
    //   entries start at page-local y=20, each h=11
    let header_h = 9.0 * sy;
    let row_h = 11.0 * sy;
    let icon_size = 8.0 * sx.min(sy);

    let mut col = widget::panel(FlexDir::Column)
        .w(page_w)
        .h(page_h)
        .padding(0.0, 4.0, 8.0, 0.0)
        .gap(0.0);

    col = col.child(
        title_lbl(cat_name)
            .color(theme.divider)
            .h(header_h)
            .align(Align::Center),
    );
    // sep region: y=9..15 (sep h=3), then gap to entries start at y=20
    col = col.child(widget::spacer().h((12.0 - 9.0) * sy)); // gap to sep
    col = col.child(widget::spacer().h((SEP_H * sy).max(1.0))); // sep height
    col = col.child(widget::spacer().h((20.0 - 12.0 - SEP_H) * sy)); // gap to entries

    let abs_start = state.list_spread_start();
    for (i, entry) in entries.iter().enumerate() {
        let abs_i = abs_start + i;
        let selected = abs_i == state.entry;
        let bg = if selected { theme.nav_selected_bg } else { 0 };
        let color = if selected {
            theme.nav_selected
        } else {
            theme.nav
        };

        // Icon at page-local (1, 20 + i*11 + 1), 8×8 (Patchouli renders entry
        // icons at 0.5× scale).
        if let Some(icon_id) = &entry.icon {
            push_icon(
                overlays,
                icon_id,
                rx + 1.0 * sx,
                py + (20.0 + i as f32 * 11.0 + 1.0) * sy,
                icon_size,
                icon_size,
            );
        }

        let mut row = widget::panel(FlexDir::Row)
            .h(row_h)
            .gap(2.0)
            .bg(bg)
            .on_click(format!("entry:{}", abs_i))
            .id(format!("book_entry_{}", abs_i))
            .padding(1.0, 2.0, 1.0, 2.0);

        row = row.child(widget::spacer().w(icon_size + 2.0));
        // Long names shrink to the row (as titles do).
        let fit = ((PAGE_W - 26.0) / yog_ui::text::str_width(&entry.name, 1.0)).clamp(0.5, 1.0);
        row = row.child(
            lbl(&entry.name)
                .color(color)
                .font_scale(text_scale() * fit)
                .flex(1.0)
                .no_wrap(),
        );
        col = col.child(row);
    }

    if spread_count > 1 {
        col = col.child(widget::spacer().flex(1.0));
        let spread_label = format!("{}/{}", state.list_spread + 1, spread_count);
        col = col.child(
            widget::panel(FlexDir::Row)
                .h(12.0 * sy)
                .gap(2.0)
                .child(
                    btn("â—€")
                        .w(12.0 * sx)
                        .h(12.0 * sy)
                        .color(theme.nav)
                        .on_click("prev_list")
                        .id("prev_list"),
                )
                .child(
                    lbl(&spread_label)
                        .color(theme.nav)
                        .flex(1.0)
                        .align(Align::Center),
                )
                .child(
                    btn("â–¶")
                        .w(12.0 * sx)
                        .h(12.0 * sy)
                        .color(theme.nav)
                        .on_click("next_list")
                        .id("next_list"),
                ),
        );
    }
    col
}

/// Draws `vis` the way `layout` lays it out, under a title with its result's
/// name, centred on the page (body-local coordinates, like Patchouli's pages).
#[allow(clippy::too_many_arguments)]
fn draw_layout(
    theme: &BookTheme,
    bg_sprites: &mut Vec<BgSprite>,
    overlays: &mut Vec<OverlayCmd>,
    col: &mut widget::Widget,
    vis: &RecipeVis,
    layout: &crate::layout::RecipeLayout,
    ox: f32,
    oy: f32,
    sx: f32,
    sy: f32,
) {
    use crate::layout::{FRAME_UV, LayoutPart};
    let mut c = std::mem::replace(col, widget::panel(FlexDir::Column));
    c = c.child(
        title_lbl(pretty_item_name(&vis.output))
            .color(theme.title)
            .h(10.0 * sy)
            .align(Align::Center),
    );
    let (lx, ly) = (PAGE_W / 2.0 - 1.0 - layout.size[0] / 2.0, 10.0);
    let at = |p: [f32; 2]| (ox + (lx + p[0]) * sx, oy + (ly + p[1]) * sy);
    let icon_s = 16.0 * sx.min(sy);
    let frame = |bg: &mut Vec<BgSprite>, p: [f32; 2]| {
        let (x, y) = at([p[0] - 4.0, p[1] - 4.0]);
        let [u, v, uw, uh] = FRAME_UV;
        bg.push(BgSprite {
            sheet: SpriteSheet::Crafting,
            u,
            v,
            uw,
            uh,
            x,
            y,
            w: uw * sx,
            h: uh * sy,
        });
    };
    for part in &layout.parts {
        match part {
            LayoutPart::Image { source, uv, at: p } => {
                let (x, y) = at(*p);
                let sheet = if source == CRAFTING_SHEET {
                    SpriteSheet::Crafting
                } else {
                    SpriteSheet::Image(source.clone())
                };
                let [u, v, uw, uh] = *uv;
                bg_sprites.push(BgSprite {
                    sheet,
                    u,
                    v,
                    uw,
                    uh,
                    x,
                    y,
                    w: uw * sx,
                    h: uh * sy,
                });
            }
            LayoutPart::Slots {
                slot,
                at: places,
                frame: framed,
            } => {
                let ingredients = vis.slots.get(slot);
                for (i, p) in places.iter().enumerate() {
                    if *framed {
                        frame(bg_sprites, *p);
                    }
                    if let Some(items) =
                        ingredients.and_then(|l| l.get(i)).filter(|x| !x.is_empty())
                    {
                        let (x, y) = at(*p);
                        overlays.push(OverlayCmd::McItems {
                            items: items.clone(),
                            x,
                            y,
                            w: icon_s,
                            h: icon_s,
                        });
                    }
                }
            }
            LayoutPart::Result {
                at: p,
                frame: framed,
            } => {
                if *framed {
                    frame(bg_sprites, *p);
                }
                let (x, y) = at(*p);
                overlays.push(OverlayCmd::McItem {
                    item_id: vis.output.clone(),
                    x,
                    y,
                    w: icon_s,
                    h: icon_s,
                });
            }
            LayoutPart::Count { at: p } => {
                if vis.count > 1 {
                    let (x, y) = at(*p);
                    overlays.push(OverlayCmd::McText {
                        text: format!("x{}", vis.count),
                        x,
                        y,
                        color: theme.title,
                    });
                }
            }
            LayoutPart::Item { item, at: p } => {
                let (x, y) = at(*p);
                overlays.push(OverlayCmd::McItem {
                    item_id: item.clone(),
                    x,
                    y,
                    w: icon_s,
                    h: icon_s,
                });
            }
            LayoutPart::Text { text, at: p } => {
                let mut shown = text.clone();
                for (name, value) in &vis.values {
                    shown = shown.replace(&format!("{{{name}}}"), value);
                }
                let (x, y) = at(*p);
                overlays.push(OverlayCmd::McText {
                    text: shown,
                    x,
                    y,
                    color: theme.text,
                });
            }
        }
    }
    // The title is 10 high; the layout, and a little room under it.
    c = c.child(widget::spacer().h((layout.size[1] + 6.0) * sy));
    *col = c;
}

// ── Page content builder ──────────────────────────────────────────────────────

/// Build the content widget for a single page.
/// `ox/oy` = screen top-left of the page body area.
/// `sx/sy` = book-local-to-screen scale factors.
fn build_page(
    page: Option<&BookPage>,
    page_num: usize,
    theme: &BookTheme,
    recipes: &HashMap<String, RecipeVis>,
    layouts: &[crate::layout::RecipeLayout],
    page_types: &[crate::page_type::PageType],
    bg_sprites: &mut Vec<BgSprite>,
    overlays: &mut Vec<OverlayCmd>,
    ox: f32,
    oy: f32,
    sx: f32,
    sy: f32,
) -> widget::Widget {
    let mut col = widget::panel(FlexDir::Column).flex(1.0).gap(4.0);

    let Some(page) = page else {
        return col.child(lbl(word("no_entries", "")).color(theme.nav));
    };

    match page {
        BookPage::Text {
            text,
            title,
            font,
            font_size,
        } => {
            // On non-first pages, show an optional section title + separator.
            if page_num > 0
                && let Some(t) = title
            {
                let sep_h_px = (SEP_H * sy).max(1.0);
                let title_h = 9.0 * sy;
                col = col.child(
                    title_lbl(t.as_str())
                        .color(theme.title)
                        .h(title_h)
                        .align(Align::Center)
                        .no_wrap(),
                );
                // sep at y=12 page-local, centered
                bg_sprites.push(BgSprite {
                    sheet: SpriteSheet::Book,
                    u: SEP_U,
                    v: SEP_V,
                    uw: SEP_W,
                    uh: SEP_H,
                    x: ox + (PAGE_W / 2.0 - SEP_W / 2.0) * sx,
                    y: oy + 12.0 * sy,
                    w: SEP_W * sx,
                    h: sep_h_px,
                });
                col = col.child(widget::spacer().h((12.0 - 9.0) * sy));
                col = col.child(widget::spacer().h(sep_h_px));
                col = col.child(widget::spacer().h((22.0 - 12.0 - SEP_H) * sy));
            }
            // One label: its lines are as far apart as the flowing counted.
            let mut l = lbl(text.as_str()).color(theme.text);
            // Another font (a resource-pack one), `font_size` pixels a line.
            if let Some(f) = font {
                l = l.font(f.as_str()).font_scale(
                    text_scale() * font_size.unwrap_or(yog_ui::text::LINE_H) / yog_ui::text::LINE_H,
                );
            }
            col = col.child(l);
        }

        BookPage::Spotlight { item, title, text } => {
            // Patchouli PageSpotlight (page-body-local coordinates):
            //   title at y=0 centered, item frame at (PAGE_W/2-33, 10) 66×26
            //   (UV 0,102 on the 128×256 crafting sheet), item at (PAGE_W/2-8, 15),
            //   text at y=40.
            bg_sprites.push(BgSprite {
                sheet: SpriteSheet::Crafting,
                u: 0.0,
                v: 102.0,
                uw: 66.0,
                uh: 26.0,
                x: ox + (PAGE_W / 2.0 - 33.0) * sx,
                y: oy + 10.0 * sy,
                w: 66.0 * sx,
                h: 26.0 * sy,
            });

            let item_name = title.clone().unwrap_or_else(|| pretty_item_name(item));
            col = col.child(
                title_lbl(item_name)
                    .color(theme.title)
                    .h(10.0 * sy)
                    .align(Align::Center),
            );

            let icon_s = 16.0 * sx.min(sy);
            overlays.push(OverlayCmd::McItem {
                item_id: item.clone(),
                x: ox + (PAGE_W / 2.0 - 8.0) * sx,
                y: oy + 15.0 * sy,
                w: icon_s,
                h: icon_s,
            });

            // Spacer from title end (y=10) to text start (y=40).
            col = col.child(widget::spacer().h(30.0 * sy));

            if let Some(t) = text {
                col = col.child(lbl(t.as_str()).color(theme.text));
            }
        }

        BookPage::Recipe { recipe, text } => {
            match recipes
                .get(recipe.as_str())
                .and_then(|vis| crate::layout::find(layouts, &vis.kind).map(|l| (vis, l)))
            {
                Some((vis, layout)) => draw_layout(
                    theme, bg_sprites, overlays, &mut col, vis, layout, ox, oy, sx, sy,
                ),
                None => col = col.child(lbl(format!("[Recipe: {}]", recipe)).color(theme.nav)),
            }
            if let Some(t) = text {
                col = col.child(lbl(t.as_str()).color(theme.text));
            }
        }

        BookPage::Image {
            texture,
            title,
            text,
            ..
        } => {
            if let Some(t) = title {
                col = col.child(title_lbl(t.as_str()).color(theme.title));
            }
            col = col.child(
                widget::image(texture)
                    .region([0.0, 0.0, 80.0, 80.0])
                    .stretch(Stretch::Fill)
                    .w(80.0)
                    .h(80.0),
            );
            if let Some(t) = text {
                col = col.child(lbl(t.as_str()).color(theme.text));
            }
        }

        BookPage::Relations { entries, text } => {
            if let Some(t) = text {
                col = col.child(lbl(t.as_str()).color(theme.text));
            }
            col = col.child(title_lbl(word("see_also", "")).color(theme.title));
            for e in entries {
                col = col.child(lbl(format!("• {}", e)).color(theme.nav));
            }
        }

        BookPage::Multiblock {
            name,
            pattern,
            mapping,
            text,
        } => {
            // A 70px view (under its name), its text below.
            let top = if let Some(n) = name {
                col = col.child(title_lbl(n.as_str()).color(theme.title).h(10.0 * sy));
                MB_NAME_H
            } else {
                0.0
            };
            overlays.push(OverlayCmd::Blocks {
                blocks: crate::multiblock_blocks(pattern, mapping),
                x: ox + (PAGE_W / 2.0 - MB_VIEW / 2.0) * sx,
                y: oy + top * sy,
                w: MB_VIEW * sx,
                h: MB_VIEW * sy,
            });
            col = col.child(widget::spacer().h(MB_VIEW * sy));
            if let Some(t) = text {
                col = col.child(lbl(t.as_str()).color(theme.text));
            }
        }

        BookPage::Entity { entity, name, text } => {
            let display = name.clone().unwrap_or_else(|| entity_name(entity));
            col = col.child(title_lbl(display).color(theme.title));
            overlays.push(OverlayCmd::Entity {
                entity: entity.clone(),
                x: ox + (PAGE_W / 2.0 - 40.0) * sx,
                y: oy + 12.0 * sy,
                w: 80.0 * sx,
                h: 80.0 * sy,
            });
            col = col.child(widget::spacer().h(84.0 * sy));
            if let Some(t) = text {
                col = col.child(lbl(t.as_str()).color(theme.text));
            }
        }

        BookPage::Drawn {
            drawer,
            title,
            height,
            caption,
            text,
            data,
        } => {
            let mut top = 0.0;
            if let Some(t) = title {
                col = col.child(title_lbl(t.as_str()).color(theme.title).h(10.0 * sy));
                top = 14.0;
            }
            // The picture: a box the page's width, drawn by the mod's code.
            if *height > 0.0 {
                overlays.push(OverlayCmd::Drawn {
                    drawer: drawer.clone(),
                    data: data.clone(),
                    x: ox,
                    y: oy + top * sy,
                    w: PAGE_W * sx,
                    h: height * sy,
                });
                col = col.child(widget::spacer().h(height * sy));
            }
            if let Some(c) = caption {
                col = col.child(lbl(c.as_str()).color(theme.text));
            }
            if let Some(t) = text {
                col = col.child(lbl(t.as_str()).color(theme.text));
            }
        }

        BookPage::Empty => {}

        // A mod's own kind of page: its type's elements, top to bottom.
        BookPage::Custom(c) => {
            use crate::page_type::PageElement as E;
            let Some(t) = page_types.iter().find(|t| t.id == c.kind) else {
                return col.child(lbl(format!("[{}]", c.kind)).color(theme.nav));
            };
            let line_h = yog_ui::text::LINE_H + yog_ui::text::LINE_GAP;
            // How far down the next element starts, in book pixels (pictures are overlays).
            let mut top = 0.0;
            for el in &t.body {
                match el {
                    E::Header { text, visible } if t.visible(c, visible) => {
                        col = col.child(title_lbl(t.text(c, text)).color(theme.title).h(10.0 * sy));
                        top += 14.0;
                    }
                    E::Text { text, visible } if t.visible(c, visible) => {
                        let words = t.text(c, text);
                        let lines: usize = words.split('\n').map(|p| yog_ui::text::wrap_text(p, TEXT_W, 1.0).len().max(1)).sum();
                        col = col.child(lbl(words).color(theme.text));
                        top += lines as f32 * line_h + 4.0;
                    }
                    E::Item { item, visible } if t.visible(c, visible) => {
                        let id = crate::page_type::words(&t.value(c, item));
                        push_icon(overlays, &id, ox + (PAGE_W / 2.0 - 8.0) * sx, oy + top * sy, 16.0 * sx, 16.0 * sy);
                        col = col.child(widget::spacer().h(16.0 * sy));
                        top += 20.0;
                    }
                    E::Image { image, height, visible } if t.visible(c, visible) => {
                        let src = crate::page_type::words(&t.value(c, image));
                        col = col.child(widget::image(src).stretch(Stretch::Fill).w(PAGE_W * sx).h(height * sy));
                        top += height + 4.0;
                    }
                    E::Drawn { drawer, height, data, visible } if t.visible(c, visible) => {
                        overlays.push(OverlayCmd::Drawn {
                            drawer: drawer.clone(),
                            data: t.value(c, data),
                            x: ox,
                            y: oy + top * sy,
                            w: PAGE_W * sx,
                            h: height * sy,
                        });
                        col = col.child(widget::spacer().h(height * sy));
                        top += height + 4.0;
                    }
                    E::Spacer { height } => {
                        col = col.child(widget::spacer().h(height * sy));
                        top += height + 4.0;
                    }
                    _ => {}
                }
            }
        }
    }

    col
}

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

    fn j(json: &str) -> yog_data::Value {
        yog_data::json::from_json_text(json).unwrap()
    }
    use crate::BookEntry;

    fn book(pages: Vec<BookPage>) -> Book {
        let mut book = Book {
            id: "t:b".into(),
            name: "B".into(),
            ..Default::default()
        };
        book.entries.push(BookEntry {
            id: "e".into(),
            name: "E".into(),
            pages,
            ..Default::default()
        });
        book
    }

    #[test]
    fn long_text_flows_onto_new_pages() {
        let long = "word ".repeat(400);
        let flowed = flow(book(vec![
            BookPage::Text {
                text: long.clone(),
                title: None,
                font: None,
                font_size: None,
            },
            BookPage::Empty,
        ]));
        let pages = &flowed.entries[0].pages;
        assert!(pages.len() > 3, "{}", pages.len());
        assert!(
            matches!(pages.last(), Some(BookPage::Empty)),
            "what came after stays after"
        );
        let line_h = yog_ui::text::LINE_H + yog_ui::text::LINE_GAP;
        for p in &pages[..pages.len() - 1] {
            let BookPage::Text { text, .. } = p else {
                panic!("{p:?}")
            };
            assert!(text.lines().count() as f32 * line_h <= BODY_H + 1.0);
            assert!(
                text.lines()
                    .all(|l| yog_ui::text::str_width(l, 1.0) <= TEXT_W)
            );
        }
        let words: usize = pages
            .iter()
            .map(|p| match p {
                BookPage::Text { text, .. } => text.split_whitespace().count(),
                _ => 0,
            })
            .sum();
        assert_eq!(words, 400, "nothing lost");
    }

    #[test]
    fn edits_keep_the_reader_where_they_were() {
        let mut b = book(vec![
            BookPage::Text {
                text: "one".into(),
                title: None,
                font: None,
                font_size: None,
            },
            BookPage::Text {
                text: "two".into(),
                title: None,
                font: None,
                font_size: None,
            },
        ]);
        b.categories.push(crate::BookCategory {
            id: "c".into(),
            name: "C".into(),
            ..Default::default()
        });
        b.entries[0].category = "c".into();
        let mut r = BookRenderer::new(b.clone());
        assert_eq!(r.shown(), None, "opens on the landing page");
        assert!(r.show("e", 1));
        assert_eq!(r.shown(), Some(("e".into(), 1)));
        r.prepare(800.0, 600.0);
        assert!(r.ui.is_some());

        b.entries[0].pages.push(BookPage::Empty);
        r.set_book(b);
        assert_eq!(r.shown(), Some(("e".into(), 1)));
        assert!(!r.show("missing", 0));
    }

    #[test]
    fn pages_are_counted_as_written() {
        let long = "word ".repeat(400);
        let mut b = book(vec![
            BookPage::Text {
                text: long,
                title: None,
                font: None,
                font_size: None,
            },
            BookPage::Empty,
        ]);
        b.categories.push(crate::BookCategory {
            id: "c".into(),
            name: "C".into(),
            ..Default::default()
        });
        b.entries[0].category = "c".into();
        let mut r = BookRenderer::new(b);
        assert!(r.show("e", 1));
        assert_eq!(
            r.shown(),
            Some(("e".into(), 1)),
            "the second page as written"
        );
        assert!(r.state.page > 1, "past the first page's flowed text");
        r.handle_event("prev_page");
        assert_eq!(
            r.shown(),
            Some(("e".into(), 0)),
            "flowed text belongs to the first"
        );
    }

    #[test]
    fn reads_yog_recipes() {
        let shaped = parse_recipe(&j(r##"{"type":"shaped","pattern":["AB"],"key":{"A":"m:a","B":["m:x","#c:t"]},"result":"m:out","count":2}"##)).unwrap();
        assert_eq!(
            (shaped.kind.as_str(), shaped.output.as_str(), shaped.count),
            ("shaped", "m:out", 2)
        );
        let grid = &shaped.slots["grid"];
        assert_eq!(
            (grid.len(), &grid[1]),
            (9, &vec!["m:x".to_string(), "#c:t".to_string()]),
            "cells by place on the 3×3 grid"
        );
        let blast =
            parse_recipe(&j(r##"{"type":"blasting","ingredient":"m:ore","result":"m:ingot"}"##))
                .unwrap();
        assert_eq!(
            (
                blast.slots["input"][0][0].as_str(),
                blast.values["time"].as_str()
            ),
            ("m:ore", "100")
        );
        let own = parse_recipe(&j(r##"{"type":"m:infusion","slots":{"ring":["m:a",["m:b","m:c"]]},"values":{"time":40},"result":"m:out"}"##)).unwrap();
        assert_eq!(
            (own.slots["ring"].len(), own.values["time"].as_str()),
            (2, "40")
        );
        assert!(
            parse_recipe(&j(r#"{"type":"minecraft:crafting_shaped"}"#)).is_none(),
            "vanilla JSON isn't the book's"
        );
    }

    #[test]
    fn recipe_pages_are_drawn_by_layouts() {
        let theme = BookTheme::default();
        let mut recipes = HashMap::new();
        recipes.insert("m:r".to_string(), parse_recipe(&j(r##"{"type":"m:infusion","slots":{"ring":["m:a","m:b"]},"values":{"time":40},"result":"m:out"}"##)).unwrap());
        recipes.insert("m:s".to_string(), parse_recipe(&j(r##"{"type":"smithing","template":"m:t","base":"m:b","addition":"m:a","result":"m:out"}"##)).unwrap());
        let layout: crate::layout::RecipeLayout = yog_data::from_text(
            r#"{ kinds: ["m:infusion"], size: [96, 40], parts: [
                { type: "slots", slot: "ring", at: [[0, 0], [20, 0]], frame: true },
                { type: "result", at: [76, 10] },
                { type: "text", text: "{time} ticks", at: [0, 30] },
            ] }"#,
        )
        .unwrap()
        .value;
        let draw = |id: &str| {
            let (mut bg, mut ov) = (Vec::new(), Vec::new());
            let page = BookPage::Recipe {
                recipe: id.into(),
                text: None,
            };
            build_page(
                Some(&page),
                0,
                &theme,
                &recipes,
                std::slice::from_ref(&layout),
                &[],
                &mut bg,
                &mut ov,
                0.0,
                0.0,
                1.0,
                1.0,
            );
            (bg, ov)
        };
        let (bg, ov) = draw("m:r");
        let lx = PAGE_W / 2.0 - 1.0 - 48.0;
        let items: Vec<(f32, f32)> = ov
            .iter()
            .filter_map(|o| match o {
                OverlayCmd::McItems { x, y, .. } | OverlayCmd::McItem { x, y, .. } => {
                    Some((*x, *y))
                }
                _ => None,
            })
            .collect();
        assert_eq!(items, [(lx, 10.0), (lx + 20.0, 10.0), (lx + 76.0, 20.0)]);
        assert_eq!(bg.len(), 2, "a frame behind each ring slot");
        assert!(
            ov.iter()
                .any(|o| matches!(o, OverlayCmd::McText { text, .. } if text == "40 ticks"))
        );
        // The game's kinds: built-in layouts (smithing had none before).
        let (bg, ov) = draw("m:s");
        assert!(
            bg.iter().any(|b| b.u == 11.0 && b.v == 135.0),
            "Patchouli's smithing strip"
        );
        assert_eq!(
            ov.iter()
                .filter(|o| matches!(o, OverlayCmd::McItems { .. }))
                .count(),
            3
        );
    }

    #[test]
    fn multiblocks_turn_and_animate() {
        let pattern = vec![vec!["G".to_string()], vec!["S ".to_string()]];
        let mapping = [
            ("G".to_string(), "minecraft:glass".to_string()),
            ("S".to_string(), "minecraft:stone".to_string()),
        ]
        .into();
        let blocks = crate::multiblock_blocks(&pattern, &mapping);
        assert_eq!(
            blocks,
            [
                ((0, 1, 0), "minecraft:glass".to_string()),
                ((0, 0, 0), "minecraft:stone".to_string())
            ]
        );

        let mut b = book(vec![BookPage::Multiblock {
            name: None,
            pattern,
            mapping,
            text: None,
        }]);
        b.categories.push(crate::BookCategory {
            id: "c".into(),
            name: "C".into(),
            ..Default::default()
        });
        b.entries[0].category = "c".into();
        let mut r = BookRenderer::new(b);
        r.prepare(800.0, 600.0);
        assert!(!r.animated(), "the landing page is still");
        assert_eq!(landing_fit("short"), 1.0);
        assert!(
            landing_fit(&"many words here ".repeat(60)) < 1.0,
            "long landing texts shrink"
        );
        r.show("e", 0);
        r.prepare(800.0, 600.0);
        assert!(r.animated(), "a structure turns");
    }

    #[test]
    fn short_text_stays_put() {
        let pages = vec![BookPage::Text {
            text: "Hello".into(),
            title: Some("T".into()),
            font: None,
            font_size: None,
        }];
        let flowed = flow(book(pages.clone()));
        assert_eq!(flowed.entries[0].pages.len(), 1);
    }

    #[test]
    fn a_drawn_page_hands_its_box_and_data_to_the_mods_drawer() {
        let data = yog_data::json::from_json(&serde_json::json!({ "op_id": "hexcasting:manual" }));
        let page: BookPage = serde_json::from_value(serde_json::json!({
            "type": "drawn", "drawer": "hexcasting:pattern", "title": "Manual", "height": 64,
            "caption": "{u|entity} → {u|num}", "text": "Casts.", "data": { "op_id": "hexcasting:manual" }
        }))
        .unwrap();
        assert!(matches!(&page, BookPage::Drawn { data: d, height, .. } if *d == data && *height == 64.0));
        assert_eq!(content_above_text(&page), Some(14.0 + 68.0 + 14.0));
        let mut b = book(vec![page.clone()]);
        b.categories.push(crate::BookCategory { id: "c".into(), name: "C".into(), ..Default::default() });
        b.entries[0].category = "c".into();
        let mut r = BookRenderer::new(b);
        r.show("e", 0);
        r.prepare(800.0, 600.0);
        let drawn: Vec<_> = r.overlays.iter().filter_map(|o| match o {
            OverlayCmd::Drawn { drawer, data, w, h, .. } => Some((drawer.clone(), data.clone(), *w / *h)),
            _ => None,
        }).collect();
        assert_eq!(drawn.len(), 1);
        assert_eq!((drawn[0].0.as_str(), &drawn[0].1), ("hexcasting:pattern", &data));
        assert!((drawn[0].2 - PAGE_W / 64.0).abs() < 0.01, "the page's width, 64 high");
        // The JSON form keeps the data.
        assert_eq!(serde_json::to_value(&page).unwrap()["data"]["op_id"], "hexcasting:manual");
    }

    #[test]
    fn a_mods_page_type_lays_out_its_pages() {
        use crate::page_type::{PageElement as E, PageProperty, PageType, PropKind};
        let ty = PageType {
            id: "hexcasting:pattern".into(),
            properties: vec![
                PageProperty { name: "name".into(), kind: PropKind::BookText, default: None },
                PageProperty { name: "patterns".into(), kind: PropKind::Data, default: Some(yog_data::Value::List(vec![])) },
            ],
            body: vec![
                E::Header { text: "{x:Bind name}".into(), visible: None },
                E::Drawn { drawer: "hexcasting:pattern".into(), height: 64.0, data: "{x:Bind patterns}".into(), visible: Some("{x:Bind patterns}".into()) },
            ],
        };
        let page = |json: &str| BookPage::Custom(yog_data::read_value(&yog_data::json::from_json_text(json).unwrap()).unwrap());
        let mut b = book(vec![
            page(r#"{"type":"hexcasting:pattern","name":"Manual","patterns":[{"startdir":"EAST","signature":"qaq"}]}"#),
            page(r#"{"type":"hexcasting:pattern","name":"Bare"}"#),
        ]);
        b.page_types.push(ty);
        b.categories.push(crate::BookCategory { id: "c".into(), name: "C".into(), ..Default::default() });
        b.entries[0].category = "c".into();
        let mut r = BookRenderer::new(b);
        r.show("e", 0);
        r.prepare(800.0, 600.0);
        let drawn: Vec<_> = r.overlays.iter().filter_map(|o| match o {
            OverlayCmd::Drawn { drawer, data, .. } => Some((drawer.clone(), data.clone())),
            _ => None,
        }).collect();
        assert_eq!(drawn.len(), 1, "the second page has no patterns: no picture");
        assert_eq!(drawn[0].0, "hexcasting:pattern");
        assert!(matches!(&drawn[0].1, yog_data::Value::List(l) if l.len() == 1), "the field's whole value");
    }

    #[test]
    fn a_mods_page_flows_its_long_text_onto_text_pages() {
        use crate::page_type::{PageElement as E, PageProperty, PageType, PropKind};
        let ty = PageType {
            id: "m:p".into(),
            properties: vec![
                PageProperty { name: "patterns".into(), kind: PropKind::Data, default: None },
                PageProperty { name: "text".into(), kind: PropKind::BookText, default: None },
            ],
            body: vec![
                E::Drawn { drawer: "m:d".into(), height: 64.0, data: "{x:Bind patterns}".into(), visible: None },
                E::Text { text: "{x:Bind text}".into(), visible: None },
            ],
        };
        let long = "word ".repeat(120);
        let page = format!(r#"{{"type":"m:p","patterns":[1],"text":"{long}"}}"#);
        let mut b = book(vec![BookPage::Custom(yog_data::read_value(&yog_data::json::from_json_text(&page).unwrap()).unwrap())]);
        b.page_types.push(ty);
        let flowed = flow(b);
        let pages = &flowed.entries[0].pages;
        assert!(pages.len() >= 2, "{pages:?}");
        let BookPage::Custom(first) = &pages[0] else { panic!("{:?}", pages[0]) };
        let kept = first.fields.get("text").and_then(|v| v.as_str()).unwrap();
        let line_h = yog_ui::text::LINE_H + yog_ui::text::LINE_GAP;
        assert!(kept.lines().count() as f32 * line_h <= BODY_H - 68.0 + 1.0, "under the picture: {kept}");
        let words: usize = kept.split_whitespace().count()
            + pages[1..].iter().map(|p| match p {
                BookPage::Text { text, .. } => text.split_whitespace().count(),
                _ => 0,
            }).sum::<usize>();
        assert_eq!(words, 120, "nothing lost");
    }

    #[test]
    fn a_translated_book_is_flowed_from_its_words_not_its_keys() {
        // A key too long for a page: flowed as it is, it'd be cut in pieces.
        fn tr(k: &str) -> Option<String> {
            (k.len() == 3000 && k.starts_with("mymod.")).then(|| "Short.".into())
        }
        let key = format!("mymod.{}", "x".repeat(2994));
        let mut b = book(vec![BookPage::Text {
            text: key,
            title: None,
            font: None,
            font_size: None,
        }]);
        b.i18n = true;
        let mut r = BookRenderer::new(b);
        r.set_translator(tr);
        r.localize();
        let pages = &r.book().entries[0].pages;
        assert_eq!(pages.len(), 1, "{pages:?}");
        assert!(matches!(&pages[0], BookPage::Text { text, .. } if text == "Short."), "{pages:?}");
    }
}