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
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
//! All `ratatui` rendering. Pure functions of [`App`] state — given the same
//! state they always draw the same frame, which keeps the loop trivial.

use ratatui::layout::{Alignment, Constraint, Layout, Position, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Clear, List, ListItem, Paragraph, Wrap};
use ratatui::Frame;

use crate::app::{App, Focus};
use crate::browser::SortKey;
use crate::color;
use crate::compare;
use crate::i18n::{EvoStrings, Language, Strings};
use crate::models::{
    egg_group_label, form_label, title_case, CatchEase, EvolutionTree, FieldData, LearnMethod,
    LearnedMove, PokemonDetail, Sprite,
};
use crate::team::{self, AbilityImmunity};
use crate::theme;
use crate::typechart;

const SPINNER: [&str; 10] = ["", "", "", "", "", "", "", "", "", ""];
/// Column width reserved for stat labels (longest is "Verteid."/"Sp. Def").
const STAT_LABEL_WIDTH: usize = 9;

/// Entry point called once per frame by the event loop.
pub fn render(frame: &mut Frame, app: &mut App) {
    let area = frame.area();
    let strings = app.language.strings();

    // Paint the whole background first so gaps share the pastel base color.
    frame.render_widget(
        Block::default().style(Style::default().bg(theme::base())),
        area,
    );

    let rows = Layout::vertical([
        Constraint::Length(1), // header
        Constraint::Min(0),    // body
        Constraint::Length(1), // footer / help
    ])
    .split(area);

    render_header(frame, app, &strings, rows[0]);
    render_footer(frame, &strings, rows[2]);

    let cols =
        Layout::horizontal([Constraint::Percentage(32), Constraint::Percentage(68)]).split(rows[1]);

    render_sidebar(frame, app, &strings, cols[0]);

    let right =
        Layout::vertical([Constraint::Percentage(58), Constraint::Percentage(42)]).split(cols[1]);
    render_details(frame, app, &strings, right[0]);
    render_evolution(frame, app, &strings, right[1]);

    // The overlay cards float above everything when open. Only one can be open
    // at a time (input is modal), so the draw order is arbitrary.
    if app.matchups {
        render_matchups(frame, app, &strings, area);
    }
    if app.ability_card {
        render_abilities(frame, app, &strings, area);
    }
    if app.moves_card {
        render_moves(frame, app, &strings, area);
    }
    if app.team_card {
        render_team(frame, app, &strings, area);
    }
    if app.forms_card {
        render_forms(frame, app, &strings, area);
    }
    if app.language_picker {
        render_language_picker(frame, app, &strings, area);
    }
    if app.evo_card {
        render_evolution_card(frame, app, &strings, area);
    }
    if app.compare_card {
        render_compare(frame, app, &strings, area);
    }
    // Drawn last: help must land on top of whatever it is explaining.
    if app.help_card {
        render_help(frame, &strings, area);
    }
}

fn render_header(frame: &mut Frame, app: &App, s: &Strings, area: Rect) {
    let cols = Layout::horizontal([Constraint::Min(0), Constraint::Length(12)]).split(area);

    let title = Paragraph::new(Line::from(Span::styled(
        s.app_title,
        Style::default()
            .fg(theme::mauve())
            .add_modifier(Modifier::BOLD),
    )));
    frame.render_widget(title, cols[0]);

    let tag = Paragraph::new(Line::from(vec![
        Span::styled("", Style::default().fg(theme::peach())),
        Span::styled(
            app.language.tag(),
            Style::default()
                .fg(theme::peach())
                .add_modifier(Modifier::BOLD),
        ),
    ]))
    .alignment(Alignment::Right);
    frame.render_widget(tag, cols[1]);
}

fn render_footer(frame: &mut Frame, s: &Strings, area: Rect) {
    let footer = Paragraph::new(Line::from(Span::styled(
        s.help,
        Style::default().fg(theme::subtext()),
    )))
    .style(Style::default().bg(theme::surface()))
    .alignment(Alignment::Center);
    frame.render_widget(footer, area);
}

fn render_sidebar(frame: &mut Frame, app: &mut App, s: &Strings, area: Rect) {
    let rows = Layout::vertical([Constraint::Length(3), Constraint::Min(0)]).split(area);

    // --- Search box ---
    let search_focused = app.focus == Focus::Search;
    let search_block = panel_block(s.search_title, search_focused);
    let cursor = if search_focused { "" } else { "" };
    let query_line = if app.browser.query.is_empty() && !search_focused {
        Line::from(Span::styled(
            s.search_hint,
            Style::default().fg(theme::overlay()),
        ))
    } else {
        Line::from(vec![
            Span::styled("🔍 ", Style::default().fg(theme::sapphire())),
            Span::styled(
                app.browser.query.clone(),
                Style::default().fg(theme::text()),
            ),
            Span::styled(cursor, Style::default().fg(theme::mauve())),
        ])
    };
    frame.render_widget(Paragraph::new(query_line).block(search_block), rows[0]);

    // --- List ---
    let list_focused = app.focus == Focus::List;
    let sort_badge = match app.browser.sort {
        SortKey::Dex => s.sort_dex,
        SortKey::Name => s.sort_name,
    };
    let title = format!(
        "{}({}) ⇅ {} ",
        s.sidebar_title,
        app.browser.filtered.len(),
        sort_badge
    );
    let list_block = panel_block_owned(title, list_focused);
    let inner = list_block.inner(rows[1]);
    frame.render_widget(&list_block, rows[1]);

    if app.list_loading {
        render_centered_loading(frame, inner, s.loading_list, app.spinner);
        return;
    }
    // A `type:`, `ability:` or `egg:` filter cannot match anything until its
    // roster arrives, so say that rather than claiming the search found
    // nothing.
    if app.awaiting_roster() {
        render_centered_loading(frame, inner, s.loading_filter, app.spinner);
        return;
    }
    if app.browser.filtered.is_empty() {
        render_centered_text(frame, inner, s.no_results, theme::overlay());
        return;
    }

    let items: Vec<ListItem> = app
        .browser
        .filtered
        .iter()
        .filter_map(|&idx| app.browser.all.get(idx))
        .map(|p| {
            // Alternate forms have no dex number; their column stays blank so
            // the names below still line up.
            let dex = match p.dex_number() {
                Some(number) => format!("{number:>4} "),
                None => " ".repeat(5),
            };
            // Two slots, each with a meaning of its own: the comparison pin on
            // the left, party membership on the right. A species can be both,
            // and each keeps its column whether or not the other is there, so
            // a marker always means the same thing in the same place.
            let pin = if app.is_pinned(&p.name) { "" } else { " " };
            let party = if app.is_in_team(&p.name) { "" } else { " " };
            ListItem::new(Line::from(vec![
                Span::styled(pin, Style::default().fg(theme::teal())),
                Span::styled(party, Style::default().fg(theme::green())),
                Span::styled(dex, Style::default().fg(theme::overlay())),
                Span::styled(title_case(&p.name), Style::default().fg(theme::text())),
            ]))
        })
        .collect();

    let list = List::new(items)
        .highlight_symbol("")
        .highlight_style(color::highlight(theme::mauve()).add_modifier(Modifier::BOLD));
    frame.render_stateful_widget(list, inner, &mut app.browser.list_state);
}

fn render_details(frame: &mut Frame, app: &App, s: &Strings, area: Rect) {
    let block = panel_block(s.details_title, false);
    let inner = block.inner(area);
    frame.render_widget(block, area);

    if app.detail_is_loading() {
        render_centered_loading(frame, inner, s.loading, app.spinner);
        return;
    }

    let Some(detail) = app.selected_detail() else {
        match &app.error {
            Some(err) => render_error(frame, inner, s, err),
            None => render_centered_text(frame, inner, s.no_selection, theme::overlay()),
        }
        return;
    };

    // Carve out a square column on the left for the sprite when the panel is
    // wide and tall enough to host one; otherwise the info text spans the full
    // width as before.
    let info = match app.selected_sprite() {
        Some(sprite) if inner.width >= 46 && inner.height >= 6 => {
            let sprite_w = sprite_col_width(inner);
            let cols = Layout::horizontal([
                Constraint::Length(sprite_w),
                Constraint::Length(2),
                Constraint::Min(0),
            ])
            .split(inner);
            render_sprite(frame, cols[0], sprite);
            cols[2]
        }
        _ => inner,
    };

    let mut lines: Vec<Line> = Vec::new();

    let mut title_spans = vec![
        Span::styled(
            title_case(&detail.name),
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("   #{:04}", detail.dex_number),
            Style::default().fg(theme::overlay()),
        ),
    ];
    // Say so when the artwork is shiny: an unfamiliar palette otherwise reads
    // as a rendering bug rather than a deliberate choice.
    if app.sprite_variant.is_shiny() {
        title_spans.push(Span::styled(
            format!("{}", s.shiny_label),
            Style::default()
                .fg(theme::yellow())
                .add_modifier(Modifier::BOLD),
        ));
    }
    lines.push(Line::from(title_spans));

    // Pokedex genus, e.g. "Seed Pokémon" — the headline of the info card, in the
    // active language where PokeAPI has it.
    let lang_code = app.language.flavor_code();
    if let Some(genus) = detail.genus_for(lang_code) {
        lines.push(Line::from(Span::styled(
            genus.to_string(),
            Style::default()
                .fg(theme::peach())
                .add_modifier(Modifier::ITALIC),
        )));
    }

    // Special-category badges (Legendary / Mythical / Baby), as little chips.
    let mut badges: Vec<(&str, ratatui::style::Color)> = Vec::new();
    if detail.is_legendary {
        badges.push((s.legendary_label, theme::yellow()));
    }
    if detail.is_mythical {
        badges.push((s.mythical_label, theme::pink()));
    }
    if detail.is_baby {
        badges.push((s.baby_label, theme::teal()));
    }
    if !badges.is_empty() {
        let mut spans = Vec::new();
        for (label, color) in badges {
            spans.push(Span::styled(
                format!("{label} "),
                Style::default()
                    .fg(theme::base())
                    .bg(color)
                    .add_modifier(Modifier::BOLD),
            ));
            spans.push(Span::raw(" "));
        }
        lines.push(Line::from(spans));
    }

    // Type chips.
    let mut type_spans = vec![Span::styled(
        format!("{}: ", s.types_label),
        Style::default().fg(theme::subtext()),
    )];
    type_spans.extend(type_chips(&detail.types));
    lines.push(Line::from(type_spans));

    // Ability names. These come in the same payload as the types, so the row
    // costs nothing; the descriptions behind `A` are what need a request.
    if !detail.abilities.is_empty() {
        let entries: Vec<String> = detail
            .abilities
            .iter()
            .map(|ability| {
                let name = ability_display_name(app, &ability.name);
                match ability.is_hidden {
                    true => format!("{name} ({})", s.ability_hidden),
                    false => name,
                }
            })
            .collect();
        lines.extend(label_rows(
            s.abilities_label,
            &entries.join(" · "),
            info.width as usize,
        ));
    }

    // The species' other varieties. They are ordinary entries in the master
    // list and have always been reachable by typing their names, but nothing
    // on Raichu's card said an Alolan form existed. This row is where it says
    // so; `V` opens the card that jumps to one. A species with a single
    // variety gets no row, rather than one listing itself.
    let forms = detail.other_forms();
    if !forms.is_empty() {
        let labels: Vec<String> = forms
            .iter()
            .map(|form| form_label(form, &detail.species))
            .collect();
        lines.extend(label_rows(
            s.forms_label,
            &labels.join(" · "),
            info.width as usize,
        ));
    }

    lines.push(Line::from(vec![
        Span::styled(
            format!("{}: ", s.height_label),
            Style::default().fg(theme::subtext()),
        ),
        Span::styled(
            format!("{:.1} m", detail.height as f32 / 10.0),
            Style::default().fg(theme::text()),
        ),
        Span::raw("    "),
        Span::styled(
            format!("{}: ", s.weight_label),
            Style::default().fg(theme::subtext()),
        ),
        Span::styled(
            format!("{:.1} kg", detail.weight as f32 / 10.0),
            Style::default().fg(theme::text()),
        ),
    ]));
    lines.push(Line::raw(""));

    // Stat bars sized to the available width.
    let bar_width = (info.width as usize).saturating_sub(STAT_LABEL_WIDTH + 6);
    for stat in &detail.stats {
        lines.push(stat_line(
            app.language.stat_label(stat.kind),
            stat.base,
            bar_width,
        ));
    }

    lines.push(Line::raw(""));
    lines.push(Line::from(vec![
        Span::styled(
            format!("{}: ", s.total_label),
            Style::default().fg(theme::subtext()),
        ),
        Span::styled(
            detail.stat_total().to_string(),
            Style::default()
                .fg(theme::lavender())
                .add_modifier(Modifier::BOLD),
        ),
    ]));

    // The field-guide half of the entry — breeding groups, gender ratio, catch
    // rate, growth, habitat — packed as many facts to a row as the column is
    // wide. Shown when the column has the rows for it, ahead of the flavour
    // blurb below: on a terminal with room for only one of them, the facts
    // are the half of the entry the card was missing, and the blurb is prose.
    let facts = field_rows(&detail.field, s, info.width as usize);
    if !facts.is_empty() && info.height as usize >= lines.len() + 1 + facts.len() {
        lines.push(Line::raw(""));
        lines.extend(facts);
    }

    // When there's a flavor blurb and room to show it, split a small card off
    // the bottom of the info column for it; otherwise the stats use all of it.
    // Prefer PokeAPI's native blurb, then a cached machine translation, then the
    // English original as a last resort.
    let flavor = detail
        .flavors
        .get(lang_code)
        .map(String::as_str)
        .or_else(|| app.translation_for(&detail.name, lang_code))
        .or_else(|| detail.flavors.get("en").map(String::as_str));

    let flavor_rows = 4;
    match flavor {
        // `>=` rather than `>`: the card is the rows below the lines, exactly,
        // and asking for one more left a blurb off a column that had room.
        Some(flavor) if info.height as usize >= lines.len() + flavor_rows => {
            let split =
                Layout::vertical([Constraint::Min(0), Constraint::Length(flavor_rows as u16)])
                    .split(info);
            frame.render_widget(Paragraph::new(lines), split[0]);
            render_flavor_card(frame, split[1], flavor);
        }
        _ => frame.render_widget(Paragraph::new(lines), info),
    }
}

