pokeductor 0.5.0

A terminal Pokedex and evolution analyzer with sprite rendering, offline type and party analysis, and an on-disk cache for offline use
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
//! Application state machine and async orchestration.
//!
//! The UI never blocks: network work is performed in detached `tokio` tasks
//! that report back over an `mpsc` channel. Each spawned task is a *producer*;
//! the main loop in [`App::run`] is the single *consumer*, draining the channel
//! alongside terminal input and a steady animation tick via `tokio::select!`.

use std::collections::{HashMap, HashSet};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crossterm::event::{Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use futures::StreamExt;
use ratatui::DefaultTerminal;
use tokio::sync::mpsc;
use tokio::time::MissedTickBehavior;

use crate::api;
use crate::api::ApiError;
use crate::browser::{Browser, SortKey};
use crate::cache;
use crate::cli::Startup;
use crate::color::{self, Depth};
use crate::i18n::Language;
use crate::models::{
    AbilityInfo, EvolutionTree, LearnedMove, MoveInfo, PokemonDetail, PokemonEntry, RosterTerm,
    Sprite, SpriteVariant,
};
use crate::session::{self, Session};
use crate::team;
use crate::theme::{self, Theme};

/// How many learnset rows around the cursor the moves card fetches records for.
/// Sized to cover the card on a tall terminal, so the visible table fills in
/// together rather than a row at a time.
const MOVE_BAND: usize = 36;
/// How much of [`MOVE_BAND`] sits above the cursor rather than below it.
const MOVE_LOOKBEHIND: usize = 4;

/// How often the loading spinner advances, while there is one to advance.
const SPINNER_TICK: Duration = Duration::from_millis(120);

/// Messages sent from background fetch tasks to the UI loop. The payloads are
/// large but short-lived and low-frequency, so the size difference between
/// variants isn't worth boxing around.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum Message {
    /// The master Pokemon list finished loading.
    ListLoaded(Vec<PokemonEntry>),
    /// A Pokemon's details and evolution chain finished loading.
    PokemonLoaded {
        detail: PokemonDetail,
        evolution: EvolutionTree,
        /// Decoded artwork, if the species had a sprite we could fetch.
        sprite: Option<Sprite>,
        /// Which palette `sprite` was fetched in. Carried along because the
        /// shiny toggle can flip while the request is in flight.
        variant: SpriteVariant,
    },
    /// A standalone sprite (for an evolution-chain member) finished loading.
    SpriteLoaded {
        name: String,
        variant: SpriteVariant,
        sprite: Option<Sprite>,
    },
    /// An ability's localized text finished loading.
    AbilityLoaded(AbilityInfo),
    /// One move's record finished loading.
    MoveLoaded(MoveInfo),
    /// The roster behind a `type:`, `ability:` or `egg:` filter finished
    /// loading.
    RosterLoaded {
        term: RosterTerm,
        members: Vec<String>,
    },
    /// A machine-translated flavor blurb finished loading.
    FlavorTranslated {
        name: String,
        lang: String,
        text: String,
    },
    /// A background task failed.
    Error(String),
}

/// Which panel currently receives keyboard input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Focus {
    Search,
    List,
    /// The evolution panel: arrow keys move between chain members and Enter
    /// jumps to the highlighted one.
    Evolution,
}

/// The complete, observable state of the running application.
pub struct App {
    pub language: Language,
    /// The palette the interface is drawn in. Installed process-wide by
    /// [`App::run`] once the flag and the restored session have settled it,
    /// since every rendering function reads it from there.
    pub theme: Theme,
    /// The sidebar: the master list, the search box, the ordering and the
    /// cursor over the result. Everything about the visible list that needs
    /// no network lives there; what stays here is the half that does.
    pub browser: Browser,
    /// Rosters currently in flight, so a filter is requested only once.
    pub roster_loading: HashSet<RosterTerm>,
    pub focus: Focus,
    /// In-memory cache so each Pokemon is fetched at most once per session.
    pub details: HashMap<String, PokemonDetail>,
    pub evolutions: HashMap<String, EvolutionTree>,
    /// Decoded sprites, keyed by palette and then by Pokemon name. Absent if a
    /// species has no art, or if that palette has not been asked for yet.
    pub sprites: HashMap<SpriteVariant, HashMap<String, Sprite>>,
    /// Names whose sprite is being fetched on demand, per palette, so we never
    /// queue the same request twice.
    pub sprite_loading: HashMap<SpriteVariant, HashSet<String>>,
    /// Which palette every sprite on screen is shown in. App-wide rather than
    /// per-species: moving through the list keeps showing shinies until the
    /// toggle is switched off again.
    pub sprite_variant: SpriteVariant,
    /// Cursor into the evolution chain (depth-first order) while the evolution
    /// panel is focused.
    pub evo_cursor: usize,
    /// Whether the chain is expanded to the full-screen evolution view. Wide
    /// branching chains never fit the panel, so this is where they get drawn as
    /// sprite cards rather than as a text tree.
    pub evo_card: bool,
    /// Whether the language-picker card is open, and which row it highlights.
    pub language_picker: bool,
    pub lang_cursor: usize,
    /// Whether the type-matchup card is open for the current selection.
    pub matchups: bool,
    /// The species pinned as the left-hand side of a comparison, if any. Held
    /// as a name rather than a record because it outlives the selection: you
    /// pin one species, walk the list, and take the second one later.
    pub pin: Option<String>,
    /// Whether the head-to-head card is open.
    pub compare_card: bool,
    /// The party being assembled, in the order members were added. Holds names
    /// only; the analysis reads their typings out of `details`, so a member
    /// whose record is still in flight simply does not contribute yet.
    pub team: Vec<String>,
    /// Team members whose details are being fetched, so each is requested once.
    pub team_loading: HashSet<String>,
    /// Whether the team card is open, and which member it highlights.
    pub team_card: bool,
    pub team_cursor: usize,
    /// Localized ability text, keyed by ability slug.
    pub abilities: HashMap<String, AbilityInfo>,
    /// Ability lookups in flight, so each is requested only once.
    pub ability_loading: HashSet<String>,
    /// Whether the ability card is open for the current selection.
    pub ability_card: bool,
    /// Move records, keyed by move slug. Filled in one move at a time as the
    /// cursor reaches each row, rather than eighty at a time when the card
    /// opens.
    pub moves: HashMap<String, MoveInfo>,
    /// Move lookups in flight, so each is requested only once.
    pub move_loading: HashSet<String>,
    /// Whether the moves card is open for the current selection.
    pub moves_card: bool,
    /// Row the moves card highlights, as an index into the selection's
    /// learnset.
    pub move_cursor: usize,
    /// Whether the forms card is open, and which of the species' varieties it
    /// highlights. Held here rather than on the record because it is a cursor
    /// over what is on display, not a property of the species.
    pub forms_card: bool,
    pub forms_cursor: usize,
    /// Whether the help overlay is open.
    pub help_card: bool,
    /// Machine-translated flavor blurbs, keyed by `(pokemon name, lang code)`.
    pub translations: HashMap<(String, String), String>,
    /// Translation requests currently in flight, to avoid duplicating work.
    pub translating: HashSet<(String, String)>,
    /// Name of the Pokemon currently shown in the detail panel.
    pub selected_name: Option<String>,
    /// What the terminal can show, resolved once at startup from `--color` and
    /// the environment. Every frame is rewritten into it on the way out, and
    /// sprites are skipped entirely when it is [`Depth::None`].
    pub color_depth: Depth,
    /// Language named on the command line, if any. Kept rather than merely
    /// applied because the restored session carries a language too, and this
    /// one has to outrank it.
    cli_language: Option<Language>,
    /// Palette named on the command line, for the same reason.
    cli_theme: Option<Theme>,
    /// Species named on the command line, opened once the list arrives — the
    /// first moment there is anything to resolve a name against.
    startup_species: Option<String>,
    /// Name currently being fetched, if any (drives the detail spinner).
    pub loading_detail: Option<String>,
    pub list_loading: bool,
    pub error: Option<String>,
    /// Monotonic counter used to animate the loading spinner.
    pub spinner: usize,
    pub should_quit: bool,

    client: reqwest::Client,
    tx: mpsc::Sender<Message>,
}

impl App {
    /// Builds the app and returns it alongside the receiver half of the
    /// message channel (handed back to [`App::run`]).
    ///
    /// `startup` carries the command-line overrides. Each is optional, so a
    /// bare invocation is the same call with nothing to override.
    pub fn new(startup: Startup) -> anyhow::Result<(Self, mpsc::Receiver<Message>)> {
        let client = api::build_client()?;
        let color_depth = color::resolve(startup.color, &color::Env::from_process());
        color::enforce(startup.color, color_depth);
        let (tx, rx) = mpsc::channel(64);
        let app = App {
            language: startup.language.unwrap_or(Language::English),
            theme: startup.theme.unwrap_or_default(),
            browser: Browser::default(),
            roster_loading: HashSet::new(),
            focus: Focus::List,
            details: HashMap::new(),
            evolutions: HashMap::new(),
            sprites: HashMap::new(),
            sprite_loading: HashMap::new(),
            sprite_variant: SpriteVariant::Normal,
            evo_cursor: 0,
            evo_card: false,
            language_picker: false,
            lang_cursor: 0,
            matchups: false,
            pin: None,
            compare_card: false,
            team: Vec::new(),
            team_loading: HashSet::new(),
            team_card: false,
            team_cursor: 0,
            abilities: HashMap::new(),
            ability_loading: HashSet::new(),
            ability_card: false,
            moves: HashMap::new(),
            move_loading: HashSet::new(),
            moves_card: false,
            move_cursor: 0,
            forms_card: false,
            forms_cursor: 0,
            help_card: false,
            translations: HashMap::new(),
            translating: HashSet::new(),
            selected_name: None,
            color_depth,
            cli_language: startup.language,
            cli_theme: startup.theme,
            startup_species: startup.species,
            loading_detail: None,
            list_loading: false,
            error: None,
            spinner: 0,
            should_quit: false,
            client,
            tx,
        };
        Ok((app, rx))
    }

