pokeductor 0.3.1

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
//! 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, SortKey};
use crate::i18n::{EvoStrings, Language, Strings};
use crate::models::{title_case, EvolutionTree, Sprite};
use crate::team;
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.team_card {
        render_team(frame, app, &strings, area);
    }
    if app.language_picker {
        render_language_picker(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.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.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.sort {
        SortKey::Dex => s.sort_dex,
        SortKey::Name => s.sort_name,
    };
    let title = format!(
        "{}({}) ⇅ {} ",
        s.sidebar_title,
        app.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:` filter cannot match anything until its roster arrives, so say
    // that rather than claiming the search found nothing.
    if app.awaiting_type_roster() {
        render_centered_loading(frame, inner, s.loading_types, app.spinner);
        return;
    }
    if app.filtered.is_empty() {
        render_centered_text(frame, inner, s.no_results, theme::OVERLAY);
        return;
    }

    let items: Vec<ListItem> = app
        .filtered
        .iter()
        .filter_map(|&idx| app.all_pokemon.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),
            };
            let in_team = app.is_in_team(&p.name);
            ListItem::new(Line::from(vec![
                Span::styled(
                    if in_team { "" } else { "  " },
                    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(
        Style::default()
            .fg(theme::BASE)
            .bg(theme::MAUVE)
            .add_modifier(Modifier::BOLD),
    );
    frame.render_stateful_widget(list, inner, &mut app.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.
    //
    // Three abilities plus a "hidden" marker overrun a narrow panel, so the
    // row is wrapped onto continuation lines rather than clipped: a name cut
    // off halfway is worse than one on the next line.
    if !detail.abilities.is_empty() {
        let label = format!("{}: ", s.abilities_label);
        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();

        let indent = " ".repeat(label.chars().count());
        let budget = (info.width as usize).saturating_sub(label.chars().count());
        for (row, text) in wrap_plain(&entries.join(" · "), budget.max(8))
            .into_iter()
            .enumerate()
        {
            lines.push(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)),
            ]));
        }
    }

    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),
        ),
    ]));

    // 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 {
        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),
    }
}

/// 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;
    Color::Rgb(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);
    let canvas = rows[0];

    let depth = tree.depth() as u16;
    let leaves = tree.leaf_count() as u16;
    let col_w = canvas.width.checked_div(depth).unwrap_or(0);
    let lane_h = canvas.height.checked_div(leaves).unwrap_or(0);

    // Draw the sprite graph when every card has room; otherwise fall back to the
    // compact text tree so cramped terminals still show the relationships.
    if col_w >= MIN_CARD_W && lane_h >= MIN_CARD_H {
        let mut lane = 0u16;
        place_node(
            frame, app, s, tree, current, cursor, canvas, col_w, lane_h, 0, &mut lane,
        );
    } else {
        let lines = evolution_lines(tree, cursor.or(current), &s.evo, canvas.width);
        frame.render_widget(Paragraph::new(lines), canvas);
    }

    // The bottom row doubles as a requirement readout: while the cursor sits on
    // a member, spell out in full what it takes to get there — the cards only
    // have room for the headline condition.
    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());

    let hint = 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(
            if focused {
                s.evo_nav_hint
            } else {
                s.expand_hint
            },
            Style::default().fg(theme::OVERLAY),
        )),
    };
    frame.render_widget(Paragraph::new(hint).alignment(Alignment::Center), rows[1]);
}

// --- 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;

/// 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 {
        Style::default()
            .fg(theme::BASE)
            .bg(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;
/// 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.
    lines.push(section_heading(s.matchups_defense));
    for group in typechart::defensive_groups(&detail.types) {
        lines.extend(chip_rows(group.label, &group.types, text_w));
    }

    // 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),
        ("T", h.act_types),
        ("A", h.act_abilities),
        ("X", h.act_shiny),
        ("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),
        ("gen:1", h.act_by_generation),
        ("", ""),
        ("", h.ctx_evolution),
        ("← → ↑ ↓ · h j k l", h.act_chain_move),
        ("Enter", h.act_chain_jump),
        ("X", h.act_shiny),
        ("Esc · Tab", h.act_back),
        ("", ""),
        ("", 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()
}

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.
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.
    for name in &app.team {
        let mut row = vec![Span::styled(
            format!("  {:<12} ", title_case(name)),
            Style::default().fg(theme::TEXT),
        )];
        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.team_ability_immunity));
            for immunity in &analysis.ability_immunities {
                let mut row = vec![
                    Span::styled(
                        format!("  {} · ", title_case(&immunity.member)),
                        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.team_maybe),
                        Style::default().fg(theme::OVERLAY),
                    ));
                }
                lines.push(Line::from(row));
            }
        }

        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),
    ))
}

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 {
            Style::default()
                .fg(theme::BASE)
                .bg(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,
    }
}