/// A `Label: value` row wrapped onto continuation lines rather than clipped,
/// the continuations indented under the value. Both rows that use it — the
/// abilities and the forms — are lists long enough to overrun a narrow panel,
/// and a name cut off halfway is worse than one on the next line.
fn label_rows(label: &str, text: &str, width: usize) -> Vec<Line<'static>> {
    let label = format!("{label}: ");
    let indent = " ".repeat(label.chars().count());
    let budget = width.saturating_sub(label.chars().count());
    wrap_plain(text, budget.max(8))
        .into_iter()
        .enumerate()
        .map(|(row, text)| {
            Line::from(vec![
                Span::styled(
                    if row == 0 {
                        label.clone()
                    } else {
                        indent.clone()
                    },
                    Style::default().fg(theme::subtext()),
                ),
                Span::styled(text, Style::default().fg(theme::text())),
            ])
        })
        .collect()
}

/// The field-guide facts as label/value pairs, in reading order, with the
/// rows that have nothing to say left out: a species past Generation IV has
/// no habitat, and a row saying "Habitat: none" would say less than no row.
fn field_facts(field: &FieldData, s: &Strings) -> Vec<(String, String)> {
    let mut facts = Vec::new();
    if !field.egg_groups.is_empty() {
        let groups: Vec<String> = field
            .egg_groups
            .iter()
            .map(|g| egg_group_label(g))
            .collect();
        facts.push((s.egg_groups_label.to_string(), groups.join(" · ")));
    }
    // The symbols are the label: "♂ 87.5% · ♀ 12.5%" needs no word in front
    // of it in any of the six languages, and the row is narrower for it.
    let gender = match field.gender_split() {
        Some((male, female)) => format!("{} · ♀ {}", percent(male), percent(female)),
        None => s.genderless.to_string(),
    };
    facts.push((String::new(), gender));
    let ease = match field.catch_ease() {
        CatchEase::Hard => s.catch_hard,
        CatchEase::Average => s.catch_average,
        CatchEase::Easy => s.catch_easy,
    };
    facts.push((
        s.catch_rate_label.to_string(),
        format!("{} ({ease})", field.capture_rate),
    ));
    if let Some(rate) = &field.growth_rate {
        facts.push((s.growth_label.to_string(), title_case(rate)));
    }
    if let Some(happiness) = field.base_happiness {
        facts.push((s.happiness_label.to_string(), happiness.to_string()));
    }
    if let Some(habitat) = &field.habitat {
        facts.push((s.habitat_label.to_string(), title_case(habitat)));
    }
    facts
}

/// A gender percentage without a pointless decimal: `50%`, `87.5%`.
fn percent(value: f32) -> String {
    if value.fract() == 0.0 {
        format!("{value:.0}%")
    } else {
        format!("{value:.1}%")
    }
}

/// The field-guide facts laid out for a column `width` cells wide.
fn field_rows(field: &FieldData, s: &Strings, width: usize) -> Vec<Line<'static>> {
    fact_rows(&field_facts(field, s), width)
}

/// Lays label/value pairs out left to right, as many to a row as `width`
/// takes, so a wide column reads them in two rows and a narrow one in five
/// rather than every row losing its end. A fact wider than the whole column
/// gets a row to itself and is clipped there, which is the one case nothing
/// can lay out. An empty label is a value that explains itself.
fn fact_rows(facts: &[(String, String)], width: usize) -> Vec<Line<'static>> {
    const GAP: &str = "    ";
    let mut rows = Vec::new();
    let mut spans: Vec<Span<'static>> = Vec::new();
    let mut used = 0;
    for (label, value) in facts {
        let label = match label.is_empty() {
            true => String::new(),
            false => format!("{label}: "),
        };
        let cell = label.chars().count() + value.chars().count();
        if !spans.is_empty() && used + GAP.len() + cell > width {
            rows.push(Line::from(std::mem::take(&mut spans)));
            used = 0;
        }
        if !spans.is_empty() {
            spans.push(Span::raw(GAP));
            used += GAP.len();
        }
        spans.push(Span::styled(label, Style::default().fg(theme::subtext())));
        spans.push(Span::styled(
            value.clone(),
            Style::default().fg(theme::text()),
        ));
        used += cell;
    }
    if !spans.is_empty() {
        rows.push(Line::from(spans));
    }
    rows
}

/// Renders the Pokedex flavor-text blurb as a quoted, word-wrapped little card.
fn render_flavor_card(frame: &mut Frame, area: Rect, flavor: &str) {
    let para = Paragraph::new(vec![Line::from(Span::styled(
        format!("{flavor}"),
        Style::default()
            .fg(theme::subtext())
            .add_modifier(Modifier::ITALIC),
    ))])
    .wrap(Wrap { trim: true });
    frame.render_widget(para, area);
}

// --- Sprite rendering ----------------------------------------------------

/// Maximum cell width we'll ever give a sprite, so it stays a tasteful accent
/// rather than swallowing the panel on very wide terminals.
const MAX_SPRITE_COLS: u16 = 40;

/// Chooses the sprite column width: square-ish, bounded by ~40% of the panel
/// width, the available height (two pixels per cell row), and [`MAX_SPRITE_COLS`].
fn sprite_col_width(inner: Rect) -> u16 {
    let by_width = inner.width * 2 / 5;
    let by_height = inner.height.saturating_mul(2);
    let w = by_width.min(by_height).min(MAX_SPRITE_COLS);
    (w & !1).max(2) // keep it even so rows = cols / 2 divides cleanly
}

/// Draws `sprite` into `area`, capped at [`MAX_SPRITE_COLS`] columns.
fn render_sprite(frame: &mut Frame, area: Rect, sprite: &Sprite) {
    render_sprite_capped(frame, area, sprite, MAX_SPRITE_COLS);
}

/// Draws `sprite` into `area` using upper-half-block characters: each cell packs
/// two vertical pixels (foreground = top, background = bottom), so one terminal
/// row shows two image rows.
///
/// The artwork is first cropped to its opaque bounding box (PokeAPI sprites have
/// a wide transparent margin), then scaled to the largest size that fits `area`
/// and `max_cols` *while preserving aspect ratio* — accounting for terminal
/// cells being roughly twice as tall as they are wide — and finally centred.
fn render_sprite_capped(frame: &mut Frame, area: Rect, sprite: &Sprite, max_cols: u16) {
    if area.width < 2 || area.height < 1 || sprite.width() == 0 || sprite.height() == 0 {
        return;
    }

    // Crop to the visible Pokemon so it fills the box instead of floating in
    // empty space.
    let (bx0, by0, bx1, by1) = sprite.content_bounds();
    let bw = (bx1 - bx0 + 1) as f32;
    let bh = (by1 - by0 + 1) as f32;

    // Fit the cropped box into the available pixel grid (width in cells, height
    // in half-cells) keeping its proportions.
    let max_w = area.width.min(max_cols) as f32;
    let max_h_px = (area.height as f32) * 2.0;
    let scale = (max_w / bw).min(max_h_px / bh);
    let cols = (((bw * scale) as u16).max(2)) & !1; // even, so columns map cleanly
    let rows = ((bh * scale) as u16).div_ceil(2).max(1);

    let bw = bw as u32;
    let bh = bh as u32;
    let cols_u = cols as u32;
    let sub_rows = 2 * rows as u32; // each cell row carries two vertical pixels

    // Source box covered by output column `cx` / sub-row `py`, in image pixels.
    let span_x = |cx: u32| {
        (
            bx0 + cx * bw / cols_u,
            bx0 + ((cx + 1) * bw / cols_u).saturating_sub(1),
        )
    };
    let span_y = |py: u32| {
        (
            by0 + py * bh / sub_rows,
            by0 + ((py + 1) * bh / sub_rows).saturating_sub(1),
        )
    };

    let mut lines: Vec<Line> = Vec::with_capacity(rows as usize);
    for cy in 0..rows {
        let (ty0, ty1) = span_y(2 * cy as u32);
        let (by_0, by_1) = span_y(2 * cy as u32 + 1);
        let mut spans: Vec<Span> = Vec::with_capacity(cols as usize);
        for cx in 0..cols {
            let (sx0, sx1) = span_x(cx as u32);
            let top = pixel_color(sprite.box_average(sx0, ty0, sx1, ty1));
            let bottom = pixel_color(sprite.box_average(sx0, by_0, sx1, by_1));
            spans.push(Span::styled("", Style::default().fg(top).bg(bottom)));
        }
        lines.push(Line::from(spans));
    }

    // Centre the block within the allotted area.
    let target = Rect {
        x: area.x + (area.width.saturating_sub(cols)) / 2,
        y: area.y + (area.height.saturating_sub(rows)) / 2,
        width: cols,
        height: rows,
    };
    frame.render_widget(Paragraph::new(lines), target);
}

/// Maps an averaged RGBA pixel to a terminal colour by alpha-compositing it over
/// the panel background. Blending (rather than a hard transparency threshold)
/// lets sprite edges fade cleanly into the UI instead of leaving a dark fringe.
fn pixel_color(rgba: [u8; 4]) -> Color {
    let a = rgba[3] as u16;
    if a == 0 {
        return theme::base();
    }
    let (br, bg, bb) = theme::base_rgb();
    let mix = |fg: u8, bg: u8| ((fg as u16 * a + bg as u16 * (255 - a)) / 255) as u8;
    // Composited first, then handed to the palette: a Game Boy has four
    // shades and quantising after the blend is what keeps a sprite's edges on
    // the background shade rather than one step above it.
    theme::ink((mix(rgba[0], br), mix(rgba[1], bg), mix(rgba[2], bb)))
}

fn render_evolution(frame: &mut Frame, app: &App, s: &Strings, area: Rect) {
    let focused = app.focus == Focus::Evolution;
    let block = if app.sprite_variant.is_shiny() {
        panel_block_owned(
            format!("{}{} ", s.evolution_title, s.shiny_label),
            focused,
        )
    } else {
        panel_block(s.evolution_title, focused)
    };
    let inner = block.inner(area);
    frame.render_widget(block, area);

    if app.detail_is_loading() {
        render_centered_loading(frame, inner, s.loading, app.spinner);
        return;
    }

    let Some(tree) = app.selected_evolution() else {
        if app.selected_detail().is_some() {
            render_centered_text(frame, inner, s.no_evolution, theme::overlay());
        } else {
            render_centered_text(frame, inner, s.no_selection, theme::overlay());
        }
        return;
    };

    // Highlight the chain node matching the displayed species (forms like
    // "raichu-alola" map back to their base "raichu" node).
    let current = app
        .selected_detail()
        .map(|d| d.species.as_str())
        .or(app.selected_name.as_deref());
    // Only when focused does the cursor highlight a specific member.
    let cursor_name = if focused {
        app.chain_names().get(app.evo_cursor).cloned()
    } else {
        None
    };
    let cursor = cursor_name.as_deref();

    // Reserve the bottom row for a context hint.
    let rows = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(inner);
    draw_chain(frame, app, s, tree, current, cursor, rows[0]);

    let fallback = if focused {
        s.evo_nav_hint
    } else {
        s.expand_hint
    };
    frame.render_widget(
        Paragraph::new(chain_hint(tree, cursor, s, fallback)).alignment(Alignment::Center),
        rows[1],
    );
}