    /// The main event loop. Owns the terminal and runs until the user quits.
    pub async fn run(
        mut self,
        mut terminal: DefaultTerminal,
        mut rx: mpsc::Receiver<Message>,
    ) -> anyhow::Result<()> {
        // Before the first frame, so the restored language and palette are
        // already in place by the time anything is drawn or fetched.
        self.restore(session::load().await);
        // Installed here rather than in `restore`, which tests call: the
        // palette is process-wide, and the first frame is drawn below.
        theme::use_theme(self.theme);
        self.fetch_list();

        let mut events = EventStream::new();
        let mut ticker = tokio::time::interval(SPINNER_TICK);
        // Nothing polls the ticker while the app is idle, so by the time it is
        // wanted again its deadline is far in the past. `Burst` — the default —
        // would answer that by firing every tick it missed back to back,
        // spinning the wheel through a whole sleep's worth of frames the moment
        // a request starts. `Delay` fires once and schedules the next a full
        // period out, which is what makes waking up look like starting rather
        // than catching up.
        ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);

        while !self.should_quit {
            // Cheap, idempotent: requests a translation only when the current
            // selection+language needs one and none is cached or in flight.
            self.ensure_translation();
            self.ensure_ability_info();
            self.ensure_move_info();
            // Rendering always writes 24-bit colour; this is where the frame
            // is rewritten into what the terminal can actually show. Doing it
            // over the finished buffer keeps every widget — and every sprite
            // pixel — degrading by one rule instead of each checking for
            // itself.
            let depth = self.color_depth;
            terminal.draw(|frame| {
                crate::ui::render(frame, &mut self);
                color::degrade(frame.buffer_mut(), depth);
            })?;

            // The ticker exists to animate the spinner, and the spinner is
            // only on screen while something is in flight. Selecting on it
            // unconditionally is what made an idle Pokedex — the kind of thing
            // left open in a split for hours — redraw itself eight times a
            // second forever. Idle, the loop now blocks on input and messages
            // alone, and draws when one of them says something changed.
            let animating = self.is_busy();

            tokio::select! {
                maybe_msg = rx.recv() => {
                    if let Some(msg) = maybe_msg {
                        self.handle_message(msg);
                    }
                }
                maybe_event = events.next() => {
                    match maybe_event {
                        Some(Ok(event)) => self.handle_event(event),
                        Some(Err(_)) => {} // transient read error: ignore and redraw
                        None => self.should_quit = true,
                    }
                }
                _ = ticker.tick(), if animating => {
                    self.spinner = self.spinner.wrapping_add(1);
                }
            }
        }