/// The full-screen evolution view: the same chain renderer, handed the whole
/// terminal rather than one panel.
///
/// Wide chains — Eevee's eight branches, Tyrogue, Wurmple, the regional-form
/// lines — need more rows than the evolution panel can ever offer, so there they
/// degrade to the compact text tree, which is exactly the case the sprite cards
/// would help most with. This view is how they get to ask for the space.
fn render_evolution_card(frame: &mut Frame, app: &App, s: &Strings, full: Rect) {
    let Some(tree) = app.selected_evolution() else {
        return; // nothing loaded to expand
    };
    if full.width < MIN_CARD_W + 2 || full.height < MIN_CARD_H + 3 {
        return; // too cramped to be readable; leave the main view alone
    }

    frame.render_widget(Clear, full);

    // The sprite pixels are composited over `theme::base()`, so the card behind
    // them has to be that same colour or every sprite picks up a halo.
    let title = if app.sprite_variant.is_shiny() {
        format!("{}{} ", s.evolution_title, s.shiny_label)
    } else {
        s.evolution_title.to_string()
    };
    let block = Block::bordered()
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(theme::mauve()))
        .title(Span::styled(
            title,
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::base()));
    let inner = block.inner(full);
    frame.render_widget(block, full);

    let current = app
        .selected_detail()
        .map(|d| d.species.as_str())
        .or(app.selected_name.as_deref());
    // The card is modal, so its cursor is always live — unlike the panel's,
    // which only lights up while the panel holds focus.
    let cursor_name = app.chain_names().get(app.evo_cursor).cloned();
    let cursor = cursor_name.as_deref();

    let rows = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(inner);
    draw_chain(frame, app, s, tree, current, cursor, rows[0]);
    frame.render_widget(
        Paragraph::new(chain_hint(tree, cursor, s, s.evo_card_hint)).alignment(Alignment::Center),
        rows[1],
    );
}

/// Draws a chain onto `canvas`: the sprite graph when every card has room,
/// otherwise the compact text tree so cramped terminals still show the
/// relationships.
fn draw_chain(
    frame: &mut Frame,
    app: &App,
    s: &Strings,
    tree: &EvolutionTree,
    current: Option<&str>,
    cursor: Option<&str>,
    canvas: Rect,
) {
    let depth = tree.depth() as u16;
    let leaves = tree.leaf_count() as u16;
    match card_grid(canvas, depth, leaves) {
        Some((col_w, lane_h)) => {
            // The grid rarely uses the canvas to the last row or column — lanes
            // divide it with a remainder, and wide canvases hit the card-width
            // cap — so centre what it does use rather than letting the leftover
            // pile up below and to the right of the chain.
            let canvas = centered_fixed(col_w * depth, lane_h * leaves, canvas);
            let mut lane = 0u16;
            place_node(
                frame, app, s, tree, current, cursor, canvas, col_w, lane_h, 0, &mut lane,
            );
        }
        None => {
            let lines = evolution_lines(tree, cursor.or(current), &s.evo, canvas.width);
            frame.render_widget(Paragraph::new(lines), canvas);
        }
    }
}

/// The sprite-card grid for a chain of `depth` stages and `leaves` branches on
/// `canvas`, or `None` when a card would come out smaller than
/// [`MIN_CARD_W`] × [`MIN_CARD_H`] and the text tree is the better rendering.
///
/// Every lane needs its own [`MIN_CARD_H`] rows, so the height a wide chain
/// asks for grows with its branches: Eevee's eight leaves want 32 rows, which
/// no panel in the right-hand column will ever have and a full screen usually
/// does. That difference is the whole point of the full-screen view.
fn card_grid(canvas: Rect, depth: u16, leaves: u16) -> Option<(u16, u16)> {
    let col_w = canvas.width.checked_div(depth)?.min(MAX_CARD_W + EVO_GAP);
    let lane_h = canvas.height.checked_div(leaves)?;
    (col_w >= MIN_CARD_W && lane_h >= MIN_CARD_H).then_some((col_w, lane_h))
}

/// The bottom row under a chain. While the cursor sits on a member it doubles
/// as a requirement readout, spelling out in full what it takes to get there —
/// the cards only have room for the headline condition; otherwise it carries
/// `fallback`, whatever the view wants to say about its own keys.
fn chain_hint(
    tree: &EvolutionTree,
    cursor: Option<&str>,
    s: &Strings,
    fallback: &'static str,
) -> Line<'static> {
    let requirement = cursor
        .and_then(|name| tree.find(name))
        .and_then(|node| node.condition.as_ref())
        .map(|condition| s.evo.summary(condition))
        .filter(|text| !text.is_empty());

    match requirement {
        Some(text) => Line::from(vec![
            Span::styled("", Style::default().fg(theme::peach())),
            Span::styled(text, Style::default().fg(theme::lavender())),
        ]),
        None => Line::from(Span::styled(
            fallback,
            Style::default().fg(theme::overlay()),
        )),
    }
}

// --- Small rendering helpers ---------------------------------------------

fn panel_block(title: &'static str, focused: bool) -> Block<'static> {
    panel_block_owned(title.to_string(), focused)
}

fn panel_block_owned(title: String, focused: bool) -> Block<'static> {
    // Focused panels glow warm yellow with a heavier double rule; resting panels
    // recede to a thin indigo frame — a retro DOS-panel feel.
    let (border, text, border_type) = if focused {
        (theme::mauve(), theme::mauve(), BorderType::Double)
    } else {
        (theme::overlay(), theme::subtext(), BorderType::Plain)
    };
    Block::bordered()
        .border_type(border_type)
        .border_style(Style::default().fg(border))
        .title(Span::styled(
            title,
            Style::default().fg(text).add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::base()))
}

fn stat_line(label: &str, base: u16, bar_width: usize) -> Line<'static> {
    let filled = if bar_width == 0 {
        0
    } else {
        ((base as usize * bar_width) / 255).min(bar_width)
    };
    Line::from(vec![
        Span::styled(
            format!("{label:<STAT_LABEL_WIDTH$}"),
            Style::default().fg(theme::subtext()),
        ),
        Span::styled(format!("{base:>3} "), Style::default().fg(theme::text())),
        Span::styled(
            "".repeat(filled),
            Style::default().fg(theme::stat_color(base)),
        ),
        Span::styled(
            "".repeat(bar_width - filled),
            Style::default().fg(theme::surface()),
        ),
    ])
}

fn render_error(frame: &mut Frame, inner: Rect, s: &Strings, err: &str) {
    let para = Paragraph::new(vec![
        Line::from(Span::styled(
            format!("{}", s.error_prefix),
            Style::default()
                .fg(theme::red())
                .add_modifier(Modifier::BOLD),
        )),
        Line::raw(""),
        Line::from(Span::styled(
            err.to_string(),
            Style::default().fg(theme::subtext()),
        )),
    ])
    .wrap(ratatui::widgets::Wrap { trim: true });
    frame.render_widget(para, inner);
}

fn render_centered_text(frame: &mut Frame, inner: Rect, text: &str, color: ratatui::style::Color) {
    if inner.height == 0 {
        return;
    }
    let row = Rect {
        x: inner.x,
        y: inner.y + inner.height / 2,
        width: inner.width,
        height: 1,
    };
    let para = Paragraph::new(Line::from(Span::styled(
        text.to_string(),
        Style::default().fg(color),
    )))
    .alignment(Alignment::Center);
    frame.render_widget(para, row);
}

fn render_centered_loading(frame: &mut Frame, inner: Rect, label: &str, spinner: usize) {
    if inner.height == 0 {
        return;
    }
    let frame_char = SPINNER[spinner % SPINNER.len()];
    let row = Rect {
        x: inner.x,
        y: inner.y + inner.height / 2,
        width: inner.width,
        height: 1,
    };
    let para = Paragraph::new(Line::from(vec![
        Span::styled(
            format!("{frame_char} "),
            Style::default().fg(theme::mauve()),
        ),
        Span::styled(format!("{label}"), Style::default().fg(theme::subtext())),
    ]))
    .alignment(Alignment::Center);
    frame.render_widget(para, row);
}

// --- Evolution tree rendering --------------------------------------------

/// Renders an [`EvolutionTree`] as a list of styled lines. Linear segments are
/// drawn horizontally (`A ──▶ B (Lv. 16) ──▶ C`); wherever a species branches,
/// the children are laid out vertically with `├──`/`└──` connectors. Each
/// member carries its evolution requirement in parentheses.
fn evolution_lines(
    tree: &EvolutionTree,
    highlight: Option<&str>,
    evo: &EvoStrings,
    width: u16,
) -> Vec<Line<'static>> {
    node_block(tree, highlight, evo, requirement_budget(width))
        .into_iter()
        .map(Line::from)
        .collect()
}

/// How many columns a requirement may take in the compact tree. Names and
/// connectors eat into the panel, so the budget grows with the panel but never
/// so far that a long location name pushes the tree off the right edge.
fn requirement_budget(width: u16) -> usize {
    (width as usize).saturating_sub(28).clamp(12, 40)
}

/// Returns the block of span-rows for `node` and its descendants, without any
/// outer indentation (the caller prepends connectors).
fn node_block(
    node: &EvolutionTree,
    highlight: Option<&str>,
    evo: &EvoStrings,
    budget: usize,
) -> Vec<Vec<Span<'static>>> {
    // Walk the linear run: follow single-child links onto one horizontal line.
    let mut run: Vec<&EvolutionTree> = vec![node];
    let mut cur = node;
    while cur.children.len() == 1 {
        cur = &cur.children[0];
        run.push(cur);
    }

    // Lay the run out left to right, tracking how wide it gets so any branch
    // connectors below can be indented under the last name.
    let mut first: Vec<Span<'static>> = Vec::new();
    let mut width = 0usize;
    let mut indent_width = 0usize;
    for (i, n) in run.iter().enumerate() {
        if i > 0 {
            first.push(Span::styled(" ──▶ ", Style::default().fg(theme::overlay())));
            width += 5; // " ──▶ " is 5 columns
        }
        if i + 1 == run.len() {
            indent_width = width; // everything preceding the final name
        }
        first.push(name_span(&n.name, highlight));
        width += title_case(&n.name).chars().count();
        if let Some(label) = condition_label(n, evo, budget) {
            width += label.chars().count();
            first.push(Span::styled(label, Style::default().fg(theme::overlay())));
        }
    }
    let mut lines = vec![first];

    // `cur` ends the run; if it branches, lay children out vertically beneath
    // the final name of the run.
    if cur.children.len() > 1 {
        let indent = " ".repeat(indent_width);

        let count = cur.children.len();
        for (i, child) in cur.children.iter().enumerate() {
            let is_last = i == count - 1;
            for (j, child_row) in node_block(child, highlight, evo, budget)
                .into_iter()
                .enumerate()
            {
                let connector = if j == 0 {
                    if is_last {
                        "└── "
                    } else {
                        "├── "
                    }
                } else if is_last {
                    "    "
                } else {
                    ""
                };
                let mut row = vec![Span::styled(
                    format!("{indent}{connector}"),
                    Style::default().fg(theme::overlay()),
                )];
                row.extend(child_row);
                lines.push(row);
            }
        }
    }

    lines
}

/// The parenthesised requirement suffix for a chain member in the compact text
/// tree, e.g. `" (Lv. 16)"`. `None` for a chain root, which nothing evolves into.
fn condition_label(node: &EvolutionTree, evo: &EvoStrings, budget: usize) -> Option<String> {
    let text = node.condition.as_ref().and_then(|c| evo.short(c))?;
    Some(format!(" ({})", truncate(&text, budget)))
}

/// Shortens `text` to `max` columns, marking the cut with an ellipsis.
fn truncate(text: &str, max: usize) -> String {
    if text.chars().count() <= max {
        return text.to_string();
    }
    if max <= 1 {
        return "".to_string();
    }
    text.chars()
        .take(max - 1)
        .chain(std::iter::once(''))
        .collect()
}

fn name_span(raw_name: &str, highlight: Option<&str>) -> Span<'static> {
    let style = if highlight == Some(raw_name) {
        Style::default()
            .fg(theme::yellow())
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(theme::green())
    };
    Span::styled(title_case(raw_name), style)
}

// --- Evolution sprite graph ----------------------------------------------

/// Minimum cells a single sprite card needs to be worth drawing as art rather
/// than falling back to the compact text tree.
const MIN_CARD_W: u16 = 10;
const MIN_CARD_H: u16 = 4;
/// Columns reserved between generations for the connector arrows.
const EVO_GAP: u16 = 5;
/// Widest a card is allowed to get. Past this it is mostly whitespace: the
/// sprite is bounded by its lane height, and a name with its short requirement
/// rarely runs further. Capping it is what stops a full screen from spreading a
/// two-stage chain into two distant clusters with a connector stretched
/// between them.
const MAX_CARD_W: u16 = 30;

/// Recursively lays out `node` and its descendants. Each generation occupies a
/// fixed-width column; leaves are stacked into horizontal lanes. Returns the
/// vertical centre (absolute row) of this node's card so the caller can wire a
/// connector to it.
///
/// `current` is the species shown in the detail panel; `cursor` is the member
/// the navigation cursor sits on (only set while the panel is focused).
#[allow(clippy::too_many_arguments)]
fn place_node(
    frame: &mut Frame,
    app: &App,
    s: &Strings,
    node: &EvolutionTree,
    current: Option<&str>,
    cursor: Option<&str>,
    canvas: Rect,
    col_w: u16,
    lane_h: u16,
    depth_idx: u16,
    lane: &mut u16,
) -> u16 {
    let x = canvas.x + depth_idx * col_w;
    let card_w = col_w.saturating_sub(EVO_GAP);

    if node.children.is_empty() {
        let top = canvas.y + *lane * lane_h;
        *lane += 1;
        draw_card(frame, app, s, node, current, cursor, x, top, card_w, lane_h);
        return top + lane_h / 2;
    }

    // Place children first so we know where to anchor the connectors.
    let centers: Vec<u16> = node
        .children
        .iter()
        .map(|child| {
            place_node(
                frame,
                app,
                s,
                child,
                current,
                cursor,
                canvas,
                col_w,
                lane_h,
                depth_idx + 1,
                lane,
            )
        })
        .collect();

    let first = *centers.first().unwrap();
    let last = *centers.last().unwrap();
    let cy = (first + last) / 2;
    let top = cy.saturating_sub(lane_h / 2);
    draw_card(frame, app, s, node, current, cursor, x, top, card_w, lane_h);

    let child_x = canvas.x + (depth_idx + 1) * col_w;
    draw_connectors(frame, x + card_w, child_x, cy, &centers);
    cy
}

/// Draws one species card: its sprite (or a placeholder while loading) with the
/// name centred beneath it. The navigation cursor gets a highlighted name bar;
/// the currently displayed species is tinted but not boxed.
#[allow(clippy::too_many_arguments)]
fn draw_card(
    frame: &mut Frame,
    app: &App,
    s: &Strings,
    node: &EvolutionTree,
    current: Option<&str>,
    cursor: Option<&str>,
    x: u16,
    top: u16,
    w: u16,
    h: u16,
) {
    if w == 0 || h == 0 {
        return;
    }

    // How this stage is reached. A card one row taller than the minimum gets a
    // dedicated row for it; a shorter one tucks it in beside the name instead,
    // so the requirement survives even on a cramped three-way branch.
    let condition = node.condition.as_ref().and_then(|c| s.evo.short(c));
    let stacked = condition.is_some() && h > MIN_CARD_H;
    let text_rows = if stacked { 2 } else { 1 };

    let sprite_area = Rect {
        x,
        y: top,
        width: w,
        height: h.saturating_sub(text_rows),
    };
    match app.sprite_for(&node.name) {
        Some(sprite) => render_sprite_capped(frame, sprite_area, sprite, w),
        None => {
            let placeholder = if app.sprite_is_loading(&node.name) {
                s.sprite_loading
            } else {
                ""
            };
            render_centered_text(frame, sprite_area, placeholder, theme::overlay());
        }
    }

    let is_cursor = cursor == Some(node.name.as_str());
    let is_current = current == Some(node.name.as_str());
    let style = if is_cursor {
        color::highlight(theme::yellow()).add_modifier(Modifier::BOLD)
    } else if is_current {
        Style::default()
            .fg(theme::yellow())
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(theme::green())
    };
    let label = title_case(&node.name);
    let mut name_spans = vec![Span::styled(label.clone(), style)];

    // Inline requirement: only when there is no row of its own for it, and only
    // if enough columns are left over to say something meaningful.
    if let (Some(text), false) = (&condition, stacked) {
        let free = (w as usize).saturating_sub(label.chars().count());
        if free >= 6 {
            name_spans.push(Span::styled(
                truncate(&format!(" · {text}"), free),
                Style::default().fg(theme::peach()),
            ));
        }
    }

    let name_y = top + h.saturating_sub(text_rows);
    let name = Paragraph::new(Line::from(name_spans)).alignment(Alignment::Center);
    frame.render_widget(
        name,
        Rect {
            x,
            y: name_y,
            width: w,
            height: 1,
        },
    );

    if let (Some(text), true) = (&condition, stacked) {
        let requirement = Paragraph::new(Line::from(Span::styled(
            truncate(text, w as usize),
            Style::default().fg(theme::peach()),
        )))
        .alignment(Alignment::Center);
        frame.render_widget(
            requirement,
            Rect {
                x,
                y: name_y + 1,
                width: w,
                height: 1,
            },
        );
    }
}

/// Wires a parent card's right edge to each child card's left edge with
/// box-drawing connectors and an arrowhead, branching where needed.
fn draw_connectors(frame: &mut Frame, x_from: u16, x_to: u16, parent_cy: u16, centers: &[u16]) {
    let color = theme::overlay();
    if x_to <= x_from {
        return;
    }

    // Single child: a straight arrow reads cleaner than a trunk-and-branch.
    if centers.len() == 1 {
        let cy = centers[0];
        for x in x_from..x_to.saturating_sub(1) {
            put_cell(frame, x, cy, "", color);
        }
        put_cell(frame, x_to.saturating_sub(1), cy, "", theme::mauve());
        return;
    }

    let trunk_x = x_from + (x_to - x_from) / 2;
    let min_c = *centers.iter().min().unwrap();
    let max_c = *centers.iter().max().unwrap();

    // Stub from the parent into the vertical trunk.
    for x in x_from..trunk_x {
        put_cell(frame, x, parent_cy, "", color);
    }
    // The vertical trunk spanning all the children.
    for y in min_c..=max_c {
        put_cell(frame, trunk_x, y, "", color);
    }
    // Junction where the parent's stub meets the trunk.
    let junction = if centers.contains(&parent_cy) {
        ""
    } else {
        ""
    };
    put_cell(frame, trunk_x, parent_cy, junction, color);

    // Branch off to each child and tip it with an arrowhead.
    for &cy in centers {
        let corner = if cy == min_c {
            ""
        } else if cy == max_c {
            ""
        } else {
            ""
        };
        if cy != parent_cy {
            put_cell(frame, trunk_x, cy, corner, color);
        }
        for x in (trunk_x + 1)..x_to.saturating_sub(1) {
            put_cell(frame, x, cy, "", color);
        }
        put_cell(frame, x_to.saturating_sub(1), cy, "", theme::mauve());
    }
}

/// Writes a single glyph straight into the frame buffer (used for the connector
/// art, which doesn't map cleanly onto a widget).
fn put_cell(frame: &mut Frame, x: u16, y: u16, symbol: &str, color: Color) {
    let area = frame.area();
    if x < area.x || y < area.y || x >= area.right() || y >= area.bottom() {
        return;
    }
    if let Some(cell) = frame.buffer_mut().cell_mut(Position::new(x, y)) {
        cell.set_symbol(symbol).set_fg(color);
    }
}

// --- Type matchup card ----------------------------------------------------

/// Preferred width of the matchup card, clamped to the terminal.
const MATCHUP_CARD_W: u16 = 48;
/// The team card carries names *and* chips, so it needs a little more room.
const TEAM_CARD_W: u16 = 56;
/// The ability card holds wrapped prose, so it is wider still.
const ABILITY_CARD_W: u16 = 60;
/// The moves card is the widest of them: seven columns, and a description
/// underneath that wants the same room the ability card's prose does.
const MOVES_CARD_W: u16 = 66;
/// Columns each of the moves card's numeric fields is padded to.
const MOVE_NUM_W: usize = 5;
/// The comparison card holds two of everything side by side, so it is the
/// widest of the lot.
const COMPARE_CARD_W: u16 = 72;
/// Columns each side's number gets on a comparison row. Four rather than the
/// three a base stat needs, so the totals line — which can run past a thousand
/// — reads down the same columns as the rows above it.
const COMPARE_VAL_W: usize = 4;
/// Columns the margin gets at the end of a comparison row: an arrow pointing at
/// the winner, a space, and up to three digits.
const COMPARE_MARGIN_W: usize = 6;
/// Columns reserved for a multiplier label (`" ×4  "`), which also sets the
/// indent used when a group of chips wraps onto another row.
const MATCHUP_LABEL_W: usize = 5;

/// Draws the modal card summarising the selected Pokemon's type matchups: what
/// hits it hard, what it shrugs off, and what its own attacks are strong
/// against. Everything here is computed offline from [`typechart`].
fn render_matchups(frame: &mut Frame, app: &App, s: &Strings, full: Rect) {
    let Some(detail) = app.selected_detail() else {
        return; // nothing loaded to analyse
    };

    let width = MATCHUP_CARD_W.min(full.width);
    let text_w = width.saturating_sub(2) as usize; // usable columns inside the border
    if text_w < 16 || full.height < 8 {
        return; // too cramped to be readable; leave the main view alone
    }

    let mut lines: Vec<Line> = Vec::new();

    // Headline: who this card is about, and the types the analysis is based on.
    let mut head = vec![Span::styled(
        format!(" {}  ", title_case(&detail.name)),
        Style::default()
            .fg(theme::mauve())
            .add_modifier(Modifier::BOLD),
    )];
    head.extend(type_chips(&detail.types));
    lines.push(Line::from(head));
    lines.push(Line::raw(""));

    // Defensive view: incoming damage, worst multiplier first. Neutral matchups
    // are omitted by `defensive_groups`, so every row here is worth reading.
    //
    // Abilities are read first because a certain one rewrites the rows: a
    // species that cannot *not* have Levitate is simply not hit by Ground, and
    // the chart on its own would say otherwise. One it merely might have is
    // left out of the numbers and annotated below instead.
    let immunities = team::ability_immunities(detail);
    let certain: Vec<&str> = immunities
        .iter()
        .filter(|immunity| immunity.certain)
        .map(|immunity| immunity.immune_to)
        .collect();

    lines.push(section_heading(s.matchups_defense));
    for group in typechart::defensive_groups(&detail.types, &certain) {
        lines.extend(chip_rows(group.label, &group.types, text_w));
    }

    // Directly under the numbers, because it is the numbers this explains:
    // why a row moved, or what would move if the species turned out to carry
    // the other ability.
    if !immunities.is_empty() {
        lines.push(Line::raw(""));
        lines.push(section_heading(s.immune_by_ability));
        for immunity in &immunities {
            lines.push(ability_immunity_row(app, s, immunity, "  "));
        }
    }

    // Offensive view: what its own same-type moves are strong against.
    lines.push(Line::raw(""));
    lines.push(section_heading(s.matchups_offense));
    let coverage = typechart::offensive_coverage(&detail.types);
    if coverage.is_empty() {
        lines.push(Line::from(Span::styled(
            format!("  {}", s.matchups_none),
            Style::default().fg(theme::overlay()),
        )));
    } else {
        lines.extend(chip_rows("", &coverage, text_w));
    }

    // Two border rows plus the hint row at the foot.
    let height = (lines.len() as u16 + 3).min(full.height);
    let area = centered_fixed(width, height, full);
    frame.render_widget(Clear, area);

    let block = Block::bordered()
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(theme::mauve()))
        .title(Span::styled(
            s.matchups_title,
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::surface()));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let rows = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(inner);
    frame.render_widget(Paragraph::new(lines), rows[0]);

    let hint = Paragraph::new(Line::from(Span::styled(
        s.close_hint,
        Style::default().fg(theme::overlay()),
    )))
    .alignment(Alignment::Center);
    frame.render_widget(hint, rows[1]);
}

/// Renders a list of types as coloured chips, separated by a space.
fn type_chips(types: &[String]) -> Vec<Span<'static>> {
    let mut spans = Vec::with_capacity(types.len() * 2);
    for ty in types {
        spans.push(Span::styled(
            format!(" {} ", title_case(ty)),
            Style::default().fg(theme::base()).bg(theme::type_color(ty)),
        ));
        spans.push(Span::raw(" "));
    }
    spans
}

fn section_heading(text: &str) -> Line<'static> {
    Line::from(Span::styled(
        format!(" {text}"),
        Style::default()
            .fg(theme::peach())
            .add_modifier(Modifier::BOLD),
    ))
}