        session::store(&self.snapshot()).await;
        Ok(())
    }

    /// Whether anything is in flight — which is exactly when a spinner is on
    /// screen, and so exactly when there is any reason to redraw on a timer.
    ///
    /// Every field here is the pending set of one kind of request, so "is
    /// anything loading" is the union of them being non-empty. `team_loading`
    /// counts too: a party member's record is fetched without the detail panel
    /// waiting on it, but the party card draws a spinner for it just the same.
    pub fn is_busy(&self) -> bool {
        self.list_loading
            || self.loading_detail.is_some()
            || !self.roster_loading.is_empty()
            || !self.ability_loading.is_empty()
            || !self.move_loading.is_empty()
            || !self.translating.is_empty()
            || !self.team_loading.is_empty()
            || self
                .sprite_loading
                .values()
                .any(|pending| !pending.is_empty())
    }

    // --- Session persistence ---------------------------------------------

    /// What this run hands to the next one.
    fn snapshot(&self) -> Session {
        Session {
            team: self.team.clone(),
            language: Some(self.language.flavor_code().to_string()),
            sort: Some(self.browser.sort.code().to_string()),
            theme: Some(self.theme.code().to_string()),
            shiny: self.sprite_variant.is_shiny(),
        }
    }

    /// Applies a restored session over the defaults [`App::new`] set.
    ///
    /// Anything the file leaves out, or records in terms this build no longer
    /// recognises, keeps its default rather than rejecting the file: a session
    /// is a convenience, and a partly understood one still beats starting over.
    fn restore(&mut self, session: Session) {
        // `--lang` is an explicit choice made for this run, so it outranks the
        // one carried over from the last. What the run *ends* in is still what
        // gets stored on the way out, which makes the flag behave exactly like
        // opening the picker and choosing that language would.
        if self.cli_language.is_none() {
            if let Some(language) = session.language.as_deref().and_then(Language::from_code) {
                self.language = language;
            }
        }
        if let Some(sort) = session.sort.as_deref().and_then(SortKey::from_code) {
            self.browser.sort = sort;
        }
        // `--theme` outranks the stored palette the way `--lang` outranks the
        // stored language, and for the same reason: it is a choice made for
        // this run, and the run still stores what it ends in.
        if self.cli_theme.is_none() {
            if let Some(theme) = session.theme.as_deref().and_then(Theme::from_code) {
                self.theme = theme;
            }
        }
        if session.shiny {
            self.sprite_variant = SpriteVariant::Shiny;
        }
        self.team = session.team;

        // The party card reads typings out of `details`, which is empty on a
        // cold start, so a restored member contributes nothing to the analysis
        // until its record is back. These are cache hits on any install that
        // has seen the member before, which is every install that stored it.
        for name in self.team.clone() {
            self.request_team_member(name);
        }
    }

    // --- Async fetch dispatch --------------------------------------------
    //
    // Every dispatcher below reads through `cache` before it touches the
    // network, and writes back whatever it had to fetch. The functions doing
    // that live at the bottom of this file: they run on spawned tasks and so
    // cannot borrow `self`.

    /// Loads the sidebar list, preferring the cache so the app has something to
    /// show immediately. A cached-but-expired list is displayed first and then
    /// refreshed in place; if that refresh fails (offline, say) the stale copy
    /// simply stays up, which is far more useful than an error banner.
    fn fetch_list(&mut self) {
        self.list_loading = true;
        let tx = self.tx.clone();
        let client = self.client.clone();
        tokio::spawn(async move {
            if let Some(cached) = cache::load_list().await {
                let fresh = cached.fresh;
                let _ = tx.send(Message::ListLoaded(cached.entries)).await;
                if fresh {
                    return;
                }
                if let Ok(list) = api::fetch_pokemon_list(&client).await {
                    cache::store_list(&list).await;
                    let _ = tx.send(Message::ListLoaded(list)).await;
                }
                return;
            }
            let msg = match api::fetch_pokemon_list(&client).await {
                Ok(list) => {
                    cache::store_list(&list).await;
                    Message::ListLoaded(list)
                }
                Err(err) => Message::Error(err.to_string()),
            };
            let _ = tx.send(msg).await;
        });
    }

    /// Kicks off a roster fetch for every filter term we have not resolved yet.
    /// One request answers a whole term, and the answer is cached on disk, so
    /// this fires at most once per term per install.
    fn request_missing_rosters(&mut self) {
        let missing: Vec<RosterTerm> = self
            .browser
            .parsed
            .rosters
            .iter()
            .filter(|t| !self.browser.rosters.contains_key(*t) && !self.roster_loading.contains(*t))
            .cloned()
            .collect();

        for term in missing {
            self.roster_loading.insert(term.clone());
            let tx = self.tx.clone();
            let client = self.client.clone();
            tokio::spawn(async move {
                let members = resolve_roster(&client, &term).await;
                let _ = tx.send(Message::RosterLoaded { term, members }).await;
            });
        }
    }

    /// Loads (or reveals from cache) the currently highlighted Pokemon.
    fn request_selected(&mut self) {
        let Some(name) = self.current_name() else {
            return;
        };
        self.error = None;
        self.selected_name = Some(name.clone());

        // Cache hit: nothing to fetch, but make sure the chain sprites are on
        // their way (they may not have been requested yet).
        if self.details.contains_key(&name) {
            self.loading_detail = None;
            self.ensure_visible_sprites();
            return;
        }

        self.loading_detail = Some(name.clone());
        let tx = self.tx.clone();
        let client = self.client.clone();
        let variant = self.sprite_variant;
        tokio::spawn(async move {
            let _ = tx.send(resolve_bundle(&client, &name, variant).await).await;
        });
    }

    /// Requests a machine translation of the selected Pokemon's flavor text when
    /// the active language has no native PokeAPI entry (e.g. Turkish) and we
    /// haven't already translated or queued it.
    fn ensure_translation(&mut self) {
        let code = self.language.flavor_code();
        if code == "en" {
            return; // English is always the source; nothing to translate
        }
        // Gather what we need under a short immutable borrow, then release it.
        let (name, source) = {
            let Some(detail) = self.selected_detail() else {
                return;
            };
            if detail.flavors.contains_key(code) {
                return; // PokeAPI already has this language natively
            }
            match detail.flavors.get("en") {
                Some(src) => (detail.name.clone(), src.clone()),
                None => return, // no English source to translate from
            }
        };

        let key = (name.clone(), code.to_string());
        if self.translations.contains_key(&key) || self.translating.contains(&key) {
            return;
        }
        self.translating.insert(key);

        let tx = self.tx.clone();
        let client = self.client.clone();
        let lang = code.to_string();
        tokio::spawn(async move {
            // Translations cost a rate-limited third-party request, so a cached
            // one is worth reaching for before we ask again.
            if let Some(text) = cache::load_translation(&name, &lang).await {
                let _ = tx
                    .send(Message::FlavorTranslated { name, lang, text })
                    .await;
                return;
            }
            // On failure we simply never send: the UI keeps the English text and
            // the in-flight flag stops us from hammering a rate-limited service.
            if let Ok(text) = api::translate_text(&client, &source, "en", &lang).await {
                cache::store_translation(&name, &lang, &text).await;
                let _ = tx
                    .send(Message::FlavorTranslated { name, lang, text })
                    .await;
            }
        });
    }

    /// A cached machine translation for `name` in `code`, if one exists.
    pub fn translation_for(&self, name: &str, code: &str) -> Option<&str> {
        self.translations
            .get(&(name.to_string(), code.to_string()))
            .map(String::as_str)
    }

    /// The names in the current evolution chain, depth-first. Empty if no
    /// evolution data is loaded for the selection.
    pub fn chain_names(&self) -> Vec<String> {
        let mut names = Vec::new();
        if let Some(tree) = self.selected_evolution() {
            tree.collect_names(&mut names);
        }
        names
    }

    /// Kicks off sprite fetches for everything on screen — the selected species
    /// and every member of its chain — that isn't already cached or in flight.
    ///
    /// Only the palette currently on display is ever requested, so flipping the
    /// shiny toggle costs the artwork in front of you rather than pre-fetching
    /// two full sets. The selection is listed separately from the chain because
    /// an alternate form (`raichu-alola`) does not appear in it under its own
    /// name — the chain carries the base species.
    fn ensure_visible_sprites(&mut self) {
        // Nothing on screen will show them, and `sprite_for` says as much, so
        // without this the loop below would re-request every chain member on
        // every frame and never be satisfied. The artwork arriving inside a
        // species bundle is still kept: it costs no request of its own, and it
        // means a later run with colour opens instantly.
        if self.color_depth == Depth::None {
            return;
        }
        let variant = self.sprite_variant;
        let names: Vec<String> = self
            .selected_name
            .iter()
            .cloned()
            .chain(self.chain_names())
            .collect();

        for name in names {
            if self.sprite_for(&name).is_some() || self.sprite_is_loading(&name) {
                continue;
            }
            // A species whose record is already loaded carries both artwork
            // URLs, which saves the resolver a `/pokemon` request. `Some(None)`
            // means we know it has no art at all.
            let known_url = self
                .details
                .get(&name)
                .map(|detail| detail.sprite_url_for(variant).map(str::to_string));

            self.sprite_loading
                .entry(variant)
                .or_default()
                .insert(name.clone());
            let tx = self.tx.clone();
            let client = self.client.clone();
            tokio::spawn(async move {
                // A failed sprite is non-fatal: the resolvers report no art, so
                // the panel shows a placeholder instead of an error banner.
                let sprite = match known_url {
                    Some(url) => resolve_sprite(&client, &name, url.as_deref(), variant).await,
                    None => resolve_named_sprite(&client, &name, variant).await,
                };
                let _ = tx
                    .send(Message::SpriteLoaded {
                        name,
                        variant,
                        sprite,
                    })
                    .await;
            });
        }
    }

    /// Flips between the normal and shiny palettes, then pulls in whatever
    /// artwork the new one is missing.
    fn toggle_shiny(&mut self) {
        self.sprite_variant = self.sprite_variant.toggled();
        self.ensure_visible_sprites();
    }

    /// Decoded artwork for `name` in the palette currently on display.
    pub fn sprite_for(&self, name: &str) -> Option<&Sprite> {
        // A sprite drawn without colour is a rectangle of identical blocks,
        // which says less than the placeholder the panels already fall back
        // to. Answering `None` here is what routes both of them to it.
        if self.color_depth == Depth::None {
            return None;
        }
        self.sprites.get(&self.sprite_variant)?.get(name)
    }

    /// Whether `name`'s artwork in the current palette is still in flight.
    pub fn sprite_is_loading(&self, name: &str) -> bool {
        self.sprite_loading
            .get(&self.sprite_variant)
            .is_some_and(|pending| pending.contains(name))
    }

    fn remember_sprite(&mut self, name: String, variant: SpriteVariant, sprite: Sprite) {
        self.sprites
            .entry(variant)
            .or_default()
            .insert(name, sprite);
    }

    /// Puts the species named on the command line under the cursor, down the
    /// same path a search-box query takes: the name goes into the box and the
    /// list narrows to it. That is what makes `pokeductor 25` and
    /// `pokeductor type:ghost` work without a second parser, and what keeps an
    /// unknown name on the one "no results" path the TUI already has rather
    /// than inventing a command-line error beside it. The query stays in the
    /// box, so a list that narrowed to nothing says why it did.
    ///
    /// The one thing the search box cannot do here is prefer an exact match:
    /// `mew` narrows to Mew and Mewtwo, and dex order puts Mewtwo first. That
    /// is right when a human is about to press `↓`, and wrong as the answer to
    /// `pokeductor mew`, so an exact name takes the cursor.
    fn select_named_species(&mut self, name: String) {
        self.browser.query = name.trim().to_lowercase();
        self.recompute_filter();
        let exact = self.browser.position_of(&self.browser.query.clone());
        if let Some(pos) = exact {
            self.browser.list_state.select(Some(pos));
        }
    }

    /// Loads the chain member currently under the evolution cursor — the quick
    /// "jump to my next evolution" action.
    fn jump_to_evolution_member(&mut self) {
        let names = self.chain_names();
        let Some(name) = names.get(self.evo_cursor).cloned() else {
            return;
        };
        // Make sure the target is visible in the list and selected there, so the
        // sidebar stays in sync with the detail panel.
        self.browser.query.clear();
        self.recompute_filter();
        if let Some(pos) = self.browser.position_of(&name) {
            self.browser.list_state.select(Some(pos));
        }
        self.request_selected();
    }

    // --- Message handling ------------------------------------------------

    fn handle_message(&mut self, msg: Message) {
        match msg {
            Message::ListLoaded(list) => {
                self.browser.all = list;
                self.list_loading = false;
                // A species named on the command line goes through the
                // search box, which is what narrows the list to it. With no
                // argument the box is empty and the filter is the whole list.
                if let Some(name) = self.startup_species.take() {
                    self.select_named_species(name);
                } else {
                    self.recompute_filter();
                }
                // Open on whatever ended up under the cursor — the argument's
                // species, or the first entry (Bulbasaur) — instead of an empty
                // panel, so there is something to look at before any keypress.
                if self.selected_name.is_none() {
                    self.request_selected();
                }
            }
            Message::PokemonLoaded {
                detail,
                evolution,
                sprite,
                variant,
            } => {
                let name = detail.name.clone();
                if self.loading_detail.as_deref() == Some(name.as_str()) {
                    self.loading_detail = None;
                }
                self.evolutions.insert(name.clone(), evolution);
                if let Some(sprite) = sprite {
                    self.remember_sprite(name.clone(), variant, sprite);
                }
                let is_selected = self.selected_name.as_deref() == Some(name.as_str());
                self.team_loading.remove(&name);
                self.details.insert(name, detail);
                // Now that the chain is known, fetch its members' sprites for
                // the evolution panel. This also covers a toggle that happened
                // while the bundle was in flight: the palette it arrived in may
                // no longer be the one on screen.
                if is_selected {
                    self.ensure_visible_sprites();
                }
            }
            Message::SpriteLoaded {
                name,
                variant,
                sprite,
            } => {
                if let Some(pending) = self.sprite_loading.get_mut(&variant) {
                    pending.remove(&name);
                }
                if let Some(sprite) = sprite {
                    self.remember_sprite(name, variant, sprite);
                }
            }
            Message::AbilityLoaded(info) => {
                self.ability_loading.remove(&info.name);
                self.abilities.insert(info.name.clone(), info);
            }
            Message::MoveLoaded(info) => {
                self.move_loading.remove(&info.name);
                self.moves.insert(info.name.clone(), info);
            }
            Message::RosterLoaded { term, members } => {
                self.roster_loading.remove(&term);
                // Recorded even when empty — a mistyped term must settle on
                // "no results" instead of being requested again every frame.
                self.browser
                    .rosters
                    .insert(term, members.into_iter().collect());
                self.recompute_filter();
            }
            Message::FlavorTranslated { name, lang, text } => {
                let key = (name, lang);
                self.translating.remove(&key);
                self.translations.insert(key, text);
            }
            Message::Error(err) => {
                self.error = Some(err);
                self.loading_detail = None;
                self.list_loading = false;
            }
        }
    }

    // --- Input handling --------------------------------------------------

    fn handle_event(&mut self, event: Event) {
        let Event::Key(key) = event else {
            return; // resize/mouse: the next draw already adapts
        };
        if key.kind != KeyEventKind::Press {
            return;
        }
        // Ctrl-C always quits, regardless of focus.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            self.should_quit = true;
            return;
        }
        // The overlay cards are modal: whichever is open grabs all input.
        if self.language_picker {
            self.handle_language_key(key);
            return;
        }
        if self.help_card {
            if matches!(
                key.code,
                KeyCode::Esc | KeyCode::Enter | KeyCode::Char('?' | 'q' | 'Q')
            ) {
                self.help_card = false;
            }
            return;
        }
        if self.ability_card {
            if matches!(
                key.code,
                KeyCode::Esc | KeyCode::Enter | KeyCode::Char('a' | 'A' | 'q' | 'Q')
            ) {
                self.ability_card = false;
            }
            return;
        }
        if self.moves_card {
            self.handle_moves_key(key);
            return;
        }
        if self.team_card {
            self.handle_team_key(key);
            return;
        }
        if self.forms_card {
            self.handle_forms_key(key);
            return;
        }
        if self.matchups {
            if matches!(
                key.code,
                KeyCode::Esc | KeyCode::Enter | KeyCode::Char('t' | 'T' | 'q' | 'Q')
            ) {
                self.matchups = false;
            }
            return;
        }
        if self.compare_card {
            if matches!(
                key.code,
                KeyCode::Esc | KeyCode::Enter | KeyCode::Char('c' | 'C' | 'q' | 'Q')
            ) {
                self.compare_card = false;
            }
            return;
        }
        if self.evo_card {
            self.handle_evo_card_key(key);
            return;
        }
        match self.focus {
            Focus::List => self.handle_list_key(key),
            Focus::Search => self.handle_search_key(key),
            Focus::Evolution => self.handle_evolution_key(key),
        }
    }

    /// Opens the type-matchup card. It reads the selection's types, so there is
    /// nothing to show until a Pokemon has actually loaded.
    /// Adds the highlighted species to the party, or drops it if it is already
    /// there. A member whose record is not loaded yet is fetched in the
    /// background: the party is picked from the list, where nothing but the
    /// name is known until something asks for more.
    fn toggle_team_membership(&mut self) {
        let Some(name) = self.current_name() else {
            return;
        };
        if let Some(position) = self.team.iter().position(|member| *member == name) {
            self.team.remove(position);
            return;
        }
        if self.team.len() >= team::MAX_MEMBERS {
            return; // party is full; drop someone first
        }
        self.team.push(name.clone());
        self.request_team_member(name);
    }

    /// Pulls in a party member's record in the background, unless it is
    /// already loaded or in flight.
    fn request_team_member(&mut self, name: String) {
        if self.details.contains_key(&name) || self.team_loading.contains(&name) {
            return;
        }
        self.team_loading.insert(name.clone());
        let tx = self.tx.clone();
        let client = self.client.clone();
        let variant = self.sprite_variant;
        tokio::spawn(async move {
            let _ = tx.send(resolve_bundle(&client, &name, variant).await).await;
        });
    }

    /// The loaded records for the current party, in party order. Members still
    /// in flight are skipped, so the analysis always describes exactly what is
    /// listed as loaded on the card.
    pub fn team_details(&self) -> Vec<&PokemonDetail> {
        self.team
            .iter()
            .filter_map(|name| self.details.get(name))
            .collect()
    }

    /// Whether the highlighted list entry is in the party, for the list marker.
    pub fn is_in_team(&self, name: &str) -> bool {
        self.team.iter().any(|member| member == name)
    }

    /// Opens the party card with its cursor on the first member. The cursor
    /// is what makes the card a place to pick from rather than only to read.
    fn open_team_card(&mut self) {
        self.team_cursor = 0;
        self.team_card = true;
    }

    fn handle_team_key(&mut self, key: KeyEvent) {
        let len = self.team.len();
        match key.code {
            KeyCode::Esc | KeyCode::Enter | KeyCode::Char('p' | 'P' | 'q' | 'Q') => {
                self.team_card = false;
            }
            KeyCode::Up | KeyCode::Char('k') if len > 0 => {
                self.team_cursor = (self.team_cursor + len - 1) % len;
            }
            KeyCode::Down | KeyCode::Char('j') if len > 0 => {
                self.team_cursor = (self.team_cursor + 1) % len;
            }
            KeyCode::Char('c') | KeyCode::Char('C') => self.pin_or_compare_member(),
            _ => {}
        }
    }

    /// The comparison key on the party card, over the member under the
    /// cursor. Same three outcomes as [`App::pin_or_compare`] in the list —
    /// pin, let go, or compare — so the card is a shortlist to compare from
    /// and not a second set of rules.
    ///
    /// The one difference is where the second species comes from. In the list
    /// it is what the detail panel shows; here it is the member under the
    /// cursor, so that member is put on display first and the card that opens
    /// is the same one, over the same two records, the list would have opened.
    fn pin_or_compare_member(&mut self) {
        let Some(name) = self.team.get(self.team_cursor).cloned() else {
            return; // an empty party has nothing under the cursor
        };
        if !self.details.contains_key(&name) {
            return; // still loading; there is nothing to compare yet
        }
        match self.pin.as_deref() {
            Some(pinned) if pinned == name => self.pin = None,
            None => self.pin = Some(name),
            Some(_) => {
                if self.show_species(&name) {
                    self.team_card = false;
                    self.compare_card = true;
                }
            }
        }
    }

    /// Puts `name` under the list cursor and in the detail panel, reporting
    /// whether it could: a name the master list does not carry cannot be
    /// shown, and a caller about to open a card over it should know.
    ///
    /// The search box is cleared only when it hides the target, so a filter
    /// the target already satisfies is kept rather than thrown away.
    fn show_species(&mut self, name: &str) -> bool {
        if self.browser.position_of(name).is_none() {
            self.browser.query.clear();
            self.recompute_filter();
        }
        let Some(pos) = self.browser.position_of(name) else {
            return false;
        };
        self.browser.list_state.select(Some(pos));
        self.request_selected();
        true
    }

    /// The varieties of the species on display, which is what the forms card
    /// lists and what its cursor runs over. Empty until a record has landed.
    pub fn forms(&self) -> &[String] {
        self.selected_detail()
            .map(|detail| detail.forms.as_slice())
            .unwrap_or_default()
    }

    /// Opens the forms card with its cursor on the variety already shown, so
    /// the card opens where the reader is and the other forms are what moving
    /// gets to.
    ///
    /// A species with a single variety has nothing to pick from, and the key
    /// does nothing rather than opening a card listing only what is already on
    /// screen.
    fn open_forms(&mut self) {
        let Some(detail) = self.selected_detail() else {
            return; // nothing loaded yet, so nothing to list
        };
        if detail.forms.len() < 2 {
            return;
        }
        let cursor = detail
            .forms
            .iter()
            .position(|form| *form == detail.name)
            .unwrap_or(0);
        self.forms_cursor = cursor;
        self.forms_card = true;
    }

    fn handle_forms_key(&mut self, key: KeyEvent) {
        let len = self.forms().len();
        match key.code {
            KeyCode::Esc | KeyCode::Char('v' | 'V' | 'q' | 'Q') => self.forms_card = false,
            KeyCode::Up | KeyCode::Char('k') if len > 0 => {
                self.forms_cursor = (self.forms_cursor + len - 1) % len;
            }
            KeyCode::Down | KeyCode::Char('j') if len > 0 => {
                self.forms_cursor = (self.forms_cursor + 1) % len;
            }
            KeyCode::Enter => self.jump_to_form(),
            _ => {}
        }
    }

    /// Shows the form under the cursor. Forms are ordinary entries in the
    /// master list — `raichu-alola` sits there under its own id — so this is
    /// the same "select in the list, then load" path every other jump takes,
    /// and the card closes behind it because what it was open for has
    /// happened. A name the list does not carry leaves it open rather than
    /// closing onto an unchanged panel.
    fn jump_to_form(&mut self) {
        let Some(name) = self.forms().get(self.forms_cursor).cloned() else {
            return;
        };
        if self.show_species(&name) {
            self.forms_card = false;
        }
    }

    /// Opens the ability card. The text it shows is pulled in by
    /// [`App::ensure_ability_info`], which the loop is already running.
    fn open_abilities(&mut self) {
        if self.selected_detail().is_some() {
            self.ability_card = true;
        }
    }

    /// Opens the moves card. The learnset came with the species record, so
    /// there is nothing to wait for; the per-move numbers are pulled in by
    /// [`App::ensure_move_info`] as the cursor reaches each row.
    fn open_moves(&mut self) {
        if self.selected_learnset().is_some_and(|set| !set.is_empty()) {
            self.moves_card = true;
            self.move_cursor = 0;
        }
    }

    /// The learnset of the species currently in the detail panel.
    pub fn selected_learnset(&self) -> Option<&[LearnedMove]> {
        self.selected_detail().map(|detail| detail.moves.as_slice())
    }

    /// The move the card highlights, if the card has anything to highlight.
    pub fn highlighted_move(&self) -> Option<&LearnedMove> {
        self.selected_learnset()?.get(self.move_cursor)
    }

    fn handle_moves_key(&mut self, key: KeyEvent) {
        let len = self.selected_learnset().map_or(0, <[LearnedMove]>::len);
        match key.code {
            KeyCode::Esc | KeyCode::Char('m' | 'M' | 'q' | 'Q') => self.moves_card = false,
            KeyCode::Up | KeyCode::Char('k') => self.move_move_cursor(-1, len),
            KeyCode::Down | KeyCode::Char('j') => self.move_move_cursor(1, len),
            KeyCode::PageUp => self.move_move_cursor(-10, len),
            KeyCode::PageDown => self.move_move_cursor(10, len),
            KeyCode::Home => self.move_cursor = 0,
            KeyCode::End => self.move_cursor = len.saturating_sub(1),
            _ => {}
        }
    }

    /// Moves the card's cursor, clamping at both ends rather than wrapping —
    /// a learnset is one long list, and wrapping off the end of eighty rows
    /// loses the reader's place.
    fn move_move_cursor(&mut self, delta: i32, len: usize) {
        if len == 0 {
            return;
        }
        let next = self.move_cursor as i32 + delta;
        self.move_cursor = next.clamp(0, len as i32 - 1) as usize;
    }

    /// Requests the records for the moves around the card's cursor.
    ///
    /// Only while the card is open, and only for a band around what is on
    /// screen: a full learnset runs past a hundred entries, and fetching all of
    /// them the moment the card opens would spend a hundred requests on rows
    /// most readers never scroll to. A band wide enough to cover the card
    /// leaves the visible table filled in rather than showing a column of
    /// names with the numbers still arriving one row at a time.
    fn ensure_move_info(&mut self) {
        if !self.moves_card {
            return;
        }
        let Some(learnset) = self.selected_learnset() else {
            return;
        };
        // A few rows back as well as forward, so scrolling up finds the same
        // band already warm.
        let start = self.move_cursor.saturating_sub(MOVE_LOOKBEHIND);
        let missing: Vec<String> = learnset
            .iter()
            .skip(start)
            .take(MOVE_BAND)
            .map(|learned| learned.name.clone())
            .filter(|name| !self.moves.contains_key(name) && !self.move_loading.contains(name))
            .collect();

        for name in missing {
            self.move_loading.insert(name.clone());
            let tx = self.tx.clone();
            let client = self.client.clone();
            tokio::spawn(async move {
                // A record we cannot fetch simply never arrives: the row keeps
                // showing the move's name and how it is learned, which is the
                // half that came free with the species.
                if let Some(info) = resolve_move(&client, &name).await {
                    let _ = tx.send(Message::MoveLoaded(info)).await;
                }
            });
        }
    }

    /// Requests the localized text for any ability on the current selection or
    /// in the party that we do not have yet.
    ///
    /// Ability *names* are localized too, and they show on the info card and
    /// the party card, not just behind `A` — so waiting for the card to open
    /// would leave those reading as raw English slugs in every other language.
    /// Cheap and idempotent: it only ever covers species the user has actually
    /// opened, each name is requested once, and every answer is cached on disk.
    fn ensure_ability_info(&mut self) {
        // Gather under a short immutable borrow, then release it.
        let missing: Vec<String> = {
            let selection = self.selected_detail().into_iter();
            selection
                .chain(self.team_details())
                .flat_map(|detail| detail.abilities.iter())
                .map(|ability| ability.name.clone())
                .filter(|name| {
                    !self.abilities.contains_key(name) && !self.ability_loading.contains(name)
                })
                .collect()
        };

        for name in missing {
            self.ability_loading.insert(name.clone());
            let tx = self.tx.clone();
            let client = self.client.clone();
            tokio::spawn(async move {
                // Text we cannot fetch simply never arrives: everything keeps
                // showing the ability's slug, which is the useful half.
                if let Some(info) = resolve_ability(&client, &name).await {
                    let _ = tx.send(Message::AbilityLoaded(info)).await;
                }
            });
        }
    }

    fn open_matchups(&mut self) {
        if self.selected_detail().is_some() {
            self.matchups = true;
        }
    }

    /// The comparison key, which does one of three things depending on what is
    /// already pinned: pins the species on display, lets go of it if it is the
    /// one pinned, or — on a second, different species — opens the head-to-head.
    ///
    /// Both sides are records the app already holds: a species reaches the
    /// detail panel by being loaded, and nothing is ever evicted from the cache,
    /// so a pin cannot go stale and the card costs no request to open.
    fn pin_or_compare(&mut self) {
        let Some(current) = self.selected_name.clone() else {
            return; // nothing on display to pin or compare against
        };
        if !self.details.contains_key(&current) {
            return; // still loading; there is nothing to compare yet
        }
        match self.pin.as_deref() {
            Some(pinned) if pinned == current => self.pin = None,
            Some(_) => self.compare_card = true,
            None => self.pin = Some(current),
        }
    }

    /// Whether a list entry is the pinned side of a comparison, for its marker.
    pub fn is_pinned(&self, name: &str) -> bool {
        self.pin.as_deref() == Some(name)
    }

    /// The two records the comparison card reads, pinned side first.
    pub fn comparison(&self) -> Option<(&PokemonDetail, &PokemonDetail)> {
        let pinned = self.details.get(self.pin.as_ref()?)?;
        let current = self.selected_detail()?;
        Some((pinned, current))
    }

    /// Opens the language picker, parking the cursor on the active language.
    fn open_language_picker(&mut self) {
        self.lang_cursor = self.language.index();
        self.language_picker = true;
    }

    fn handle_language_key(&mut self, key: KeyEvent) {
        let len = Language::ALL.len();
        match key.code {
            KeyCode::Esc => self.language_picker = false,
            KeyCode::Up | KeyCode::Char('k') => {
                self.lang_cursor = (self.lang_cursor + len - 1) % len;
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.lang_cursor = (self.lang_cursor + 1) % len;
            }
            KeyCode::Enter | KeyCode::Char(' ') | KeyCode::Char('l') | KeyCode::Char('L') => {
                self.language = Language::ALL[self.lang_cursor];
                self.language_picker = false;
            }
            _ => {}
        }
    }

    fn handle_list_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Char('q') | KeyCode::Char('Q') | KeyCode::Esc => self.should_quit = true,
            KeyCode::Up | KeyCode::Char('k') => self.move_selection(-1),
            KeyCode::Down | KeyCode::Char('j') => self.move_selection(1),
            KeyCode::PageUp => self.move_selection(-10),
            KeyCode::PageDown => self.move_selection(10),
            KeyCode::Enter => self.request_selected(),
            KeyCode::Char('e') | KeyCode::Char('E') => self.focus_evolution(),
            KeyCode::Char('f') | KeyCode::Char('F') => self.open_evolution_card(),
            KeyCode::Char('t') | KeyCode::Char('T') => self.open_matchups(),
            KeyCode::Char('c') | KeyCode::Char('C') => self.pin_or_compare(),
            KeyCode::Tab | KeyCode::Char('/') => self.focus = Focus::Search,
            KeyCode::Char('l') | KeyCode::Char('L') => self.open_language_picker(),
            KeyCode::Char('s') | KeyCode::Char('S') => self.cycle_sort(),
            KeyCode::Char(' ') => self.toggle_team_membership(),
            KeyCode::Char('p') | KeyCode::Char('P') => self.open_team_card(),
            KeyCode::Char('a') | KeyCode::Char('A') => self.open_abilities(),
            KeyCode::Char('m') | KeyCode::Char('M') => self.open_moves(),
            KeyCode::Char('v') | KeyCode::Char('V') => self.open_forms(),
            KeyCode::Char('x') | KeyCode::Char('X') => self.toggle_shiny(),
            KeyCode::Char('r') | KeyCode::Char('R') => self.open_random(),
            KeyCode::Char('?') => self.help_card = true,
            _ => {}
        }
    }

    /// Loads a species picked at random from the list as it is currently
    /// filtered, the way `Enter` loads the highlighted one.
    ///
    /// Rolling from `filtered` rather than `all_pokemon` is the point:
    /// `type:ghost` then `R` is a random Ghost, and `gen:1` then `R` is a
    /// random Kanto species. It is the one thing in the app that shows you a
    /// species you did not ask for — a fair part of what a Pokedex full of
    /// names you have never heard of is good for.
    fn open_random(&mut self) {
        let Some(pos) = random_index(self.browser.filtered.len()) else {
            return; // an empty list rolls nothing
        };
        self.browser.list_state.select(Some(pos));
        self.request_selected();
    }

    /// Moves focus into the evolution panel, parking the cursor on the species
    /// currently shown in the detail panel.
    fn focus_evolution(&mut self) {
        if self.park_evo_cursor() {
            self.focus = Focus::Evolution;
        }
    }

    /// Opens the full-screen evolution view on the current chain. Same cursor
    /// as the panel, so expanding and collapsing never loses the reader's place.
    fn open_evolution_card(&mut self) {
        if self.park_evo_cursor() {
            self.evo_card = true;
        }
    }

    /// Parks the chain cursor on the species in the detail panel, reporting
    /// whether there is a chain to navigate at all.
    fn park_evo_cursor(&mut self) -> bool {
        let names = self.chain_names();
        if names.is_empty() {
            return false; // no chain to navigate yet
        }
        self.evo_cursor = self
            .selected_name
            .as_ref()
            .and_then(|sel| names.iter().position(|n| n == sel))
            .unwrap_or(0);
        true
    }

    /// The full-screen view is the evolution panel with room to breathe, so it
    /// answers to the same keys — `Esc` (or `F` again) collapses it back.
    fn handle_evo_card_key(&mut self, key: KeyEvent) {
        let len = self.chain_names().len();
        match key.code {
            KeyCode::Esc | KeyCode::Char('f' | 'F' | 'q' | 'Q') => self.evo_card = false,
            KeyCode::Left | KeyCode::Up | KeyCode::Char('h') | KeyCode::Char('k')
                if self.evo_cursor > 0 =>
            {
                self.evo_cursor -= 1;
            }
            KeyCode::Right | KeyCode::Down | KeyCode::Char('l') | KeyCode::Char('j')
                if self.evo_cursor + 1 < len =>
            {
                self.evo_cursor += 1;
            }
            // Taking a stage collapses the view: what you picked is loaded on
            // the panels behind it, and leaving the chain spread over them is
            // the one thing the jump was for.
            KeyCode::Enter => {
                self.jump_to_evolution_member();
                self.evo_card = false;
            }
            KeyCode::Char('x') | KeyCode::Char('X') => self.toggle_shiny(),
            KeyCode::Char('?') => self.help_card = true,
            _ => {}
        }
    }

    fn handle_evolution_key(&mut self, key: KeyEvent) {
        let len = self.chain_names().len();
        match key.code {
            KeyCode::Esc | KeyCode::Tab => self.focus = Focus::List,
            KeyCode::Char('q') | KeyCode::Char('Q') => self.should_quit = true,
            KeyCode::Left | KeyCode::Up | KeyCode::Char('h') | KeyCode::Char('k')
                if self.evo_cursor > 0 =>
            {
                self.evo_cursor -= 1;
            }
            KeyCode::Right | KeyCode::Down | KeyCode::Char('l') | KeyCode::Char('j')
                if self.evo_cursor + 1 < len =>
            {
                self.evo_cursor += 1;
            }
            KeyCode::Enter => self.jump_to_evolution_member(),
            KeyCode::Char('f') | KeyCode::Char('F') => self.evo_card = true,
            KeyCode::Char('t') | KeyCode::Char('T') => self.open_matchups(),
            KeyCode::Char('x') | KeyCode::Char('X') => self.toggle_shiny(),
            KeyCode::Char('?') => self.help_card = true,
            _ => {}
        }
    }

    fn handle_search_key(&mut self, key: KeyEvent) {
        match key.code {
            KeyCode::Esc | KeyCode::Tab => self.focus = Focus::List,
            KeyCode::Enter => {
                self.request_selected();
                self.focus = Focus::List;
            }
            KeyCode::Up => self.move_selection(-1),
            KeyCode::Down => self.move_selection(1),
            KeyCode::Backspace => {
                self.browser.query.pop();
                self.recompute_filter();
            }
            KeyCode::Char(c) => {
                self.browser.query.push(c);
                self.recompute_filter();
            }
            _ => {}
        }
    }

    // --- List / filter helpers -------------------------------------------

    /// Re-filters the sidebar and asks for whatever rosters the new query
    /// needs. The filtering is [`Browser::recompute`]; what this adds is the
    /// fetch, which is the half that cannot live there.
    ///
    /// The requests go out after the pass rather than before it. They are
    /// answered on another task either way, so the list this pass produces is
    /// the same, and reading the terms off the query it just parsed saves
    /// parsing the box twice on every keystroke.
    fn recompute_filter(&mut self) {
        self.browser.recompute();
        self.request_missing_rosters();
    }

    /// True while a filter term is still waiting on its roster, so the sidebar
    /// can say "loading" rather than "no results".
    pub fn awaiting_roster(&self) -> bool {
        self.browser.awaiting_roster()
    }

    fn cycle_sort(&mut self) {
        self.browser.cycle_sort();
    }

    fn move_selection(&mut self, delta: i32) {
        self.browser.move_selection(delta);
    }

    /// Raw API name of the highlighted list entry, if any.
    pub fn current_name(&self) -> Option<String> {
        self.browser.current_name()
    }

    /// Detail record for the panel, if the selection is loaded.
    pub fn selected_detail(&self) -> Option<&PokemonDetail> {
        let name = self.selected_name.as_ref()?;
        self.details.get(name)
    }

    /// Evolution tree for the selected Pokemon, if loaded.
    pub fn selected_evolution(&self) -> Option<&EvolutionTree> {
        let name = self.selected_name.as_ref()?;
        self.evolutions.get(name)
    }

    /// Decoded sprite for the selected Pokemon in the current palette, if one
    /// was loaded.
    pub fn selected_sprite(&self) -> Option<&Sprite> {
        self.sprite_for(self.selected_name.as_deref()?)
    }

    /// True while the detail panel is awaiting its current selection.
    pub fn detail_is_loading(&self) -> bool {
        match (&self.loading_detail, &self.selected_name) {
            (Some(loading), Some(selected)) => loading == selected,
            _ => false,
        }
    }
}