/// Lays `types` out as chips in a labelled row, wrapping onto further rows when
/// they overflow `max_width`. Continuation rows are indented under the chips so
/// the label column stays clean.
fn chip_rows(label: &str, types: &[&str], max_width: usize) -> Vec<Line<'static>> {
    let indent = " ".repeat(MATCHUP_LABEL_W);
    let mut rows: Vec<Line> = Vec::new();
    let mut spans: Vec<Span> = vec![Span::styled(
        format!(" {label:<pad$} ", pad = MATCHUP_LABEL_W - 2),
        Style::default()
            .fg(theme::subtext())
            .add_modifier(Modifier::BOLD),
    )];
    let mut used = MATCHUP_LABEL_W;

    for ty in types {
        let chip = format!(" {} ", title_case(ty));
        let chip_w = chip.chars().count() + 1; // chip plus its trailing space
        if used + chip_w > max_width && used > MATCHUP_LABEL_W {
            rows.push(Line::from(std::mem::take(&mut spans)));
            spans.push(Span::raw(indent.clone()));
            used = MATCHUP_LABEL_W;
        }
        spans.push(Span::styled(
            chip,
            Style::default().fg(theme::base()).bg(theme::type_color(ty)),
        ));
        spans.push(Span::raw(" "));
        used += chip_w;
    }

    rows.push(Line::from(spans));
    rows
}

// --- Language picker ------------------------------------------------------

/// Draws the little modal card for switching interface language.
/// The party card: who is on the team, and the three things their combined
/// typings say about it.
/// The ability card: each of the species' abilities with what it actually does.
/// The overlay is two columns wide so the whole key map fits without scrolling
/// on a standard 24-row terminal.
const HELP_CARD_W: u16 = 86;

/// The help overlay: every binding in one place, grouped by where it applies.
///
/// The key names are language-neutral and live here; only the action labels
/// come from the translation table.
fn render_help(frame: &mut Frame, s: &Strings, full: Rect) {
    let h = &s.help_card;

    let left: Vec<(&str, &str)> = vec![
        ("", h.ctx_list),
        ("↑ ↓ · j k", h.act_move),
        ("PgUp PgDn", h.act_jump10),
        ("Enter", h.act_load),
        ("/ · Tab", h.act_search),
        ("E", h.act_evolutions),
        ("F", h.act_chain_expand),
        ("T", h.act_types),
        ("C", h.act_compare),
        ("A", h.act_abilities),
        ("M", h.act_moves),
        ("V", h.act_forms),
        ("X", h.act_shiny),
        ("R", h.act_random),
        ("Space", h.act_party_toggle),
        ("P", h.act_party_card),
        ("S", h.act_sort),
        ("L", h.act_language),
        ("?", h.act_help),
        ("Q", h.act_quit),
    ];
    let right: Vec<(&str, &str)> = vec![
        ("", h.ctx_search),
        ("Enter", h.act_load_back),
        ("Esc · Tab", h.act_back),
        ("type:water", h.act_by_type),
        ("ability:levitate", h.act_by_ability),
        ("egg:dragon", h.act_by_egg),
        ("gen:1", h.act_by_generation),
        ("", ""),
        ("", h.ctx_evolution),
        ("← → ↑ ↓ · h j k l", h.act_chain_move),
        ("Enter", h.act_chain_jump),
        ("F", h.act_chain_expand),
        ("X", h.act_shiny),
        ("Esc · Tab", h.act_back),
        ("", ""),
        ("", h.ctx_party),
        ("↑ ↓ · j k", h.act_move),
        ("C", h.act_compare),
        ("", ""),
        ("", h.ctx_forms),
        ("↑ ↓ · j k", h.act_move),
        ("Enter", h.act_form_jump),
        ("", ""),
        ("", h.ctx_cards),
        ("Esc", h.act_close),
        ("Ctrl-C", h.act_quit),
    ];

    let rows = left.len().max(right.len()) as u16;
    let width = HELP_CARD_W.min(full.width);
    let height = (rows + 4).min(full.height);
    if width < 40 || height < 8 {
        return; // too cramped to be readable; leave the main view alone
    }

    let area = centered_fixed(width, height, full);
    frame.render_widget(Clear, area);

    let block = Block::bordered()
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(theme::mauve()))
        .title(Span::styled(
            h.title,
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::surface()));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let body = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(inner);
    let cols =
        Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)]).split(body[0]);
    frame.render_widget(Paragraph::new(help_lines(&left)), cols[0]);
    frame.render_widget(Paragraph::new(help_lines(&right)), cols[1]);

    let hint = Paragraph::new(Line::from(Span::styled(
        h.close_hint,
        Style::default().fg(theme::overlay()),
    )))
    .alignment(Alignment::Center);
    frame.render_widget(hint, body[1]);
}

/// Turns help rows into lines. A row with no keys is a section heading, and an
/// entirely empty one is a spacer.
///
/// The key column is sized from the column's own widest entry, so the side
/// carrying `← → ↑ ↓ · h j k l` does not force that much padding on the other
/// and squeeze its labels into truncation.
fn help_lines(rows: &[(&str, &str)]) -> Vec<Line<'static>> {
    let key_w = rows
        .iter()
        .map(|(keys, _)| keys.chars().count())
        .max()
        .unwrap_or(0)
        + 2;

    rows.iter()
        .map(|(keys, action)| {
            if keys.is_empty() {
                return match action.is_empty() {
                    true => Line::raw(""),
                    false => section_heading(action),
                };
            }
            Line::from(vec![
                Span::styled(
                    format!("  {keys:<key_w$}"),
                    Style::default()
                        .fg(theme::teal())
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled((*action).to_string(), Style::default().fg(theme::subtext())),
            ])
        })
        .collect()
}

/// Draws the modal card listing the selected Pokemon's learnset: what it learns,
/// how, and — for whichever row the cursor is on — what the move actually does.
///
/// The rows come free with the species record. The per-move numbers do not, so
/// a row shows what it has and fills in the rest once
/// [`App::ensure_move_info`] has fetched it; scrolling past a row without
/// stopping costs one request that the next visit reads from the cache.
fn render_moves(frame: &mut Frame, app: &App, s: &Strings, full: Rect) {
    let Some(detail) = app.selected_detail() else {
        return;
    };
    let learnset = detail.moves.as_slice();

    let width = MOVES_CARD_W.min(full.width);
    // Prose is inset from the border on both sides; the table uses the full
    // inner width, since its own leading space is part of the format.
    let table_w = width.saturating_sub(2) as usize;
    let text_w = width.saturating_sub(4) as usize;
    if text_w < 40 || full.height < 12 {
        return; // too cramped for seven columns; leave the main view alone
    }

    let block = Block::bordered()
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(theme::mauve()))
        .title(Span::styled(
            s.moves_title,
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::surface()));

    // The card claims most of the height available, leaving a margin so the
    // list behind it stays visible — this is a card, not a second screen.
    let height = full
        .height
        .saturating_sub(4)
        .min(learnset.len() as u16 + 10);
    let area = centered_fixed(width, height, full);
    frame.render_widget(Clear, area);
    let inner = block.inner(area);
    frame.render_widget(block, area);

    if learnset.is_empty() {
        render_centered_text(frame, inner, s.moves_empty, theme::overlay());
        return;
    }

    // Header, the scrolling list, the highlighted move's description, and the
    // hint — in that order, with the list taking whatever is left over.
    let rows = Layout::vertical([
        Constraint::Length(2), // species + games, then column headings
        Constraint::Min(1),    // the learnset
        Constraint::Length(3), // what the highlighted move does
        Constraint::Length(1), // close hint
    ])
    .split(inner);

    let mut heading = vec![Span::styled(
        format!(" {}", title_case(&detail.name)),
        Style::default()
            .fg(theme::mauve())
            .add_modifier(Modifier::BOLD),
    )];
    if let Some(games) = &detail.learnset_games {
        heading.push(Span::styled(
            format!("  ·  {}", title_case(games)),
            Style::default().fg(theme::overlay()),
        ));
    }
    frame.render_widget(
        Paragraph::new(vec![Line::from(heading), {
            let (left, middle, right) = move_columns(
                s.col_learn,
                s.col_move,
                s.col_type,
                s.col_category,
                s.col_power,
                s.col_accuracy,
                s.col_pp,
                table_w,
            );
            Line::from(Span::styled(
                format!("{left}{middle}{right}"),
                Style::default().fg(theme::overlay()),
            ))
        }]),
        rows[0],
    );

    // Centre the cursor in the window where there is room on both sides, and
    // pin it to an end where there is not, so the last rows stay reachable.
    let window = rows[1].height as usize;
    let first = app
        .move_cursor
        .saturating_sub(window / 2)
        .min(learnset.len().saturating_sub(window));
    let lines: Vec<Line> = learnset
        .iter()
        .enumerate()
        .skip(first)
        .take(window)
        .map(|(idx, learned)| move_row(app, s, learned, idx == app.move_cursor, table_w))
        .collect();
    frame.render_widget(Paragraph::new(lines), rows[1]);

    frame.render_widget(Paragraph::new(move_description(app, s, text_w)), rows[2]);

    let hint = Paragraph::new(Line::from(Span::styled(
        s.moves_close_hint,
        Style::default().fg(theme::overlay()),
    )))
    .alignment(Alignment::Center);
    frame.render_widget(hint, rows[3]);
}

/// Lays the seven columns out on one row, split either side of the type so the
/// caller can colour that column on its own. Spelled once so the headings and
/// the rows under them cannot drift apart.
#[allow(clippy::too_many_arguments)]
fn move_columns(
    learn: &str,
    name: &str,
    type_name: &str,
    category: &str,
    power: &str,
    accuracy: &str,
    pp: &str,
    width: usize,
) -> (String, String, String) {
    // Everything but the name is fixed-width — the leading space, the level
    // column and its separator, the type column and its separators, and the
    // four numeric columns — so the name absorbs whatever is left over.
    let name_w = width.saturating_sub(12 + 4 * MOVE_NUM_W + 8).max(8);
    (
        format!(" {learn:>7} {name:<name_w$} "),
        format!("{type_name:<9}"),
        format!(
            " {category:<MOVE_NUM_W$}{power:>MOVE_NUM_W$}{accuracy:>MOVE_NUM_W$}{pp:>MOVE_NUM_W$}"
        ),
    )
}

/// One row of the learnset. The type is the only part that carries colour: it
/// is what a reader scans the list for.
fn move_row<'a>(
    app: &'a App,
    s: &Strings,
    learned: &'a LearnedMove,
    highlighted: bool,
    width: usize,
) -> Line<'a> {
    let code = app.language.flavor_code();
    let info = app.moves.get(&learned.name);

    // Levels go in bare under the level heading, the way the games print them.
    // Level zero is how a move known from the start is recorded, and no game
    // ever calls that level zero.
    let learn = match learned.method {
        LearnMethod::LevelUp if learned.level == 0 => "".to_string(),
        LearnMethod::LevelUp => learned.level.to_string(),
        LearnMethod::Machine => s.learn_machine.to_string(),
        LearnMethod::Egg => s.learn_egg.to_string(),
        LearnMethod::Tutor => s.learn_tutor.to_string(),
    };
    let name = match info {
        Some(info) => info.name_for(code),
        None => title_case(&learned.name),
    };
    // A row whose record has not landed shows the two fields the species
    // record already answered for, and blanks rather than zeros for the rest.
    let (type_name, category, power, accuracy, pp) = match info {
        Some(info) => (
            info.type_name.to_uppercase(),
            damage_class_label(s, &info.damage_class).to_string(),
            info.power
                .map_or_else(|| "".to_string(), |p| p.to_string()),
            info.accuracy
                .map_or_else(|| "".to_string(), |a| a.to_string()),
            info.pp.map_or_else(|| "".to_string(), |p| p.to_string()),
        ),
        None => (
            String::new(),
            String::new(),
            String::new(),
            String::new(),
            String::new(),
        ),
    };

    let (left, middle, right) = move_columns(
        &learn, &name, &type_name, &category, &power, &accuracy, &pp, width,
    );

    // The highlighted row is painted in one piece: the selection bar is what
    // says where the cursor is, and a type colour showing through it would only
    // muddy that.
    if highlighted {
        let style = color::highlight(theme::mauve()).add_modifier(Modifier::BOLD);
        return Line::from(Span::styled(format!("{left}{middle}{right}"), style));
    }

    let plain = Style::default().fg(theme::text());
    Line::from(vec![
        Span::styled(left, plain),
        Span::styled(
            middle,
            Style::default().fg(theme::type_color(&learned_type(app, learned))),
        ),
        Span::styled(right, Style::default().fg(theme::subtext())),
    ])
}

/// The type slug of a move whose record has landed, or the empty string —
/// which no type answers to, so the column simply draws unstyled.
fn learned_type(app: &App, learned: &LearnedMove) -> String {
    app.moves
        .get(&learned.name)
        .map(|info| info.type_name.clone())
        .unwrap_or_default()
}