// --- Cache-first resolvers -----------------------------------------------
//
// These run on spawned tasks, so they take everything they need by value or
// shared reference rather than borrowing `App`.

/// Resolves a species from the cache, falling back to the network and storing
/// whatever it had to fetch.
async fn resolve_bundle(client: &reqwest::Client, name: &str, variant: SpriteVariant) -> Message {
    if let Some(bundle) = cache::load_bundle(name).await {
        let sprite =
            resolve_sprite(client, name, bundle.detail.sprite_url_for(variant), variant).await;
        return Message::PokemonLoaded {
            detail: bundle.detail,
            evolution: bundle.evolution,
            sprite,
            variant,
        };
    }
    match api::fetch_pokemon_bundle(client, name, variant).await {
        Ok((detail, evolution, sprite)) => {
            cache::store_bundle(name, &detail, &evolution).await;
            record_sprite(name, sprite.as_ref(), variant).await;
            Message::PokemonLoaded {
                detail,
                evolution,
                sprite,
                variant,
            }
        }
        Err(err) => Message::Error(err.to_string()),
    }
}

/// Cache-first sprite lookup for a species whose artwork URL we already know
/// (because its details came out of the cache alongside it). `url` is the one
/// for `variant`, so a species with no shiny art resolves its normal sprite —
/// stored under the shiny name, since that is the question we asked.
async fn resolve_sprite(
    client: &reqwest::Client,
    name: &str,
    url: Option<&str>,
    variant: SpriteVariant,
) -> Option<Sprite> {
    if let Some(sprite) = cache::load_sprite(name, variant).await {
        return Some(sprite);
    }
    if cache::has_sprite_answer(name, variant).await {
        return None; // asked before: this species genuinely has no artwork
    }
    let Some(url) = url else {
        // The record itself says there is no artwork in either palette. Write
        // that down so the question is not re-asked on every toggle.
        record_sprite(name, None, variant).await;
        return None;
    };
    let sprite = api::fetch_sprite(client, url).await.ok();
    record_sprite(name, sprite.as_ref(), variant).await;
    sprite
}

/// Cache-first sprite lookup for a chain member we know nothing else about.
/// Only the network path has to resolve the artwork URL first.
async fn resolve_named_sprite(
    client: &reqwest::Client,
    name: &str,
    variant: SpriteVariant,
) -> Option<Sprite> {
    if let Some(sprite) = cache::load_sprite(name, variant).await {
        return Some(sprite);
    }
    if cache::has_sprite_answer(name, variant).await {
        return None;
    }
    // Chain members arrive as species names, which are not always valid
    // `/pokemon` keys — see `resolve_default_variety`. The answer is cached
    // under the species name either way, since that is what the UI asks for.
    let variety = resolve_default_variety(client, name).await?;

    match api::fetch_named_sprite(client, &variety, variant).await {
        Ok(sprite) => {
            record_sprite(name, sprite.as_ref(), variant).await;
            sprite
        }
        // A 404 is a permanent answer about the name, so it is worth writing
        // down rather than re-asking on every run.
        Err(ApiError::NotFound(_)) => {
            record_sprite(name, None, variant).await;
            None
        }
        // A transient failure must not be written down as "no artwork", or the
        // species would stay blank for as long as the cache lives.
        Err(_) => None,
    }
}

/// The `/pokemon` key a species' artwork is filed under, cache first.
///
/// Most of the time this is the species name itself, but a species whose
/// default form has its own name (`giratina` -> `giratina-altered`) has no
/// `/pokemon` entry under the bare name at all, and its card would otherwise
/// stay blank forever.
///
/// `name` can also arrive already being a variety (`raichu-alola`, straight out
/// of the master list), which has no species record of its own. That 404 means
/// "the name is its own key" — cached like any other answer, so the failing
/// request happens once per install rather than once per view.
async fn resolve_default_variety(client: &reqwest::Client, name: &str) -> Option<String> {
    if let Some(variety) = cache::load_default_variety(name).await {
        return Some(variety);
    }
    let variety = match api::fetch_default_variety(client, name).await {
        Ok(variety) => variety,
        Err(ApiError::NotFound(_)) => name.to_string(),
        // Nothing was learned, so nothing is written down; the next run asks
        // again rather than filing a network hiccup as a fact.
        Err(_) => return None,
    };
    cache::store_default_variety(name, &variety).await;
    Some(variety)
}