/// What the highlighted move does, wrapped to the card. Absent until its record
/// lands, where the loading placeholder stands in — the same shape the ability
/// card uses for the same reason.
fn move_description<'a>(app: &App, s: &Strings, width: usize) -> Vec<Line<'a>> {
    let code = app.language.flavor_code();
    let text = app
        .highlighted_move()
        .and_then(|learned| app.moves.get(&learned.name))
        .and_then(|info| info.flavor_for(code));

    match text {
        Some(text) => wrap_plain(text, width)
            .into_iter()
            .take(3)
            .map(|row| {
                Line::from(Span::styled(
                    format!(" {row}"),
                    Style::default().fg(theme::subtext()),
                ))
            })
            .collect(),
        None => vec![Line::from(Span::styled(
            format!(" {}", s.loading),
            Style::default().fg(theme::overlay()),
        ))],
    }
}

/// Localized label for a move's damage category. An unrecognised class shows
/// its API slug rather than being dropped, which is how a new one would
/// announce itself.
fn damage_class_label<'a>(s: &Strings, class: &'a str) -> &'a str
where
    'static: 'a,
{
    match class {
        "physical" => s.class_physical,
        "special" => s.class_special,
        "status" => s.class_status,
        other => other,
    }
}

fn render_abilities(frame: &mut Frame, app: &App, s: &Strings, full: Rect) {
    let Some(detail) = app.selected_detail() else {
        return;
    };

    let width = ABILITY_CARD_W.min(full.width);
    let text_w = width.saturating_sub(4) as usize;
    if text_w < 16 || full.height < 8 {
        return; // too cramped to be readable; leave the main view alone
    }

    let mut lines: Vec<Line> = Vec::new();
    let code = app.language.flavor_code();

    lines.push(Line::from(Span::styled(
        format!(" {}", title_case(&detail.name)),
        Style::default()
            .fg(theme::mauve())
            .add_modifier(Modifier::BOLD),
    )));

    for ability in &detail.abilities {
        lines.push(Line::raw(""));

        let mut head = vec![Span::styled(
            format!(" {}", ability_display_name(app, &ability.name)),
            Style::default()
                .fg(theme::peach())
                .add_modifier(Modifier::BOLD),
        )];
        if ability.is_hidden {
            head.push(Span::styled(
                format!("  ({})", s.ability_hidden),
                Style::default().fg(theme::overlay()),
            ));
        }
        lines.push(Line::from(head));

        // Until the text lands — or if it never does — the name above is still
        // the useful half, so the row degrades to a quiet placeholder.
        match app
            .abilities
            .get(&ability.name)
            .and_then(|info| info.flavor_for(code))
        {
            Some(text) => {
                for row in wrap_plain(text, text_w) {
                    lines.push(Line::from(Span::styled(
                        format!("  {row}"),
                        Style::default().fg(theme::subtext()),
                    )));
                }
            }
            None => lines.push(Line::from(Span::styled(
                format!("  {}", s.loading),
                Style::default().fg(theme::overlay()),
            ))),
        }
    }

    let height = (lines.len() as u16 + 3).min(full.height);
    let area = centered_fixed(width, height, full);
    frame.render_widget(Clear, area);

    let block = Block::bordered()
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(theme::mauve()))
        .title(Span::styled(
            s.abilities_title,
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::surface()));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let rows = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(inner);
    frame.render_widget(Paragraph::new(lines), rows[0]);

    let hint = Paragraph::new(Line::from(Span::styled(
        s.ability_close_hint,
        Style::default().fg(theme::overlay()),
    )))
    .alignment(Alignment::Center);
    frame.render_widget(hint, rows[1]);
}

/// An ability's name in the active language, falling back to its slug until
/// the localized text has been fetched. Callers add the hidden marker
/// themselves, since the two cards place it differently.
/// One `ability → type` row, drawn identically wherever an immunity is
/// reported. `lead` is whatever precedes the ability name: the party card
/// names the member it belongs to, the single-species card is already about
/// one Pokemon and has nothing to disambiguate.
///
/// An immunity the species might not have is marked rather than asserted. A
/// species carries one of its listed abilities, not all of them, and a card
/// that quietly dropped that distinction would promise a certainty the data
/// does not support.
fn ability_immunity_row(
    app: &App,
    s: &Strings,
    immunity: &AbilityImmunity,
    lead: &str,
) -> Line<'static> {
    let mut row = vec![
        Span::styled(lead.to_string(), Style::default().fg(theme::text())),
        Span::styled(
            ability_display_name(app, &immunity.ability),
            Style::default().fg(theme::subtext()),
        ),
        Span::styled("", Style::default().fg(theme::overlay())),
        Span::styled(
            format!(" {} ", title_case(immunity.immune_to)),
            Style::default()
                .fg(theme::base())
                .bg(theme::type_color(immunity.immune_to)),
        ),
    ];
    if !immunity.certain {
        row.push(Span::styled(
            format!("  ({})", s.immunity_maybe),
            Style::default().fg(theme::overlay()),
        ));
    }
    Line::from(row)
}

fn ability_display_name(app: &App, slug: &str) -> String {
    match app.abilities.get(slug) {
        Some(info) => info.name_for(app.language.flavor_code()),
        None => title_case(slug),
    }
}

/// Greedy word wrap for a plain paragraph of text.
fn wrap_plain(text: &str, width: usize) -> Vec<String> {
    let mut rows = Vec::new();
    let mut current = String::new();
    for word in text.split_whitespace() {
        if !current.is_empty() && current.chars().count() + 1 + word.chars().count() > width {
            rows.push(std::mem::take(&mut current));
        }
        if !current.is_empty() {
            current.push(' ');
        }
        current.push_str(word);
    }
    if !current.is_empty() {
        rows.push(current);
    }
    rows
}

fn render_team(frame: &mut Frame, app: &App, s: &Strings, full: Rect) {
    let width = TEAM_CARD_W.min(full.width);
    let text_w = width.saturating_sub(2) as usize;
    if text_w < 16 || full.height < 8 {
        return; // too cramped to be readable; leave the main view alone
    }

    let loaded = app.team_details();
    let mut lines: Vec<Line> = Vec::new();

    lines.push(Line::from(Span::styled(
        format!(" {}/{}", app.team.len(), team::MAX_MEMBERS),
        Style::default()
            .fg(theme::mauve())
            .add_modifier(Modifier::BOLD),
    )));
    lines.push(Line::raw(""));

    if app.team.is_empty() {
        lines.push(Line::from(Span::styled(
            format!(" {}", s.team_empty),
            Style::default().fg(theme::overlay()),
        )));
    }

    // Roster. A member whose record has not arrived yet is listed by name so
    // the party still reads as complete, but greyed out — the analysis below
    // genuinely does not account for it yet.
    //
    // The two lead columns are the cursor and the comparison pin, in the same
    // glyphs the list uses for the same things, so a member reads the same
    // here as it does there. They replace the row's old indent rather than
    // adding to it, so nothing to the right of them moves.
    for (i, name) in app.team.iter().enumerate() {
        let cursor = if i == app.team_cursor { "" } else { " " };
        let pin = if app.is_pinned(name) { "" } else { " " };
        let name_style = if i == app.team_cursor {
            color::highlight(theme::mauve()).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(theme::text())
        };
        let mut row = vec![
            Span::styled(cursor, Style::default().fg(theme::mauve())),
            Span::styled(pin, Style::default().fg(theme::teal())),
            Span::styled(format!(" {:<12} ", title_case(name)), name_style),
        ];
        match app.details.get(name) {
            Some(detail) => row.extend(type_chips(&detail.types)),
            None => row.push(Span::styled(
                s.loading.to_string(),
                Style::default().fg(theme::overlay()),
            )),
        }
        lines.push(Line::from(row));
    }

    if !loaded.is_empty() {
        let analysis = team::analyse(&loaded);

        // Shared weaknesses, grouped by how many members each type hits. The
        // `n/total` label counts members, not damage — an important distinction
        // next to the single-species card, where the label is a multiplier.
        lines.push(Line::raw(""));
        lines.push(section_heading(s.team_shared_weak));
        if analysis.shared_weaknesses.is_empty() {
            lines.push(all_clear(s));
        } else {
            let mut remaining = analysis.shared_weaknesses.as_slice();
            while let Some(first) = remaining.first() {
                let count = first.weak;
                let split = remaining.partition_point(|row| row.weak == count);
                let (group, rest) = remaining.split_at(split);
                let types: Vec<&str> = group.iter().map(|row| row.attacker).collect();
                let label = format!("{count}/{}", loaded.len());
                lines.extend(chip_rows(&label, &types, text_w));
                remaining = rest;
            }
        }

        lines.push(Line::raw(""));
        lines.push(section_heading(s.team_unresisted));
        push_chip_section(&mut lines, &analysis.unresisted, text_w, s);

        // Placed directly under "resisted by nobody", because that is exactly
        // the claim it qualifies: the chart cannot see these, so an unresisted
        // type may still have an answer sitting right here.
        if !analysis.ability_immunities.is_empty() {
            lines.push(Line::raw(""));
            lines.push(section_heading(s.immune_by_ability));
            for immunity in &analysis.ability_immunities {
                // Led by the member's name: this card lists six Pokemon, so an
                // unattributed row would not say whose immunity it is.
                let lead = format!("  {} · ", title_case(&immunity.pokemon));
                lines.push(ability_immunity_row(app, s, immunity, &lead));
            }
        }

        lines.push(Line::raw(""));
        lines.push(section_heading(s.team_offense_gaps));
        push_chip_section(&mut lines, &analysis.offense_gaps, text_w, s);
    }

    let height = (lines.len() as u16 + 3).min(full.height);
    let area = centered_fixed(width, height, full);
    frame.render_widget(Clear, area);

    let block = Block::bordered()
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(theme::mauve()))
        .title(Span::styled(
            s.team_title,
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::surface()));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let rows = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(inner);
    frame.render_widget(Paragraph::new(lines), rows[0]);

    let hint = Paragraph::new(Line::from(Span::styled(
        s.team_close_hint,
        Style::default().fg(theme::overlay()),
    )))
    .alignment(Alignment::Center);
    frame.render_widget(hint, rows[1]);
}

/// Renders one chip section, or the "nothing to report" line when it is empty.
/// On this card an empty section is good news, so it reads as reassurance
/// rather than as missing data.
fn push_chip_section(lines: &mut Vec<Line<'static>>, types: &[&str], width: usize, s: &Strings) {
    if types.is_empty() {
        lines.push(all_clear(s));
    } else {
        lines.extend(chip_rows("", types, width));
    }
}

fn all_clear(s: &Strings) -> Line<'static> {
    Line::from(Span::styled(
        format!("  {}", s.team_all_clear),
        Style::default().fg(theme::green()),
    ))
}