/// Resolves one ability's localized text, cache first.
async fn resolve_ability(client: &reqwest::Client, name: &str) -> Option<AbilityInfo> {
    if let Some(info) = cache::load_ability(name).await {
        return Some(info);
    }
    let info = api::fetch_ability(client, name).await.ok()?;
    cache::store_ability(name, &info).await;
    Some(info)
}

/// Resolves one move's record from the cache, falling back to the network.
async fn resolve_move(client: &reqwest::Client, name: &str) -> Option<MoveInfo> {
    if let Some(info) = cache::load_move(name).await {
        return Some(info);
    }
    let info = api::fetch_move(client, name).await.ok()?;
    cache::store_move(name, &info).await;
    Some(info)
}

/// Resolves one filter term's roster from the cache, falling back to the
/// network.
///
/// A failure yields an empty roster rather than an error: the only way to get
/// here is something typed in the search box, and the honest answer to a term
/// we cannot resolve is that nothing matches it.
async fn resolve_roster(client: &reqwest::Client, term: &RosterTerm) -> Vec<String> {
    if let Some(members) = cache::load_roster(term).await {
        return members;
    }
    match api::fetch_roster(client, term).await {
        Ok(members) => {
            cache::store_roster(term, &members).await;
            members
        }
        Err(_) => Vec::new(),
    }
}

/// Stores a freshly fetched sprite, or the fact that there wasn't one, so the
/// next run does not repeat the request either way. Recorded per palette: a
/// species can be cached shiny and unknown normal, or the other way round.
async fn record_sprite(name: &str, sprite: Option<&Sprite>, variant: SpriteVariant) {
    match sprite {
        Some(sprite) => cache::store_sprite(name, sprite, variant).await,
        None => cache::store_missing_sprite(name, variant).await,
    }
}

/// A position in `0..len`, or `None` when there is nowhere to land.
///
/// The clock's nanoseconds are the whole generator. Choosing one Pokemon out
/// of a list is not a use that justifies a dependency: `rand` would bring a
/// handful of crates for a roll that only has to be different from the last
/// one, and the sub-second part of "now" is that on every real clock.
fn random_index(len: usize) -> Option<usize> {
    if len == 0 {
        return None;
    }
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|since| since.subsec_nanos())
        .unwrap_or(0);
    Some(nanos as usize % len)
}

/// An app with `entries` as its master list and nothing in flight.
///
/// `App::new` touches no network of its own — it only builds the client the
/// fetch tasks would use, and the receiver dropped here means nothing is
/// listening if one ever did — so this stays a plain unit test. It lives out
/// here rather than in the test module below because the renderer's tests
/// need an app to draw, and one way of building one is enough.
#[cfg(test)]
pub(crate) fn app_listing(entries: &[(u32, &str)]) -> App {
    let (mut app, _rx) = App::new(Startup::default()).expect("client builds");
    app.browser.all = entries
        .iter()
        .map(|&(id, name)| PokemonEntry {
            name: name.to_string(),
            id,
        })
        .collect();
    app
}

/// A loaded record for `name`, empty apart from it. Tests that care about a
/// field set it; the rest are what a species the app has never heard of would
/// look like, which is exactly what the panels have to survive.
#[cfg(test)]
pub(crate) fn loaded(name: &str) -> PokemonDetail {
    PokemonDetail {
        name: name.to_string(),
        species: name.to_string(),
        forms: Vec::new(),
        dex_number: 0,
        is_legendary: false,
        is_mythical: false,
        is_baby: false,
        types: Vec::new(),
        abilities: Vec::new(),
        stats: Vec::new(),
        height: 0,
        weight: 0,
        sprite_url: None,
        shiny_sprite_url: None,
        genera: std::collections::HashMap::new(),
        flavors: std::collections::HashMap::new(),
        moves: Vec::new(),
        learnset_games: None,
        field: crate::models::FieldData::default(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::RosterKind;
    use crate::query::Query;

    /// The membership set a roster resolves to.
    fn members(names: &[&str]) -> HashSet<String> {
        names.iter().map(|n| n.to_string()).collect()
    }

    /// The names currently visible in the sidebar, in order.
    fn visible(app: &App) -> Vec<&str> {
        app.browser
            .filtered
            .iter()
            .map(|&idx| app.browser.all[idx].name.as_str())
            .collect()
    }

    /// A chain of `names`, each stage evolving into the next.
    fn line(names: &[&str]) -> EvolutionTree {
        let mut node = EvolutionTree {
            name: names[names.len() - 1].to_string(),
            condition: None,
            children: Vec::new(),
        };
        for name in names.iter().rev().skip(1) {
            node = EvolutionTree {
                name: (*name).to_string(),
                condition: None,
                children: vec![node],
            };
        }
        node
    }

    fn press(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    #[test]
    fn taking_a_stage_collapses_the_full_screen_chain() {
        let mut app = app_listing(&[(1, "bulbasaur"), (2, "ivysaur")]);
        // Artwork is the other thing a selection spawns fetches for.
        app.color_depth = Depth::None;
        app.recompute_filter();
        app.details
            .insert("bulbasaur".to_string(), loaded("bulbasaur"));
        app.details.insert("ivysaur".to_string(), loaded("ivysaur"));
        app.selected_name = Some("bulbasaur".to_string());
        app.evolutions
            .insert("bulbasaur".to_string(), line(&["bulbasaur", "ivysaur"]));

        app.open_evolution_card();
        assert!(app.evo_card);
        // The cursor opens on the species already in the detail panel.
        assert_eq!(app.evo_cursor, 0);

        app.handle_evo_card_key(press(KeyCode::Right));
        app.handle_evo_card_key(press(KeyCode::Enter));

        // Ivysaur is loaded, and the chain is out of the way of it.
        assert_eq!(app.selected_name.as_deref(), Some("ivysaur"));
        assert!(!app.evo_card);
    }

    #[test]
    fn the_comparison_key_pins_then_compares_then_lets_go() {
        let mut app = app_listing(&[(94, "gengar"), (65, "alakazam")]);
        app.recompute_filter();
        app.details.insert("gengar".to_string(), loaded("gengar"));
        app.details
            .insert("alakazam".to_string(), loaded("alakazam"));

        // First press pins what is on display, and nothing opens yet: a
        // comparison needs the second species.
        app.selected_name = Some("gengar".to_string());
        app.pin_or_compare();
        assert!(app.is_pinned("gengar"));
        assert!(!app.compare_card);

        // A second, different species opens the card, pinned side first.
        app.selected_name = Some("alakazam".to_string());
        app.pin_or_compare();
        assert!(app.compare_card);
        let (left, right) = app.comparison().expect("two loaded records");
        assert_eq!(
            (left.name.as_str(), right.name.as_str()),
            ("gengar", "alakazam")
        );

        // Pressing it on the pinned species is how the pin is let go of.
        app.compare_card = false;
        app.selected_name = Some("gengar".to_string());
        app.pin_or_compare();
        assert!(!app.is_pinned("gengar"));
        assert!(!app.compare_card);
    }

    #[test]
    fn the_comparison_key_on_the_party_card_pins_then_compares_then_lets_go() {
        // The sibling of the list test above: pinning from the card has to
        // leave exactly the state pinning from the list does, or the two
        // routes to a comparison would drift apart.
        let mut app = app_listing(&[(94, "gengar"), (65, "alakazam")]);
        app.color_depth = Depth::None;
        app.recompute_filter();
        app.details.insert("gengar".to_string(), loaded("gengar"));
        app.details
            .insert("alakazam".to_string(), loaded("alakazam"));
        app.team = vec!["gengar".to_string(), "alakazam".to_string()];
        app.open_team_card();

        // First press pins the member under the cursor and nothing opens yet.
        app.handle_team_key(press(KeyCode::Char('c')));
        assert!(app.is_pinned("gengar"));
        assert!(!app.compare_card);
        assert!(app.team_card, "pinning alone does not close the card");

        // On a second, different member the head-to-head opens, pinned side
        // first, with that member put on display to be the other side.
        app.handle_team_key(press(KeyCode::Down));
        app.handle_team_key(press(KeyCode::Char('c')));
        assert!(app.compare_card);
        assert!(!app.team_card, "the comparison takes the card's place");
        assert_eq!(app.selected_name.as_deref(), Some("alakazam"));
        let (left, right) = app.comparison().expect("two loaded records");
        assert_eq!(
            (left.name.as_str(), right.name.as_str()),
            ("gengar", "alakazam")
        );

        // Pressing it on the pinned member is how the pin is let go of.
        app.compare_card = false;
        app.open_team_card();
        app.handle_team_key(press(KeyCode::Char('c')));
        assert!(!app.is_pinned("gengar"));
        assert!(!app.compare_card);
    }

    #[test]
    fn a_party_member_still_loading_is_not_pinned_from_the_card() {
        let mut app = app_listing(&[(94, "gengar")]);
        app.recompute_filter();
        // In the party, but its record has not landed yet.
        app.team = vec!["gengar".to_string()];
        app.open_team_card();

        app.handle_team_key(press(KeyCode::Char('c')));
        assert!(app.pin.is_none());
    }

    #[test]
    fn the_party_cursor_wraps_and_an_empty_party_has_nowhere_to_put_it() {
        let mut app = app_listing(&[]);
        app.team = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        app.open_team_card();
        app.handle_team_key(press(KeyCode::Up));
        assert_eq!(app.team_cursor, 2);
        app.handle_team_key(press(KeyCode::Down));
        assert_eq!(app.team_cursor, 0);

        app.team.clear();
        app.open_team_card();
        app.handle_team_key(press(KeyCode::Down));
        assert_eq!(app.team_cursor, 0);
        app.handle_team_key(press(KeyCode::Char('c')));
        assert!(app.pin.is_none());
    }

    #[test]
    fn showing_a_species_the_filter_hides_clears_the_box_and_a_filter_it_passes_is_kept() {
        let mut app = app_listing(&[(94, "gengar"), (65, "alakazam")]);
        app.color_depth = Depth::None;
        app.details.insert("gengar".to_string(), loaded("gengar"));
        app.details
            .insert("alakazam".to_string(), loaded("alakazam"));

        app.browser.query = "gen".to_string();
        app.recompute_filter();
        assert!(app.show_species("gengar"));
        assert_eq!(
            app.browser.query, "gen",
            "gengar matches, so the filter stays"
        );
        assert_eq!(app.selected_name.as_deref(), Some("gengar"));

        assert!(app.show_species("alakazam"));
        assert_eq!(
            app.browser.query, "",
            "alakazam did not, so the box was cleared"
        );
        assert_eq!(app.selected_name.as_deref(), Some("alakazam"));

        assert!(!app.show_species("missingno"), "not in the list at all");
    }

    /// A loaded record listing the varieties its species ships as.
    fn with_forms(name: &str, species: &str, forms: &[&str]) -> PokemonDetail {
        PokemonDetail {
            species: species.to_string(),
            forms: forms.iter().map(|f| f.to_string()).collect(),
            ..loaded(name)
        }
    }

    /// A list holding Raichu and its Alolan form, with both records loaded and
    /// Raichu on display — the state the forms card is opened from.
    fn app_with_raichu() -> App {
        let mut app = app_listing(&[(26, "raichu"), (10100, "raichu-alola")]);
        app.color_depth = Depth::None;
        app.recompute_filter();
        for name in ["raichu", "raichu-alola"] {
            app.details.insert(
                name.to_string(),
                with_forms(name, "raichu", &["raichu", "raichu-alola"]),
            );
        }
        assert!(app.show_species("raichu"));
        app
    }

    #[test]
    fn the_forms_card_opens_on_the_form_shown_and_jumps_to_the_one_picked() {
        let mut app = app_with_raichu();

        // The cursor starts on the variety in the detail panel, so the card
        // opens where the reader is.
        app.open_forms();
        assert!(app.forms_card);
        assert_eq!(app.forms_cursor, 0);

        // Enter on another form loads it and takes the card away, which is
        // the whole of what it was open for.
        app.handle_forms_key(press(KeyCode::Down));
        app.handle_forms_key(press(KeyCode::Enter));
        assert_eq!(app.selected_name.as_deref(), Some("raichu-alola"));
        assert!(!app.forms_card);

        // And from the form, the card is the way back: it opens on the form
        // now shown, and the base species is what moving reaches.
        app.open_forms();
        assert_eq!(app.forms_cursor, 1);
        app.handle_forms_key(press(KeyCode::Up));
        app.handle_forms_key(press(KeyCode::Enter));
        assert_eq!(app.selected_name.as_deref(), Some("raichu"));
    }

    #[test]
    fn a_species_with_one_variety_has_no_card_to_open() {
        // Opening a card that lists only what is already on screen would say
        // nothing, so the key does nothing instead.
        let mut app = app_listing(&[(483, "dialga")]);
        app.color_depth = Depth::None;
        app.recompute_filter();
        app.details.insert(
            "dialga".to_string(),
            with_forms("dialga", "dialga", &["dialga"]),
        );
        assert!(app.show_species("dialga"));

        app.open_forms();
        assert!(!app.forms_card);

        // Nor before anything has loaded: there are no forms to list yet.
        let mut empty = app_listing(&[(1, "bulbasaur")]);
        empty.open_forms();
        assert!(!empty.forms_card);
        assert!(empty.forms().is_empty());
    }

    #[test]
    fn the_forms_cursor_wraps_at_both_ends() {
        let mut app = app_with_raichu();
        app.open_forms();
        app.handle_forms_key(press(KeyCode::Up));
        assert_eq!(app.forms_cursor, 1);
        app.handle_forms_key(press(KeyCode::Down));
        assert_eq!(app.forms_cursor, 0);

        // V closes the card it opened, the way every other overlay's key does.
        app.handle_forms_key(press(KeyCode::Char('v')));
        assert!(!app.forms_card);
    }

    #[test]
    fn a_roll_lands_inside_the_current_filter_and_never_outside_it() {
        // Every roll has to come out of `filtered`, not `all_pokemon`: the
        // filter is what makes `R` a random Ghost rather than a random entry.
        let mut app = app_listing(&[
            (92, "gastly"),
            (93, "haunter"),
            (94, "gengar"),
            (25, "pikachu"),
        ]);
        app.color_depth = Depth::None;
        app.browser.rosters.insert(
            RosterTerm::new(RosterKind::Type, "ghost"),
            members(&["gastly", "haunter", "gengar"]),
        );
        for name in ["gastly", "haunter", "gengar", "pikachu"] {
            app.details.insert(name.to_string(), loaded(name));
        }
        app.browser.query = "type:ghost".to_string();
        app.recompute_filter();

        for _ in 0..50 {
            app.open_random();
            let landed = app.selected_name.clone().expect("a roll loads something");
            assert!(
                ["gastly", "haunter", "gengar"].contains(&landed.as_str()),
                "{landed} is not in the filter"
            );
            let pos = app.browser.list_state.selected().expect("the cursor moved");
            assert!(
                pos < app.browser.filtered.len(),
                "the cursor is inside the filtered list"
            );
        }
    }

    #[test]
    fn rolling_on_an_empty_list_does_nothing() {
        let mut app = app_listing(&[(1, "bulbasaur")]);
        app.browser.query = "nothing-matches-this".to_string();
        app.recompute_filter();
        assert!(app.browser.filtered.is_empty());

        app.open_random();
        assert_eq!(
            app.browser.list_state.selected(),
            None,
            "the cursor stays parked"
        );
        assert_eq!(app.selected_name, None, "nothing was loaded");
    }

    #[test]
    fn a_roll_over_one_row_always_lands_on_it() {
        assert_eq!(random_index(1), Some(0));
        assert_eq!(random_index(0), None);
        let pos = random_index(7).expect("a non-empty list has a position");
        assert!(pos < 7);
    }

    #[test]
    fn a_species_still_loading_is_not_pinned() {
        let mut app = app_listing(&[(94, "gengar")]);
        app.recompute_filter();
        // Named as the selection, but its record has not landed yet.
        app.selected_name = Some("gengar".to_string());

        app.pin_or_compare();
        assert!(app.pin.is_none());
    }

    #[test]
    fn the_full_screen_chain_does_not_open_on_a_species_with_no_chain_loaded() {
        let mut app = app_listing(&[(1, "bulbasaur")]);
        app.recompute_filter();
        app.selected_name = Some("bulbasaur".to_string());

        app.open_evolution_card();
        assert!(!app.evo_card);
    }

    #[test]
    fn roster_terms_of_different_kinds_narrow_together() {
        // `egg:grass` also has to survive the trip through the alias table on
        // the way to the group PokeAPI files as `plant`.
        let mut app = app_listing(&[(1, "bulbasaur"), (43, "oddish"), (92, "gastly")]);
        app.browser.rosters.insert(
            RosterTerm::new(RosterKind::Type, "poison"),
            members(&["bulbasaur", "oddish", "gastly"]),
        );
        app.browser.rosters.insert(
            RosterTerm::new(RosterKind::EggGroup, "plant"),
            members(&["bulbasaur", "oddish"]),
        );

        app.browser.query = "type:poison".to_string();
        app.recompute_filter();
        assert_eq!(visible(&app), ["bulbasaur", "oddish", "gastly"]);

        app.browser.query = "type:poison egg:grass".to_string();
        app.recompute_filter();
        assert_eq!(visible(&app), ["bulbasaur", "oddish"]);
    }

    #[test]
    fn the_list_waits_until_every_roster_it_needs_has_landed() {
        // Each roster arrives on its own message, and until the last one does
        // the sidebar has to say "loading" rather than "no results" — an
        // unresolved term matches nothing, so the two look identical from the
        // list alone.
        let mut app = app_listing(&[]);
        app.browser.parsed = Query::parse("type:poison ability:levitate");
        assert!(app.awaiting_roster());

        app.browser
            .rosters
            .insert(RosterTerm::new(RosterKind::Type, "poison"), HashSet::new());
        assert!(app.awaiting_roster());

        app.browser.rosters.insert(
            RosterTerm::new(RosterKind::Ability, "levitate"),
            HashSet::new(),
        );
        assert!(!app.awaiting_roster());
    }

    #[test]
    fn the_moves_cursor_stops_at_both_ends_of_the_learnset() {
        // Wrapping would be worse than stopping here: a learnset is one long
        // list, and jumping from the last tutor move back to level one loses
        // the reader's place rather than saving them a keypress.
        let mut app = app_listing(&[]);
        app.move_move_cursor(-1, 3);
        assert_eq!(app.move_cursor, 0);
        app.move_move_cursor(10, 3);
        assert_eq!(app.move_cursor, 2);
        // An empty learnset has no row to land on.
        app.move_cursor = 0;
        app.move_move_cursor(1, 0);
        assert_eq!(app.move_cursor, 0);
    }

    #[test]
    fn an_app_with_nothing_in_flight_is_idle() {
        assert!(!app_listing(&[]).is_busy());
    }

    #[test]
    fn any_one_pending_request_is_enough_to_keep_the_spinner_turning() {
        // One arm per kind of request. All of them put a spinner on screen, so
        // all of them have to keep the ticker alive; a kind missing from
        // `is_busy` would show as a frozen spinner, which is the failure this
        // pins down.
        /// What kind of request to start, and how to start it.
        type Pending = (&'static str, fn(&mut App));

        let cases: [Pending; 7] = [
            ("list", |app| app.list_loading = true),
            ("detail", |app| app.loading_detail = Some("mew".to_string())),
            ("roster", |app| {
                app.roster_loading
                    .insert(RosterTerm::new(RosterKind::Type, "ghost"));
            }),
            ("ability", |app| {
                app.ability_loading.insert("levitate".to_string());
            }),
            ("translation", |app| {
                app.translating
                    .insert(("mew".to_string(), "tr".to_string()));
            }),
            ("party member", |app| {
                app.team_loading.insert("mew".to_string());
            }),
            ("sprite", |app| {
                app.sprite_loading
                    .entry(SpriteVariant::Normal)
                    .or_default()
                    .insert("mew".to_string());
            }),
        ];

        for (kind, begin) in cases {
            let mut app = app_listing(&[]);
            begin(&mut app);
            assert!(
                app.is_busy(),
                "a pending {kind} request should read as busy"
            );
        }
    }

    #[test]
    fn a_pending_set_that_has_drained_stops_counting() {
        // `sprite_loading` keeps one set per palette and the sets outlive their
        // contents. Testing the map for emptiness rather than its sets would
        // leave the app busy — and redrawing on a timer — forever after the
        // first sprite it ever fetched.
        let mut app = app_listing(&[]);
        app.sprite_loading.entry(SpriteVariant::Normal).or_default();
        assert!(!app.is_busy());
    }

    #[test]
    fn a_named_species_wins_the_cursor_over_the_longer_name_that_sorts_first() {
        let mut app = app_listing(&[(150, "mewtwo"), (151, "mew")]);
        app.select_named_species("Mew".to_string());

        assert_eq!(
            app.browser.query, "mew",
            "the box shows what narrowed the list"
        );
        assert_eq!(
            app.browser.filtered.len(),
            2,
            "Mewtwo still matches the text"
        );
        assert_eq!(app.current_name().as_deref(), Some("mew"));
    }

    #[test]
    fn a_name_reaching_the_box_carries_its_search_syntax_with_it() {
        let mut app = app_listing(&[(25, "pikachu"), (26, "raichu")]);
        app.select_named_species("dex:26".to_string());

        assert_eq!(app.current_name().as_deref(), Some("raichu"));
    }

    #[test]
    fn a_name_matching_nothing_lands_on_the_empty_list_rather_than_an_error() {
        let mut app = app_listing(&[(1, "bulbasaur")]);
        app.select_named_species("gengr".to_string());

        assert!(app.browser.filtered.is_empty());
        assert_eq!(app.current_name(), None, "nothing to load, nothing loaded");
        assert_eq!(
            app.browser.query, "gengr",
            "and the box says why the list is empty"
        );
    }

    #[test]
    fn a_lang_flag_outranks_the_language_the_last_run_left_behind() {
        let (mut app, _rx) = App::new(Startup {
            language: Some(Language::Turkish),
            ..Startup::default()
        })
        .expect("client builds");
        app.restore(Session {
            language: Some("de".to_string()),
            ..Session::default()
        });

        assert_eq!(app.language, Language::Turkish);
    }

    #[test]
    fn without_the_flag_the_stored_language_is_still_what_comes_back() {
        let (mut app, _rx) = App::new(Startup::default()).expect("client builds");
        app.restore(Session {
            language: Some("de".to_string()),
            ..Session::default()
        });

        assert_eq!(app.language, Language::German);
    }

    #[test]
    fn a_theme_flag_outranks_the_palette_the_last_run_left_behind() {
        // The same rule as `--lang`, and worth pinning separately: both are
        // read out of one session file, and getting one right says nothing
        // about the other.
        let (mut app, _rx) = App::new(Startup {
            theme: Some(Theme::Pico8),
            ..Startup::default()
        })
        .expect("client builds");
        app.restore(Session {
            theme: Some("dmg".to_string()),
            ..Session::default()
        });
        assert_eq!(app.theme, Theme::Pico8);

        // Without the flag, the stored palette is what comes back.
        let (mut app, _rx) = App::new(Startup::default()).expect("client builds");
        app.restore(Session {
            theme: Some("dmg".to_string()),
            ..Session::default()
        });
        assert_eq!(app.theme, Theme::Dmg);
        assert_eq!(
            app.snapshot().theme.as_deref(),
            Some("dmg"),
            "and is what this run hands on"
        );
    }

    #[test]
    fn a_session_naming_a_palette_this_build_does_not_have_keeps_the_default() {
        let (mut app, _rx) = App::new(Startup::default()).expect("client builds");
        app.restore(Session {
            theme: Some("cga".to_string()),
            ..Session::default()
        });
        assert_eq!(app.theme, Theme::default());
    }
}