/// Draws the head-to-head card: the pinned species against the one on display,
/// stat by stat.
///
/// The arithmetic is [`compare`]'s; what this adds is the reading order. Every
/// row is a pair of bars growing outwards from the labels, so the answer to
/// "which of these two is bulkier" arrives before any of the numbers are read,
/// and the margin at the end of the row says by how much for the ones that are.
fn render_compare(frame: &mut Frame, app: &App, s: &Strings, full: Rect) {
    let Some((left, right)) = app.comparison() else {
        return; // nothing pinned, or nothing on display to pin it against
    };

    let width = COMPARE_CARD_W.min(full.width);
    // Two borders, and a column of breathing room inside each of them: the
    // header, the chips and the abilities all sit against the frame otherwise.
    let inner_w = width.saturating_sub(4) as usize;
    // Two bars, two values, a label and the margin. Below this there is no
    // room left for bars, and a card of bare numbers is what the reader could
    // already have got by flipping between the two species by hand.
    let bar_w =
        inner_w.saturating_sub(COMPARE_VAL_W * 2 + STAT_LABEL_WIDTH + COMPARE_MARGIN_W + 5) / 2;
    if bar_w < 6 || full.height < 18 {
        return; // too cramped to be readable; leave the main view alone
    }

    let rows = compare::stat_rows(left, right);
    let peak = compare::peak(&rows);

    let height = (rows.len() as u16 + 15).min(full.height);
    let area = centered_fixed(width, height, full);
    frame.render_widget(Clear, area);

    let block = Block::bordered()
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(theme::mauve()))
        .title(Span::styled(
            s.compare_title,
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::surface()));
    let inner = block.inner(area);
    frame.render_widget(block, area);
    let inner = Rect {
        x: inner.x + 1,
        width: inner.width.saturating_sub(2),
        ..inner
    };

    let body = Layout::vertical([
        Constraint::Length(2),                     // names, then type chips
        Constraint::Length(1),                     // spacer
        Constraint::Length(rows.len() as u16 + 2), // stats, spacer, totals
        Constraint::Length(1),                     // spacer
        Constraint::Length(1),                     // best-hit heading
        Constraint::Length(1),                     // best-hit row
        Constraint::Length(1),                     // spacer
        Constraint::Min(0),                        // measurements and abilities
        Constraint::Length(1),                     // close hint
    ])
    .split(inner);

    // Each side keeps to its own half throughout, and the right one is mirrored
    // — right-aligned against the edge it grows from — so the two read as two
    // columns rather than as one list of pairs.
    let head =
        Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)]).split(body[0]);
    frame.render_widget(Paragraph::new(side_heading(left)), head[0]);
    frame.render_widget(
        Paragraph::new(side_heading(right)).alignment(Alignment::Right),
        head[1],
    );

    let mut stat_lines: Vec<Line> = rows
        .iter()
        .map(|row| {
            compare_row(
                app.language.stat_label(row.kind),
                row.left as u32,
                row.right as u32,
                Some((row.left, row.right, peak)),
                bar_w,
                s,
            )
        })
        .collect();
    stat_lines.push(Line::raw(""));
    // The totals are on a scale of their own — a species' six stats sum to
    // several hundred — so the row carries the numbers without bars rather than
    // drawing them against a ruler the rows above do not share.
    stat_lines.push(compare_row(
        s.total_label,
        left.stat_total(),
        right.stat_total(),
        None,
        bar_w,
        s,
    ));
    frame.render_widget(Paragraph::new(stat_lines), body[2]);

    frame.render_widget(Paragraph::new(section_heading(s.compare_best_hit)), body[4]);
    let hits =
        Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)]).split(body[5]);
    frame.render_widget(Paragraph::new(best_hit_line(left, right)), hits[0]);
    frame.render_widget(
        Paragraph::new(best_hit_line(right, left)).alignment(Alignment::Right),
        hits[1],
    );

    let facts =
        Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)]).split(body[7]);
    let fact_w = facts[0].width as usize;
    frame.render_widget(Paragraph::new(side_facts(app, left, fact_w)), facts[0]);
    frame.render_widget(
        Paragraph::new(side_facts(app, right, fact_w)).alignment(Alignment::Right),
        facts[1],
    );

    let hint = Paragraph::new(Line::from(Span::styled(
        s.compare_hint,
        Style::default().fg(theme::overlay()),
    )))
    .alignment(Alignment::Center);
    frame.render_widget(hint, body[8]);
}

/// One side's name, dex number and typing, for the top of the comparison card.
fn side_heading(species: &PokemonDetail) -> Vec<Line<'static>> {
    vec![
        Line::from(vec![
            Span::styled(
                title_case(&species.name),
                Style::default()
                    .fg(theme::mauve())
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                format!("  #{:04}", species.dex_number),
                Style::default().fg(theme::overlay()),
            ),
        ]),
        Line::from(type_chips(&species.types)),
    ]
}

/// One comparison row: a pair of bars growing outwards from the label, the two
/// numbers beside it, and the margin at the end.
///
/// `bars` carries the values to draw and the number they scale against; the
/// totals line passes `None`, which lays the numbers out on the same columns
/// with the bar space left blank.
fn compare_row(
    label: &str,
    left: u32,
    right: u32,
    bars: Option<(u16, u16, u16)>,
    bar_w: usize,
    s: &Strings,
) -> Line<'static> {
    let winner = compare::side(left, right);
    let (left_color, right_color) = match winner {
        compare::Side::Left => (theme::green(), theme::overlay()),
        compare::Side::Right => (theme::overlay(), theme::green()),
        compare::Side::Tie => (theme::lavender(), theme::lavender()),
    };
    let emphasis = |side| match winner == side {
        true => Modifier::BOLD,
        false => Modifier::empty(),
    };

    let (left_fill, right_fill) = match bars {
        Some((l, r, peak)) => (fill(l, peak, bar_w), fill(r, peak, bar_w)),
        None => (0, 0),
    };

    Line::from(vec![
        Span::raw(" ".repeat(bar_w - left_fill)),
        Span::styled("".repeat(left_fill), Style::default().fg(left_color)),
        Span::styled(
            format!(" {left:>COMPARE_VAL_W$} "),
            Style::default()
                .fg(left_color)
                .add_modifier(emphasis(compare::Side::Left)),
        ),
        Span::styled(
            format!("{label:^STAT_LABEL_WIDTH$}"),
            Style::default().fg(theme::subtext()),
        ),
        Span::styled(
            format!(" {right:<COMPARE_VAL_W$} "),
            Style::default()
                .fg(right_color)
                .add_modifier(emphasis(compare::Side::Right)),
        ),
        Span::styled("".repeat(right_fill), Style::default().fg(right_color)),
        Span::raw(" ".repeat(bar_w - right_fill)),
        Span::styled(
            format!(" {:<COMPARE_MARGIN_W$}", margin_label(left, right, s)),
            Style::default().fg(match winner {
                compare::Side::Tie => theme::overlay(),
                _ => theme::green(),
            }),
        ),
    ])
}

/// How many cells of a `bar_w` bar a value fills, against the biggest number on
/// the card. A value that is not quite zero still gets a cell, so a row reads
/// as a very short bar rather than as a missing one.
fn fill(value: u16, peak: u16, bar_w: usize) -> usize {
    if value == 0 || peak == 0 {
        return 0;
    }
    ((value as usize * bar_w) / peak as usize).clamp(1, bar_w)
}

/// The end of a comparison row: an arrow pointing at the side that wins it and
/// by how much, or the word for a row they are level on.
fn margin_label(left: u32, right: u32, s: &Strings) -> String {
    match compare::side(left, right) {
        compare::Side::Left => format!("{}", left - right),
        compare::Side::Right => format!("{}", right - left),
        compare::Side::Tie => s.compare_tie.to_string(),
    }
}

/// The hardest same-type hit `attacker` has on `defender`, as a chip and a
/// multiplier.
fn best_hit_line(attacker: &PokemonDetail, defender: &PokemonDetail) -> Line<'static> {
    let Some(hit) = compare::best_hit(attacker, defender) else {
        return Line::raw("");
    };
    let label = typechart::multiplier_label(hit.multiplier);
    Line::from(vec![
        Span::styled(
            format!(" {} ", title_case(hit.attack_type)),
            Style::default()
                .fg(theme::base())
                .bg(theme::type_color(hit.attack_type))
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!(" {label}"),
            Style::default()
                .fg(match hit.multiplier > 1.0 {
                    true => theme::peach(),
                    false => theme::subtext(),
                })
                .add_modifier(Modifier::BOLD),
        ),
    ])
}

/// One side's measurements and abilities, for the foot of the comparison card.
fn side_facts(app: &App, species: &PokemonDetail, width: usize) -> Vec<Line<'static>> {
    let mut lines = vec![Line::from(Span::styled(
        format!(
            "{:.1} m · {:.1} kg",
            species.height as f32 / 10.0,
            species.weight as f32 / 10.0
        ),
        Style::default().fg(theme::subtext()),
    ))];

    let abilities: Vec<String> = species
        .abilities
        .iter()
        .map(|ability| ability_display_name(app, &ability.name))
        .collect();
    if !abilities.is_empty() {
        // Two lines at most: a third would push the hint off a card sized for
        // the pair, and the ability card behind `A` has the full list anyway.
        lines.extend(
            wrap_plain(&abilities.join(" · "), width.max(8))
                .into_iter()
                .take(2)
                .map(|text| Line::from(Span::styled(text, Style::default().fg(theme::text())))),
        );
    }
    lines
}

/// Wide enough for the foot hint, which is longer than any form's name and
/// longer still in German.
const FORMS_CARD_W: u16 = 48;

/// The species' varieties as a list to pick from: the info card's Forms row
/// says they exist, and this is where one is chosen and jumped to.
///
/// Built like the language picker, because it is the same kind of card — a
/// short list of alternatives with one of them currently in force — and the
/// `●` marking the variety on display means here what it means there.
fn render_forms(frame: &mut Frame, app: &App, s: &Strings, full: Rect) {
    let Some(detail) = app.selected_detail() else {
        return;
    };
    let width = FORMS_CARD_W.min(full.width);
    // A card, not a second screen: it leaves a margin so the list behind it
    // stays visible, and Pikachu's seventeen varieties scroll inside whatever
    // that leaves rather than growing the card past the terminal.
    let height = full
        .height
        .saturating_sub(4)
        .min(detail.forms.len() as u16 + 4);
    if width < 20 || height < 6 {
        return; // too cramped to be readable; leave the main view alone
    }

    let area = centered_fixed(width, height, full);
    frame.render_widget(Clear, area);

    let block = Block::bordered()
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(theme::mauve()))
        .title(Span::styled(
            s.forms_title,
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::surface()));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let rows = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(inner);

    // Centre the cursor in the window where there is room on both sides, and
    // pin it to an end where there is not, so the last forms stay reachable.
    let window = rows[0].height as usize;
    let first = app
        .forms_cursor
        .saturating_sub(window / 2)
        .min(detail.forms.len().saturating_sub(window));

    let mut lines: Vec<Line> = Vec::with_capacity(window);
    for (i, form) in detail.forms.iter().enumerate().skip(first).take(window) {
        let selected = i == app.forms_cursor;
        let shown = *form == detail.name;
        let marker = if shown { "" } else { "" };
        let label = format!(" {marker} {} ", form_label(form, &detail.species));
        let style = if selected {
            color::highlight(theme::mauve()).add_modifier(Modifier::BOLD)
        } else if shown {
            Style::default().fg(theme::mauve())
        } else {
            Style::default().fg(theme::text())
        };
        lines.push(Line::from(Span::styled(label, style)));
    }
    frame.render_widget(Paragraph::new(lines), rows[0]);

    let hint = Paragraph::new(Line::from(Span::styled(
        s.forms_close_hint,
        Style::default().fg(theme::overlay()),
    )))
    .alignment(Alignment::Center);
    frame.render_widget(hint, rows[1]);
}

fn render_language_picker(frame: &mut Frame, app: &App, s: &Strings, full: Rect) {
    let width = 26u16;
    let height = Language::ALL.len() as u16 + 4; // borders + title pad + hint
    let area = centered_fixed(width, height, full);
    frame.render_widget(Clear, area);

    let block = Block::bordered()
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(theme::mauve()))
        .title(Span::styled(
            s.language_title,
            Style::default()
                .fg(theme::mauve())
                .add_modifier(Modifier::BOLD),
        ))
        .style(Style::default().bg(theme::surface()));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    let rows = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(inner);

    let mut lines: Vec<Line> = Vec::with_capacity(Language::ALL.len());
    for (i, lang) in Language::ALL.iter().enumerate() {
        let selected = i == app.lang_cursor;
        let active = *lang == app.language;
        let marker = if active { "" } else { "" };
        let label = format!(" {marker} {:<10} {} ", lang.label(), lang.tag());
        let style = if selected {
            color::highlight(theme::mauve()).add_modifier(Modifier::BOLD)
        } else if active {
            Style::default().fg(theme::mauve())
        } else {
            Style::default().fg(theme::text())
        };
        lines.push(Line::from(Span::styled(label, style)));
    }
    frame.render_widget(Paragraph::new(lines), rows[0]);

    let hint = Paragraph::new(Line::from(Span::styled(
        "↑/↓ · Enter · Esc",
        Style::default().fg(theme::overlay()),
    )))
    .alignment(Alignment::Center);
    frame.render_widget(hint, rows[1]);
}

/// A fixed-size `Rect` centred within `area` (clamped to fit).
fn centered_fixed(width: u16, height: u16, area: Rect) -> Rect {
    let w = width.min(area.width);
    let h = height.min(area.height);
    Rect {
        x: area.x + (area.width.saturating_sub(w)) / 2,
        y: area.y + (area.height.saturating_sub(h)) / 2,
        width: w,
        height: h,
    }
}

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

    use ratatui::backend::TestBackend;
    use ratatui::Terminal;

    use crate::app::{app_listing, loaded};
    use crate::color::Depth;
    use crate::models::{Ability, Stat, StatKind};

    /// Draws one frame into an off-screen buffer and returns its rows as plain
    /// text.
    ///
    /// The panel tests assert on those lines rather than on cells and styles,
    /// deliberately: a snapshot that pins every attribute fails on each
    /// cosmetic change and gets deleted, and what is worth keeping is that the
    /// right panel says the right thing at the right size.
    fn frame_rows(app: &mut App, width: u16, height: u16) -> Vec<String> {
        let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test backend");
        terminal
            .draw(|frame| render(frame, app))
            .expect("a frame draws");
        let buffer = terminal.backend().buffer().clone();
        (0..buffer.area.height)
            .map(|y| {
                (0..buffer.area.width)
                    .map(|x| buffer.cell((x, y)).map_or(" ", |cell| cell.symbol()))
                    .collect()
            })
            .collect()
    }

    /// One frame as a single string, for "does this appear at all" checks.
    fn screen(app: &mut App, width: u16, height: u16) -> String {
        frame_rows(app, width, height).join("\n")
    }

    /// The right-hand column of a frame — the detail and evolution panels —
    /// so a name that is also in the sidebar cannot answer for them.
    fn right_column(app: &mut App, width: u16, height: u16) -> String {
        let split = (f32::from(width) * 0.32) as usize;
        frame_rows(app, width, height)
            .iter()
            .map(|row| row.chars().skip(split).collect::<String>())
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// An app listing the Kanto ghosts, with Gengar loaded and on display.
    fn showing_gengar() -> App {
        let mut app = app_listing(&[(92, "gastly"), (93, "haunter"), (94, "gengar")]);
        app.color_depth = Depth::None;
        app.browser.recompute();
        app.details.insert("gengar".to_string(), gengar());
        app.selected_name = Some("gengar".to_string());
        app
    }

    /// Enough of a record for the info card to have something to draw in every
    /// one of its rows.
    fn gengar() -> PokemonDetail {
        PokemonDetail {
            dex_number: 94,
            types: vec!["ghost".to_string(), "poison".to_string()],
            abilities: vec![Ability {
                name: "cursed-body".to_string(),
                is_hidden: false,
            }],
            stats: vec![
                Stat {
                    kind: StatKind::Hp,
                    base: 60,
                },
                Stat {
                    kind: StatKind::SpecialAttack,
                    base: 130,
                },
            ],
            height: 15,
            weight: 405,
            ..loaded("gengar")
        }
    }

    #[test]
    fn the_sidebar_lists_what_the_filter_left_and_counts_it() {
        let mut app = showing_gengar();
        app.browser.query = "ga".to_string();
        app.browser.recompute();

        let frame = screen(&mut app, 120, 40);
        assert!(frame.contains("Gastly"), "{frame}");
        assert!(frame.contains("Gengar"));
        assert!(!frame.contains("Haunter"), "filtered out, so not drawn");
        assert!(frame.contains("(2)"), "the title counts what survived");
        assert!(frame.contains(""), "and the cursor sits on a row");
    }

    #[test]
    fn the_sidebar_says_what_it_is_waiting_for_rather_than_drawing_an_empty_list() {
        let s = Language::English.strings();

        // Before the master list lands.
        let mut app = app_listing(&[]);
        app.color_depth = Depth::None;
        app.list_loading = true;
        assert!(screen(&mut app, 120, 40).contains(s.loading_list));

        // A filter term whose roster has not arrived is a wait, not a miss —
        // the difference the list would otherwise report as "no results".
        let mut app = showing_gengar();
        app.browser.query = "type:ghost".to_string();
        app.browser.recompute();
        assert!(screen(&mut app, 120, 40).contains(s.loading_filter));

        // A search that genuinely matches nothing says so.
        let mut app = showing_gengar();
        app.browser.query = "zzz".to_string();
        app.browser.recompute();
        assert!(screen(&mut app, 120, 40).contains(s.no_results));
    }

    #[test]
    fn the_detail_panel_draws_the_species_it_was_given() {
        let mut app = showing_gengar();
        let panel = right_column(&mut app, 120, 40);

        assert!(panel.contains("Gengar"), "{panel}");
        assert!(panel.contains("#0094"), "the dex number, padded");
        assert!(
            panel.contains("Ghost") && panel.contains("Poison"),
            "type chips"
        );
        assert!(
            panel.contains("Cursed Body"),
            "abilities come free with the record"
        );
        assert!(
            panel.contains("1.5 m") && panel.contains("40.5 kg"),
            "measurements"
        );
        assert!(
            panel.contains("Total: 190"),
            "the stat total is summed, not stored"
        );
    }

    #[test]
    fn the_detail_panel_says_when_there_is_nothing_to_show_yet() {
        let s = Language::English.strings();

        // Nothing selected at all.
        let mut app = app_listing(&[(94, "gengar")]);
        app.color_depth = Depth::None;
        app.browser.recompute();
        assert!(right_column(&mut app, 120, 40).contains(s.no_selection));

        // Selected, and the record still on its way.
        let mut app = app_listing(&[(94, "gengar")]);
        app.color_depth = Depth::None;
        app.browser.recompute();
        app.selected_name = Some("gengar".to_string());
        app.loading_detail = Some("gengar".to_string());
        assert!(right_column(&mut app, 120, 40).contains(s.loading));

        // And a fetch that failed says what went wrong instead of spinning
        // forever or going blank.
        let mut app = app_listing(&[(94, "gengar")]);
        app.color_depth = Depth::None;
        app.browser.recompute();
        app.error = Some("the network is down".to_string());
        assert!(right_column(&mut app, 120, 40).contains("the network is down"));
    }

    #[test]
    fn the_evolution_panel_says_when_a_species_has_no_chain() {
        let s = Language::English.strings();
        let mut app = showing_gengar();
        // Loaded, but no chain came with it.
        assert!(right_column(&mut app, 120, 40).contains(s.no_evolution));
    }

    #[test]
    fn a_chain_that_fits_is_drawn_as_cards_and_one_that_does_not_falls_back_to_the_tree() {
        // Both sides of the same threshold, through the renderer rather than
        // through `card_grid` alone: what the fallback is for is that the
        // chain is still readable, and only a drawn frame shows that.
        let mut app = showing_gengar();
        app.evolutions.insert("gengar".to_string(), chain(3, 1));

        // Three stages down one line: the panel has room for a card each, and
        // the text tree's connectors are nowhere in the frame.
        let cards = right_column(&mut app, 120, 40);
        assert!(cards.contains("Stage"), "{cards}");
        assert!(
            !cards.contains("└── ") && !cards.contains("├── "),
            "cards, not the tree: {cards}"
        );

        // Eight branches need a lane each, which no panel in that column ever
        // has, so the same chain degrades to the compact tree.
        app.evolutions.insert("gengar".to_string(), chain(2, 8));
        let tree = right_column(&mut app, 120, 40);
        assert!(
            tree.contains("└── ") || tree.contains("├── "),
            "the tree, not cards: {tree}"
        );
    }

    /// A chain shaped like `children`: one root, then a leaf per entry, nested
    /// `depth` deep along the first branch.
    fn chain(depth: usize, leaves: usize) -> EvolutionTree {
        let mut node = EvolutionTree {
            name: "leaf".to_string(),
            condition: None,
            children: Vec::new(),
        };
        for _ in 1..depth {
            node = EvolutionTree {
                name: "stage".to_string(),
                condition: None,
                children: vec![node],
            };
        }
        // Widen the last stage out to `leaves` branches.
        let deepest = (1..depth).fold(&mut node, |n, _| &mut n.children[0]);
        for _ in 1..leaves {
            deepest.children.push(EvolutionTree {
                name: "branch".to_string(),
                condition: None,
                children: Vec::new(),
            });
        }
        node
    }

    fn canvas(width: u16, height: u16) -> Rect {
        Rect {
            x: 0,
            y: 0,
            width,
            height,
        }
    }

    fn fact(label: &str, value: &str) -> (String, String) {
        (label.to_string(), value.to_string())
    }

    /// The text of each row, gaps included.
    fn row_text(rows: &[Line]) -> Vec<String> {
        rows.iter().map(|line| line.to_string()).collect()
    }

    #[test]
    fn facts_pack_into_a_row_until_it_is_full() {
        let facts = [fact("A", "one"), fact("B", "two"), fact("C", "three")];
        // "A: one" is 6, the gap 4, "B: two" 6: 16 fits a row of 20 and
        // "C: three" (8 more) does not.
        assert_eq!(
            row_text(&fact_rows(&facts, 20)),
            ["A: one    B: two", "C: three"]
        );
        // Wide enough, and they all sit on one row.
        assert_eq!(
            row_text(&fact_rows(&facts, 40)),
            ["A: one    B: two    C: three"]
        );
    }

    #[test]
    fn a_fact_wider_than_the_column_still_gets_a_row() {
        // The alternative is an infinite loop or a dropped fact; a clipped
        // row is the honest answer.
        let facts = [fact("Habitat", "Somewhere very far away indeed")];
        assert_eq!(fact_rows(&facts, 10).len(), 1);
        assert!(fact_rows(&[], 10).is_empty());
    }

    #[test]
    fn a_label_row_wraps_under_its_value_and_loses_nothing() {
        // Wide enough, and the row is one line.
        assert_eq!(
            row_text(&label_rows("Forms", "Alola · Gmax", 40)),
            ["Forms: Alola · Gmax"]
        );
        // Too narrow, and the rest goes on the next line indented under the
        // value — the names are all still there, which is the point of
        // wrapping rather than clipping.
        assert_eq!(
            row_text(&label_rows("Forms", "Alola · Gmax", 14)),
            ["Forms: Alola ·", "       Gmax"]
        );
    }

    #[test]
    fn a_fact_with_no_label_is_its_own_explanation() {
        assert_eq!(
            row_text(&fact_rows(&[fact("", "♂ 50% · ♀ 50%")], 40)),
            ["♂ 50% · ♀ 50%"]
        );
    }

    #[test]
    fn the_field_rows_say_genderless_and_leave_out_what_the_record_lacks() {
        let s = Language::English.strings();
        let mut field = FieldData {
            egg_groups: vec!["monster".to_string(), "plant".to_string()],
            capture_rate: 45,
            base_happiness: Some(50),
            growth_rate: Some("medium-slow".to_string()),
            gender_rate: 1,
            habitat: Some("grassland".to_string()),
        };
        let text = row_text(&field_rows(&field, &s, 200)).join(" ");
        assert!(text.contains("Egg groups: Monster · Grass"), "{text}");
        assert!(text.contains("♂ 87.5% · ♀ 12.5%"), "{text}");
        assert!(text.contains("Catch rate: 45 (hard)"), "{text}");
        assert!(text.contains("Growth: Medium Slow"), "{text}");
        assert!(text.contains("Habitat: Grassland"), "{text}");

        // Genderless, and nothing recorded for the optional three.
        field.gender_rate = -1;
        field.habitat = None;
        field.base_happiness = None;
        field.growth_rate = None;
        let text = row_text(&field_rows(&field, &s, 200)).join(" ");
        assert!(text.contains("Genderless"), "{text}");
        assert!(
            !text.contains("Habitat"),
            "a null habitat drops the row: {text}"
        );
        assert!(!text.contains("None"), "{text}");
        assert!(!text.contains("Growth"), "{text}");
    }

    #[test]
    fn a_two_stage_chain_gets_cards_in_a_panel() {
        assert_eq!(card_grid(canvas(60, 16), 2, 2), Some((30, 8)));
    }

    #[test]
    fn a_column_never_grows_past_the_card_cap() {
        // Half of a 130-column screen would be a 65-wide card of mostly
        // whitespace; the graph is drawn tighter and centred instead.
        assert_eq!(
            card_grid(canvas(130, 16), 2, 2),
            Some((MAX_CARD_W + EVO_GAP, 8))
        );
    }

    #[test]
    fn eevees_eight_branches_do_not_fit_the_panel() {
        // The evolution panel realistically gets 15-20 rows; eight lanes need
        // MIN_CARD_H each, so the chain falls back to the text tree there...
        assert_eq!(card_grid(canvas(120, 18), 2, 8), None);
        // ...and gets its sprite cards once the full screen is handed over.
        assert!(card_grid(canvas(120, 40), 2, 8).is_some());
    }

    #[test]
    fn a_chain_too_wide_for_its_columns_falls_back() {
        // Nine stages across 80 columns leaves under MIN_CARD_W each, however
        // many rows are available.
        assert_eq!(card_grid(canvas(80, 60), 9, 1), None);
    }

    #[test]
    fn an_empty_canvas_is_not_divided_by_zero() {
        assert_eq!(card_grid(canvas(0, 0), 0, 0), None);
    }

    #[test]
    fn the_hint_row_prefers_the_cursors_requirement_over_the_key_map() {
        let s = Language::English.strings();
        let tree = chain(2, 1);
        // No cursor: the view's own hint.
        let plain = chain_hint(&tree, None, &s, "keys");
        assert_eq!(plain.spans.len(), 1);
        assert_eq!(plain.spans[0].content, "keys");
        // A cursor on a node nothing is known about keeps the same hint: an
        // empty requirement is not worth a row of its own.
        assert_eq!(
            chain_hint(&tree, Some("leaf"), &s, "keys").spans[0].content,
            "keys"
        );
    }
}