pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
use ratatui::{
    Frame,
    layout::{Alignment, Constraint, Direction, Layout},
    prelude::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap},
};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use super::common::render_simple_list_modal;
use crate::state::{
    AppState,
    modal::{
        DoasPersistSetupModalState, DoasPersistSetupPhase, StartupSetupTask,
        SudoTimestampSetupModalState, SudoTimestampSetupPhase,
    },
    types::{OptionalDepRow, RepositoryKeyTrust, RepositoryModalRow, RepositoryPacmanStatus},
};
use crate::theme::{Theme, theme};

/// What: Render the optional dependencies modal with install status indicators.
///
/// Inputs:
/// - `f`: Frame to render into
/// - `area`: Full screen area used to center the modal
/// - `rows`: Optional dependency entries (label, package, status)
/// - `selected`: Index of the currently highlighted row
///
/// Output:
/// - Draws the modal content, highlights the selected row, and updates
///   `app.optional_deps_modal_rect` / `app.optional_deps_wizard_rect` for mouse hit-testing.
///
/// Details:
/// - Marks installed rows, shows optional notes, and reuses the common simple modal renderer for
///   consistent styling.
/// - Stores the rendered `[Wizard]` button bounds in app state so pointer interactions can detect
///   clicks on the button.
/// - Stores the modal outer bounds so the wheel can scroll the selection inside the dialog.
#[allow(clippy::many_single_char_names)]
pub fn render_optional_deps(
    f: &mut Frame,
    area: Rect,
    rows: &[OptionalDepRow],
    selected: usize,
    selected_pkg_names: &std::collections::HashSet<String>,
    app: &mut crate::state::AppState,
) {
    let th = theme();
    let w = area.width.saturating_sub(8).min(80);
    let h = area.height.saturating_sub(8).min(20);
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let rect = ratatui::prelude::Rect {
        x,
        y,
        width: w,
        height: h,
    };
    app.optional_deps_modal_rect = Some((rect.x, rect.y, rect.width, rect.height));
    // Build content lines with selection and install status markers
    let mut lines: Vec<Line<'static>> = Vec::new();
    lines.push(Line::from(Span::styled(
        crate::i18n::t(app, "app.modals.optional_deps.heading"),
        Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
    )));
    lines.push(Line::from(""));

    for (i, row) in rows.iter().enumerate() {
        let is_sel = selected == i;
        let selected_mark = if !row.installed && row.selectable {
            if selected_pkg_names.contains(&row.package) {
                "[x]"
            } else {
                "[ ]"
            }
        } else {
            "   "
        };
        let (mark, color) = if row.installed {
            (
                crate::i18n::t(app, "app.modals.optional_deps.markers.installed"),
                th.green,
            )
        } else {
            (
                crate::i18n::t(app, "app.modals.optional_deps.markers.not_installed"),
                th.overlay1,
            )
        };
        let style = if is_sel {
            Style::default()
                .fg(th.crust)
                .bg(th.lavender)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(th.text)
        };
        let mut segs: Vec<Span> = Vec::new();
        segs.push(Span::styled(
            format!("{selected_mark} {}  ", row.label),
            style,
        ));
        segs.push(Span::styled(
            format!("[{}]", row.package),
            Style::default().fg(th.overlay1),
        ));
        segs.push(Span::raw("  "));
        segs.push(Span::styled(mark.clone(), Style::default().fg(color)));
        if let Some(note) = &row.note {
            segs.push(Span::raw("  "));
            segs.push(Span::styled(
                format!("({note})"),
                Style::default().fg(th.overlay2),
            ));
        }
        lines.push(Line::from(segs));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        crate::i18n::t(app, "app.modals.optional_deps.footer_hint"),
        Style::default().fg(th.subtext1),
    )));

    f.render_widget(Clear, rect);
    let boxw = Paragraph::new(lines)
        .style(Style::default().fg(th.text).bg(th.mantle))
        .wrap(Wrap { trim: true })
        .block(
            Block::default()
                .title(Span::styled(
                    format!(
                        " {} ",
                        crate::i18n::t(app, "app.modals.optional_deps.title")
                    ),
                    Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
                ))
                .borders(Borders::ALL)
                .border_type(BorderType::Double)
                .border_style(Style::default().fg(th.mauve))
                .style(Style::default().bg(th.mantle)),
        );
    f.render_widget(boxw, rect);

    // Top-right Wizard button.
    let wizard_label = crate::i18n::t(app, "app.modals.optional_deps.wizard_button");
    let wizard_w = u16::try_from(UnicodeWidthStr::width(wizard_label.as_str())).unwrap_or(8);
    let wizard_x = rect.x + rect.width.saturating_sub(wizard_w + 2);
    let wizard_y = rect.y;
    app.optional_deps_wizard_rect = Some((wizard_x, wizard_y, wizard_w, 1));
    f.render_widget(
        Paragraph::new(Line::from(Span::styled(
            wizard_label.as_str(),
            Style::default()
                .fg(th.mauve)
                .bg(th.surface2)
                .add_modifier(Modifier::BOLD),
        ))),
        Rect {
            x: wizard_x,
            y: wizard_y,
            width: wizard_w,
            height: 1,
        },
    );
}

/// What: Draw the read-only Repositories modal listing `repos.conf` vs pacman sections.
///
/// Inputs:
/// - `frame`: Frame to render into.
/// - `area`: Full-screen area for centering.
/// - `rows`: Merged repository rows.
/// - `selected` / `scroll`: List focus and window start.
/// - `repos_conf_error` / `pacman_warnings`: Optional diagnostics.
/// - `app`: For i18n lookup and storing `repositories_modal_rect` for wheel hit-testing.
///
/// Output:
/// - Renders a scrollable table-style list; updates modal rectangle fields on `app`.
///
/// Details:
/// - Uses a wider box than `render_simple_list_modal` to fit column hints.
#[allow(clippy::too_many_arguments)]
pub fn render_repositories(
    frame: &mut Frame,
    area: Rect,
    rows: &[RepositoryModalRow],
    selected: usize,
    scroll: u16,
    repos_conf_error: Option<&str>,
    pacman_warnings: &[String],
    app: &mut AppState,
) {
    const VIEWPORT: usize = 12;
    let th = theme();
    let box_w = area.width.saturating_sub(6).min(102);
    let box_h = area.height.saturating_sub(6).min(28);
    let box_x = area.x + (area.width.saturating_sub(box_w)) / 2;
    let box_y = area.y + (area.height.saturating_sub(box_h)) / 2;
    let rect = Rect {
        x: box_x,
        y: box_y,
        width: box_w,
        height: box_h,
    };
    app.repositories_modal_rect = Some((rect.x, rect.y, rect.width, rect.height));
    frame.render_widget(Clear, rect);

    let mut lines: Vec<Line<'static>> = Vec::new();
    lines.push(Line::from(Span::styled(
        crate::i18n::t(app, "app.modals.repositories.heading"),
        Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
    )));
    lines.push(Line::from(""));

    if let Some(err) = repos_conf_error {
        lines.push(Line::from(Span::styled(
            format!(
                "{} {err}",
                crate::i18n::t(app, "app.modals.repositories.parse_error")
            ),
            Style::default().fg(th.red),
        )));
        lines.push(Line::from(""));
    }

    if rows.is_empty() && repos_conf_error.is_none() {
        lines.push(Line::from(Span::styled(
            crate::i18n::t(app, "app.modals.repositories.empty"),
            Style::default().fg(th.subtext1),
        )));
        lines.push(Line::from(""));
    }

    let header_style = Style::default()
        .fg(th.subtext0)
        .add_modifier(Modifier::BOLD);
    lines.push(Line::from(vec![
        Span::styled(
            pad_right_display(&crate::i18n::t(app, "app.modals.repositories.col.repo"), 22),
            header_style,
        ),
        Span::styled(
            pad_right_display(
                &crate::i18n::t(app, "app.modals.repositories.col.filter"),
                16,
            ),
            header_style,
        ),
        Span::styled(
            pad_right_display(
                &crate::i18n::t(app, "app.modals.repositories.col.pacman"),
                12,
            ),
            header_style,
        ),
        Span::styled(
            crate::i18n::t(app, "app.modals.repositories.col.key"),
            header_style,
        ),
    ]));
    lines.push(Line::from(""));

    let scroll_u = usize::from(scroll);
    let start = scroll_u.min(rows.len());
    let end = (start + VIEWPORT).min(rows.len());
    for (rel_i, row) in rows[start..end].iter().enumerate() {
        let i_global = start + rel_i;
        let is_sel = selected == i_global;
        let style = if is_sel {
            Style::default()
                .fg(th.crust)
                .bg(th.lavender)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(th.text)
        };
        let pname = pad_right_display(&truncate_display(&row.pacman_section_name, 20), 22);
        let pfilter = pad_right_display(&truncate_display(&row.results_filter_display, 14), 16);
        let pst = pad_right_display(&pacman_status_label(app, row.pacman_status), 12);
        let pk = key_trust_label(app, row.key_trust);
        let hint = row
            .source_hint
            .as_deref()
            .map(|s| format!(" [{}]", truncate_display(s, 20)))
            .unwrap_or_default();
        lines.push(Line::from(vec![
            Span::styled(pname, style),
            Span::styled(pfilter, style),
            Span::styled(pst, style),
            Span::styled(format!("{pk}{hint}"), style),
        ]));
    }

    lines.push(Line::from(""));
    if !pacman_warnings.is_empty() {
        let wtext = pacman_warnings
            .iter()
            .take(3)
            .cloned()
            .collect::<Vec<_>>()
            .join(" | ");
        lines.push(Line::from(Span::styled(
            format!(
                "{} {wtext}",
                crate::i18n::t(app, "app.modals.repositories.warnings_prefix")
            ),
            Style::default().fg(th.yellow),
        )));
        lines.push(Line::from(""));
    }
    lines.push(Line::from(Span::styled(
        crate::i18n::t(app, "app.modals.repositories.footer_hint"),
        Style::default().fg(th.subtext1),
    )));

    let repo_paragraph = Paragraph::new(lines)
        .style(Style::default().fg(th.text).bg(th.mantle))
        .wrap(Wrap { trim: true })
        .block(
            Block::default()
                .title(ratatui::text::Span::styled(
                    format!(" {} ", crate::i18n::t(app, "app.modals.repositories.title")),
                    Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
                ))
                .borders(Borders::ALL)
                .border_type(BorderType::Double)
                .border_style(Style::default().fg(th.mauve))
                .style(Style::default().bg(th.mantle)),
        );
    frame.render_widget(repo_paragraph, rect);
}

/// What: Truncate `s` to a maximum terminal display width, appending an ellipsis when shortened.
///
/// Inputs:
/// - `s`: Source text.
/// - `max_width`: Maximum display columns ([`UnicodeWidthStr::width`]); the result fits within this
///   width when rendered in a typical monospace terminal.
///
/// Output:
/// - Owned string at most `max_width` display columns, or empty when `max_width` is zero.
///
/// Details:
/// - Uses [`UnicodeWidthChar`] per scalar value (same approach as `results/status.rs`); combining
///   sequences are not grapheme-cluster aware.
fn truncate_display(s: &str, max_width: usize) -> String {
    const ELLIPSIS: char = '';
    let ellipsis_w = ELLIPSIS.width().unwrap_or(0);
    let w = s.width();
    if w <= max_width {
        return s.to_string();
    }
    if max_width == 0 {
        return String::new();
    }
    let budget = max_width.saturating_sub(ellipsis_w);
    let mut out = String::new();
    let mut width_so_far = 0usize;
    for ch in s.chars() {
        let ch_w = ch.width().unwrap_or(0);
        if width_so_far.saturating_add(ch_w) > budget {
            break;
        }
        out.push(ch);
        width_so_far = width_so_far.saturating_add(ch_w);
    }
    out.push(ELLIPSIS);
    out
}

/// What: Append ASCII spaces so `s` spans at least `target_width` terminal display columns.
///
/// Inputs:
/// - `s`: Text to pad (callers should truncate first if it may exceed `target_width`).
/// - `target_width`: Minimum display width for the returned string.
///
/// Output:
/// - `s` unchanged when already wide enough; otherwise `s` plus trailing spaces.
///
/// Details:
/// - Matches [`UnicodeWidthStr::width`] so padding aligns with `truncate_display` and Ratatui spans.
fn pad_right_display(s: &str, target_width: usize) -> String {
    let w = s.width();
    if w >= target_width {
        return s.to_string();
    }
    let pad = target_width - w;
    format!("{s}{}", " ".repeat(pad))
}

/// What: Localized label for pacman section presence.
///
/// Inputs:
/// - `app`: For i18n.
/// - `st`: Enumeration from the row model.
///
/// Output:
/// - Short uppercase-ish token for the column.
fn pacman_status_label(app: &AppState, st: RepositoryPacmanStatus) -> String {
    match st {
        RepositoryPacmanStatus::Absent => {
            crate::i18n::t(app, "app.modals.repositories.pacman.absent")
        }
        RepositoryPacmanStatus::Active => {
            crate::i18n::t(app, "app.modals.repositories.pacman.active")
        }
        RepositoryPacmanStatus::Commented => {
            crate::i18n::t(app, "app.modals.repositories.pacman.commented")
        }
    }
}

/// What: Localized label for keyring trust column.
///
/// Inputs:
/// - `app`: For i18n.
/// - `kt`: Trust enum.
///
/// Output:
/// - Compact column text.
fn key_trust_label(app: &AppState, kt: RepositoryKeyTrust) -> String {
    match kt {
        RepositoryKeyTrust::NotApplicable => crate::i18n::t(app, "app.modals.repositories.key.na"),
        RepositoryKeyTrust::Trusted => crate::i18n::t(app, "app.modals.repositories.key.trusted"),
        RepositoryKeyTrust::NotTrusted => {
            crate::i18n::t(app, "app.modals.repositories.key.not_trusted")
        }
        RepositoryKeyTrust::Unknown => crate::i18n::t(app, "app.modals.repositories.key.unknown"),
    }
}

/// What: Compose wrapped body lines for the AUR SSH setup modal.
///
/// Inputs:
/// - `accent`: Step accent color for section headers.
/// - `th`: Active theme palette.
/// - `status_lines`: Setup status lines from logic.
/// - `existing_host_block`: Optional host block preview text.
///
/// Output:
/// - Paragraph lines for the scrollable body (excludes footer shortcut row).
///
/// Details:
/// - Applies per-line styling for failures, warnings, and the public key line.
fn build_ssh_aur_setup_scrollable_lines(
    accent: Color,
    th: &Theme,
    status_lines: &[String],
    existing_host_block: Option<&str>,
) -> Vec<Line<'static>> {
    let mut lines: Vec<Line<'static>> = Vec::new();
    lines.push(Line::from(Span::styled(
        "Status",
        Style::default().fg(accent).add_modifier(Modifier::BOLD),
    )));
    lines.push(Line::from(""));
    for line in status_lines {
        let line_style = if line.starts_with("Failed [") {
            Style::default().fg(th.red).add_modifier(Modifier::BOLD)
        } else if line.starts_with("Warning:") {
            Style::default().fg(th.yellow).add_modifier(Modifier::BOLD)
        } else if line.starts_with("Public key file:") {
            Style::default().fg(th.green)
        } else if line.starts_with("ssh-") {
            Style::default()
                .fg(th.lavender)
                .add_modifier(Modifier::BOLD)
        } else if line.starts_with("Next step:") {
            Style::default().fg(th.sapphire)
        } else {
            Style::default().fg(th.text)
        };
        lines.push(Line::from(Span::styled(format!("- {line}"), line_style)));
    }
    if let Some(block) = existing_host_block {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "Existing Host aur.archlinux.org block:",
            Style::default().fg(th.yellow).add_modifier(Modifier::BOLD),
        )));
        for line in block.lines() {
            lines.push(Line::from(Span::styled(
                format!("  {line}"),
                Style::default().fg(th.subtext1),
            )));
        }
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "AUR login page",
        Style::default().fg(accent).add_modifier(Modifier::BOLD),
    )));
    lines.push(Line::from(Span::styled(
        format!("- {}", crate::logic::ssh_setup::AUR_ACCOUNT_URL),
        Style::default().fg(th.sapphire),
    )));
    lines
}

/// What: Render the guided AUR SSH setup modal.
///
/// Inputs:
/// - `f`: Frame to render into.
/// - `area`: Full screen area used to center the modal.
/// - `step`: Current SSH setup step.
/// - `status_lines`: Current status/instruction lines.
/// - `existing_host_block`: Existing host block shown during overwrite confirmation.
/// - `app`: Mutable app state (stores copy-button hit rect when a public key line is present).
///
/// Output:
/// - Draws the SSH setup modal content.
#[allow(clippy::many_single_char_names)]
pub fn render_ssh_aur_setup(
    f: &mut Frame,
    area: Rect,
    step: crate::state::SshSetupStep,
    status_lines: &[String],
    existing_host_block: Option<&str>,
    app: &mut AppState,
) {
    let th = theme();
    app.ssh_setup_copy_key_rect = None;
    let w = area.width.saturating_sub(8).min(100);
    let h = area.height.saturating_sub(6).min(24);
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let rect = Rect {
        x,
        y,
        width: w,
        height: h,
    };
    f.render_widget(Clear, rect);

    let (title, accent, footer_base) = match step {
        crate::state::SshSetupStep::Intro => (
            "AUR SSH Setup",
            th.mauve,
            "Enter: run setup  |  O: open AUR login page  |  Esc: cancel",
        ),
        crate::state::SshSetupStep::ConfirmOverwrite => (
            "AUR SSH Setup: Confirm Overwrite",
            th.yellow,
            "Y/Enter: overwrite block  |  N/Esc: keep existing config  |  O: open login page",
        ),
        crate::state::SshSetupStep::ApplyKeyOnAur => (
            "AUR SSH Setup: Apply Key on AUR",
            th.sapphire,
            "Y/Enter: I applied key, test connection  |  O: open login page  |  Esc: cancel",
        ),
        crate::state::SshSetupStep::Result => (
            "AUR SSH Setup: Result",
            th.green,
            "Esc: close  |  O: open login page",
        ),
    };

    let show_copy =
        crate::logic::ssh_setup::ssh_public_key_line_from_status_lines(status_lines).is_some();
    let footer = if show_copy {
        format!("{footer_base}  |  C: copy public key")
    } else {
        footer_base.to_string()
    };

    let lines =
        build_ssh_aur_setup_scrollable_lines(accent, &th, status_lines, existing_host_block);

    let block = Block::default()
        .title(Span::styled(
            title,
            Style::default().fg(accent).add_modifier(Modifier::BOLD),
        ))
        .borders(Borders::ALL)
        .border_type(BorderType::Double)
        .border_style(Style::default().fg(accent))
        .style(Style::default().bg(th.mantle));

    let inner = block.inner(rect);
    f.render_widget(Paragraph::new("").block(block), rect);

    let chunks = if show_copy && inner.height > 2 {
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Min(0),
                Constraint::Length(1),
                Constraint::Length(1),
            ])
            .split(inner)
    } else {
        Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(0), Constraint::Length(1)])
            .split(inner)
    };

    let body_area = chunks[0];
    let content_paragraph = Paragraph::new(lines)
        .wrap(Wrap { trim: true })
        .style(Style::default().bg(th.mantle));
    f.render_widget(content_paragraph, body_area);

    if show_copy && inner.height > 2 {
        let copy_area = chunks[1];
        app.ssh_setup_copy_key_rect =
            Some((copy_area.x, copy_area.y, copy_area.width, copy_area.height));
        let copy_label = "  Copy public key  ";
        let copy_paragraph = Paragraph::new(Line::from(Span::styled(
            copy_label,
            Style::default()
                .fg(th.mantle)
                .bg(th.mauve)
                .add_modifier(Modifier::BOLD),
        )))
        .alignment(Alignment::Center)
        .style(Style::default().bg(th.mantle));
        f.render_widget(copy_paragraph, copy_area);
        let footer_area = chunks[2];
        let footer_paragraph = Paragraph::new(Line::from(Span::styled(
            footer,
            Style::default()
                .fg(th.overlay1)
                .add_modifier(Modifier::BOLD),
        )))
        .alignment(Alignment::Center)
        .style(Style::default().bg(th.mantle));
        f.render_widget(footer_paragraph, footer_area);
    } else {
        let footer_area = chunks[1];
        let footer_paragraph = Paragraph::new(Line::from(Span::styled(
            footer,
            Style::default()
                .fg(th.overlay1)
                .add_modifier(Modifier::BOLD),
        )))
        .alignment(Alignment::Center)
        .style(Style::default().bg(th.mantle));
        f.render_widget(footer_paragraph, footer_area);
    }
}

#[allow(clippy::too_many_arguments)]
/// What: Render the scan configuration modal listing security tools to toggle.
///
/// Inputs:
/// - `f`: Frame to render into
/// - `area`: Full screen area used to center the modal
/// - `do_clamav`…`do_sleuth`: Flags indicating which scanners are enabled
/// - `cursor`: Index of the row currently focused
///
/// Output:
/// - Draws the configuration list, highlighting the focused entry and indicating current toggles.
///
/// Details:
/// - Presents each scanner with checkboxes, respecting theme emphasis for the cursor and summarizing
///   available shortcuts at the bottom.
#[allow(clippy::fn_params_excessive_bools)]
pub fn render_scan_config(
    f: &mut Frame,
    area: Rect,
    do_clamav: bool,
    do_trivy: bool,
    do_semgrep: bool,
    do_shellcheck: bool,
    do_virustotal: bool,
    do_custom: bool,
    do_sleuth: bool,
    cursor: usize,
) {
    let th = theme();
    let mut lines: Vec<Line<'static>> = Vec::new();

    let items: [(&str, bool); 7] = [
        ("ClamAV (antivirus)", do_clamav),
        ("Trivy (filesystem)", do_trivy),
        ("Semgrep (static analysis)", do_semgrep),
        ("ShellCheck (PKGBUILD/.install)", do_shellcheck),
        ("VirusTotal (hash lookups)", do_virustotal),
        ("Custom scan for Suspicious patterns", do_custom),
        ("aur-sleuth (LLM audit)", do_sleuth),
    ];

    for (i, (label, checked)) in items.iter().enumerate() {
        let mark = if *checked { "[x]" } else { "[ ]" };
        let mut spans: Vec<Span> = Vec::new();
        spans.push(Span::styled(
            format!("{mark} "),
            Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
        ));
        let style = if i == cursor {
            Style::default()
                .fg(th.text)
                .add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
        } else {
            Style::default().fg(th.subtext1)
        };
        spans.push(Span::styled((*label).to_string(), style));
        lines.push(Line::from(spans));
    }

    lines.push(Line::from(Span::raw("")));
    lines.push(Line::from(Span::styled(
        "Up/Down: select  •  Space: toggle  •  Enter: run  •  Esc: cancel",
        Style::default().fg(th.overlay1),
    )));

    render_simple_list_modal(f, area, "Scan Configuration", lines);
}

/// What: Render the news setup modal for configuring startup news popup.
///
/// Inputs:
/// - `f`: Frame to render into
/// - `area`: Full screen area used to center the modal
/// - `app`: Application state for i18n
/// - `show_arch_news`…`show_pkg_updates`: Flags indicating which news sources are enabled
/// - `max_age_days`: Selected maximum age (7, 30, or 90)
/// - `cursor`: Index of the row currently focused (0-4 for toggles, 5-7 for date buttons)
///
/// Output:
/// - Draws the configuration list, highlighting the focused entry and indicating current toggles.
///
/// Details:
/// - Presents 5 news source toggles with checkboxes, then date selection buttons (7/30/90 days).
/// - Respects theme emphasis for the cursor and summarizes available shortcuts at the bottom.
#[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)]
pub fn render_news_setup(
    f: &mut Frame,
    area: Rect,
    app: &AppState,
    show_arch_news: bool,
    show_advisories: bool,
    show_aur_updates: bool,
    show_aur_comments: bool,
    show_pkg_updates: bool,
    max_age_days: Option<u32>,
    cursor: usize,
) {
    let th = theme();
    let mut lines: Vec<Line<'static>> = Vec::new();

    // News source toggles (cursor 0-4)
    let items: [(&str, bool); 5] = [
        (
            &crate::i18n::t(app, "app.modals.news_setup.arch_news"),
            show_arch_news,
        ),
        (
            &crate::i18n::t(app, "app.modals.news_setup.advisories"),
            show_advisories,
        ),
        (
            &crate::i18n::t(app, "app.modals.news_setup.aur_updates"),
            show_aur_updates,
        ),
        (
            &crate::i18n::t(app, "app.modals.news_setup.aur_comments"),
            show_aur_comments,
        ),
        (
            &crate::i18n::t(app, "app.modals.news_setup.pkg_updates"),
            show_pkg_updates,
        ),
    ];

    for (i, (label, checked)) in items.iter().enumerate() {
        let mark = if *checked { "[x]" } else { "[ ]" };
        let mut spans: Vec<Span> = Vec::new();
        spans.push(Span::styled(
            format!("{mark} "),
            Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
        ));
        let style = if i == cursor {
            Style::default()
                .fg(th.text)
                .add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
        } else {
            Style::default().fg(th.subtext1)
        };
        spans.push(Span::styled((*label).to_string(), style));
        lines.push(Line::from(spans));
    }

    // Date selection row (cursor 5-7)
    lines.push(Line::from(""));
    let date_label = crate::i18n::t(app, "app.modals.news_setup.date_selection");
    lines.push(Line::from(Span::styled(
        format!("{date_label}:"),
        Style::default().fg(th.subtext1),
    )));

    let date_options = [7, 30, 90];
    let mut date_spans: Vec<Span> = Vec::new();
    for (i, &days) in date_options.iter().enumerate() {
        let date_cursor = 5 + i; // cursor 5, 6, 7
        let is_selected = max_age_days == Some(days);
        let is_cursor = cursor == date_cursor;
        let button_text = if is_selected {
            format!("[{days} days]")
        } else {
            format!(" {days} days ")
        };
        let style = if is_cursor {
            Style::default()
                .fg(th.text)
                .add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
        } else if is_selected {
            Style::default().fg(th.mauve).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(th.subtext1)
        };
        date_spans.push(Span::styled(button_text.clone(), style));
        if i < date_options.len() - 1 {
            date_spans.push(Span::raw("  "));
        }
    }
    lines.push(Line::from(date_spans));

    lines.push(Line::from(Span::raw("")));
    let footer_hint = crate::i18n::t(app, "app.modals.news_setup.footer_hint");
    lines.push(Line::from(Span::styled(
        footer_hint,
        Style::default().fg(th.overlay1),
    )));

    render_simple_list_modal(
        f,
        area,
        &crate::i18n::t(app, "app.modals.news_setup.title"),
        lines,
    );
}

/// What: Render the first-startup setup selector checklist modal.
///
/// Inputs:
/// - `f`: Frame to render into
/// - `area`: Full screen area
/// - `app`: Application state for localized strings
/// - `cursor`: Focused selector row
/// - `selected`: Set of selected setup tasks
/// - `active_tool`: Cached privilege tool resolved outside the render path
///
/// Output:
/// - Draws the selector modal with checklist rows and key hints.
pub fn render_startup_setup_selector(
    f: &mut Frame,
    area: Rect,
    app: &AppState,
    cursor: usize,
    selected: &std::collections::HashSet<StartupSetupTask>,
    active_tool: Option<crate::logic::privilege::PrivilegeTool>,
) {
    let th = theme();
    let ssh_setup_ready = app.aur_ssh_help_ready.unwrap_or(false);
    let mut lines: Vec<Line<'static>> = Vec::new();
    lines.push(Line::from(Span::styled(
        crate::i18n::t(app, "app.modals.startup_setup_selector.heading"),
        Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
    )));
    lines.push(Line::from(""));

    let items = [
        (
            StartupSetupTask::ArchNews,
            crate::i18n::t(app, "app.modals.startup_setup_selector.items.arch_news"),
        ),
        (
            StartupSetupTask::SshAurSetup,
            crate::i18n::t(app, "app.modals.startup_setup_selector.items.ssh_aur_setup"),
        ),
        (
            StartupSetupTask::OptionalDepsMissing,
            crate::i18n::t(
                app,
                "app.modals.startup_setup_selector.items.optional_deps_missing",
            ),
        ),
        (
            StartupSetupTask::SudoTimestampSetup,
            crate::i18n::t(
                app,
                "app.modals.startup_setup_selector.items.sudo_timestamp_setup",
            ),
        ),
        (
            StartupSetupTask::DoasPersistSetup,
            crate::i18n::t(
                app,
                "app.modals.startup_setup_selector.items.doas_persist_setup",
            ),
        ),
        (
            StartupSetupTask::AurSleuthSetup,
            crate::i18n::t(
                app,
                "app.modals.startup_setup_selector.items.aur_sleuth_setup",
            ),
        ),
        (
            StartupSetupTask::VirusTotalSetup,
            crate::i18n::t(
                app,
                "app.modals.startup_setup_selector.items.virustotal_setup",
            ),
        ),
    ];

    for (idx, (task, label)) in items.iter().enumerate() {
        let disabled_suffix_key =
            startup_setup_disabled_suffix_key(*task, ssh_setup_ready, active_tool);
        let disabled = disabled_suffix_key.is_some();
        let mark = if selected.contains(task) {
            "[x]"
        } else {
            "[ ]"
        };
        let style = if disabled {
            Style::default().fg(th.overlay1)
        } else if idx == cursor {
            Style::default()
                .fg(th.text)
                .add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
        } else {
            Style::default().fg(th.subtext1)
        };
        lines.push(Line::from(vec![
            Span::styled(
                format!("{mark} "),
                if disabled {
                    Style::default().fg(th.overlay1)
                } else {
                    Style::default().fg(th.mauve).add_modifier(Modifier::BOLD)
                },
            ),
            Span::styled(label.clone(), style),
            disabled_suffix_key.map_or_else(
                || Span::raw(""),
                |suffix_key| {
                    Span::styled(
                        crate::i18n::t(app, suffix_key),
                        Style::default().fg(th.overlay1),
                    )
                },
            ),
        ]));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        crate::i18n::t(app, "app.modals.startup_setup_selector.footer_hint"),
        Style::default().fg(th.overlay1),
    )));

    render_simple_list_modal(
        f,
        area,
        &crate::i18n::t(app, "app.modals.startup_setup_selector.title"),
        lines,
    );
}

/// What: Resolve the disable-state suffix key for a startup setup task.
///
/// Inputs:
/// - `task`: Startup setup task currently being rendered.
/// - `ssh_setup_ready`: Whether SSH-based AUR setup is already configured.
/// - `active_tool`: Resolved privilege tool for the current runtime.
///
/// Output:
/// - Translation key for a disabled-state suffix, or `None` when the task is enabled.
///
/// Details:
/// - Returns `disabled_suffix_already_configured` only when the task is truly completed.
/// - For privilege-specific tasks, returns dedicated suffixes when another tool is active.
const fn startup_setup_disabled_suffix_key(
    task: StartupSetupTask,
    ssh_setup_ready: bool,
    active_tool: Option<crate::logic::privilege::PrivilegeTool>,
) -> Option<&'static str> {
    match task {
        StartupSetupTask::SshAurSetup if ssh_setup_ready => {
            Some("app.modals.startup_setup_selector.disabled_suffix_already_configured")
        }
        StartupSetupTask::SudoTimestampSetup
            if !matches!(
                active_tool,
                Some(crate::logic::privilege::PrivilegeTool::Sudo)
            ) =>
        {
            Some("app.modals.startup_setup_selector.disabled_suffix_requires_sudo")
        }
        StartupSetupTask::DoasPersistSetup
            if !matches!(
                active_tool,
                Some(crate::logic::privilege::PrivilegeTool::Doas)
            ) =>
        {
            Some("app.modals.startup_setup_selector.disabled_suffix_requires_doas")
        }
        _ => None,
    }
}

/// What: Render the `doas` `persist` setup wizard modal.
///
/// Inputs:
/// - `f`: Frame to render into.
/// - `area`: Full screen area used to center the modal.
/// - `app`: Application state for localized strings.
/// - `setup`: Wizard state (phase + cursor + scroll).
///
/// Output:
/// - Draws the select list or instruction pane with scrolling.
#[allow(clippy::many_single_char_names)]
pub fn render_doas_persist_setup(
    f: &mut Frame,
    area: Rect,
    app: &AppState,
    setup: DoasPersistSetupModalState,
) {
    let th = theme();
    let w = area.width.saturating_sub(8).min(102);
    let h = 22_u16.min(area.height.saturating_sub(4));
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let rect = Rect::new(x, y, w, h);
    f.render_widget(Clear, rect);

    let mut lines: Vec<Line<'static>> = Vec::new();
    match setup.phase {
        DoasPersistSetupPhase::Select => {
            lines.push(Line::from(Span::styled(
                crate::i18n::t(app, "app.modals.doas_persist_setup.select_heading"),
                Style::default().fg(th.text),
            )));
            lines.push(Line::from(""));
            let option_keys = [
                "app.modals.doas_persist_setup.option_wheel",
                "app.modals.doas_persist_setup.option_user",
                "app.modals.doas_persist_setup.option_skip",
            ];
            for (idx, key) in option_keys.iter().enumerate() {
                let label = crate::i18n::t(app, key);
                let style = if idx == setup.select_cursor {
                    Style::default()
                        .fg(th.text)
                        .add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
                } else {
                    Style::default().fg(th.subtext1)
                };
                lines.push(Line::from(Span::styled(label, style)));
            }
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                crate::i18n::t(app, "app.modals.doas_persist_setup.select_footer"),
                Style::default().fg(th.overlay1),
            )));
        }
        DoasPersistSetupPhase::Instructions { choice, scroll } => {
            let body =
                crate::logic::doas_persist_setup::doas_persist_instruction_lines(app, choice);
            let start = (scroll as usize).min(body.len());
            let end = (start
                + crate::logic::doas_persist_setup::DOAS_PERSIST_INSTRUCTION_VIEWPORT_LINES)
                .min(body.len());
            lines.extend(body[start..end].iter().cloned());
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                crate::i18n::t(app, "app.modals.doas_persist_setup.instructions_footer"),
                Style::default().fg(th.overlay1),
            )));
        }
    }
    let boxw = Paragraph::new(lines)
        .style(Style::default().fg(th.text).bg(th.mantle))
        .wrap(Wrap { trim: true })
        .block(
            Block::default()
                .title(Span::styled(
                    crate::i18n::t(app, "app.modals.doas_persist_setup.title"),
                    Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
                ))
                .borders(Borders::ALL)
                .border_type(BorderType::Double)
                .border_style(Style::default().fg(th.mauve))
                .style(Style::default().bg(th.mantle)),
        );
    f.render_widget(boxw, rect);
}

/// What: Render the prompt encouraging installation of GNOME Terminal in GNOME environments.
///
/// Inputs:
/// - `f`: Frame to render into
/// - `area`: Full screen area used to center the modal
///
/// Output:
/// - Draws a concise confirmation dialog describing recommended action and key hints.
///
/// Details:
/// - Highlights the heading, explains why the terminal is recommended, and warns about cancelling.
#[allow(clippy::many_single_char_names)]
pub fn render_gnome_terminal_prompt(f: &mut Frame, area: Rect) {
    let th = theme();
    // Centered confirmation dialog for installing GNOME Terminal
    let w = area.width.saturating_sub(10).min(90);
    let h = 9;
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let rect = ratatui::prelude::Rect {
        x,
        y,
        width: w,
        height: h,
    };
    f.render_widget(Clear, rect);

    let lines: Vec<Line<'static>> = vec![
        Line::from(Span::styled(
            "GNOME Terminal or Console recommended",
            Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "GNOME was detected, but no GNOME terminal (gnome-terminal or gnome-console/kgx) is installed.",
            Style::default().fg(th.text),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "Press Enter to install gnome-terminal  •  Esc to cancel",
            Style::default().fg(th.subtext1),
        )),
        Line::from(Span::styled(
            "Cancel may lead to unexpected behavior.",
            Style::default().fg(th.yellow),
        )),
    ];

    let boxw = Paragraph::new(lines)
        .style(Style::default().fg(th.text).bg(th.mantle))
        .wrap(Wrap { trim: true })
        .block(
            Block::default()
                .title(Span::styled(
                    " Install a GNOME Terminal ",
                    Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
                ))
                .borders(Borders::ALL)
                .border_type(BorderType::Double)
                .border_style(Style::default().fg(th.mauve))
                .style(Style::default().bg(th.mantle)),
        );
    f.render_widget(boxw, rect);
}

/// What: Render the `VirusTotal` API setup modal with clickable URL and current input preview.
///
/// Inputs:
/// - `f`: Frame to render into
/// - `app`: Mutable application state (records URL rect for mouse clicks)
/// - `area`: Full screen area used to center the modal
/// - `input`: Current API key buffer contents
///
/// Output:
/// - Draws the setup dialog, updates `app.vt_url_rect`, and shows current text entry.
///
/// Details:
/// - Provides direct link to the API portal, surfaces instructions, and mirrors the buffer so users
///   can verify pasted values.
#[allow(clippy::many_single_char_names)]
pub fn render_virustotal_setup(f: &mut Frame, app: &mut AppState, area: Rect, input: &str) {
    let th = theme();
    // Centered dialog for VirusTotal API key setup with clickable URL and input field
    let w = area.width.saturating_sub(10).min(90);
    let h = 11;
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let rect = ratatui::prelude::Rect {
        x,
        y,
        width: w,
        height: h,
    };
    f.render_widget(Clear, rect);

    // Build content
    let vt_url = "https://www.virustotal.com/gui/my-apikey";
    // Show input buffer (not masked)
    let shown = if input.is_empty() {
        "<empty>".to_string()
    } else {
        input.to_string()
    };
    let lines: Vec<Line<'static>> = vec![
        Line::from(Span::styled(
            "VirusTotal API Setup",
            Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "Open the link to view your API key:",
            Style::default().fg(th.text),
        )),
        Line::from(vec![
            // Surround with spaces to avoid visual concatenation with underlying content
            Span::styled(" ", Style::default().fg(th.text)),
            Span::styled(
                vt_url.to_string(),
                Style::default()
                    .fg(th.lavender)
                    .add_modifier(Modifier::UNDERLINED | Modifier::BOLD),
            ),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            "Enter/paste your API key below and press Enter to save (Esc to cancel):",
            Style::default().fg(th.subtext1),
        )),
        Line::from(Span::styled(
            format!("API key: {shown}"),
            Style::default().fg(th.text),
        )),
        Line::from(""),
        Line::from(Span::styled(
            "Tip: After saving, scans will auto-query VirusTotal by file hash.",
            Style::default().fg(th.overlay1),
        )),
    ];

    let inner_x = rect.x + 1;
    let inner_y = rect.y + 1;
    let url_line_y = inner_y + 3;
    let url_x = inner_x + 1;
    let url_w = u16::try_from(vt_url.len()).unwrap_or(u16::MAX);
    app.vt_url_rect = Some((url_x, url_line_y, url_w, 1));
    let boxw = Paragraph::new(lines)
        .style(Style::default().fg(th.text).bg(th.mantle))
        .wrap(Wrap { trim: true })
        .block(
            Block::default()
                .title(Span::styled(
                    " VirusTotal ",
                    Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
                ))
                .borders(Borders::ALL)
                .border_type(BorderType::Double)
                .border_style(Style::default().fg(th.mauve))
                .style(Style::default().bg(th.mantle)),
        );
    f.render_widget(boxw, rect);
}

/// What: Render the import help modal describing expected file format and keybindings.
///
/// Inputs:
/// - `f`: Frame to render into
/// - `area`: Full screen area used to center the modal
/// - `app`: Application state for i18n translation
///
/// Output:
/// - Draws instructions for import file syntax and highlights confirm/cancel keys.
///
/// Details:
/// - Enumerates formatting rules, provides an example snippet, and keeps styling aligned with other
///   informational modals.
#[allow(clippy::many_single_char_names)]
pub fn render_import_help(f: &mut Frame, area: Rect, app: &crate::state::AppState) {
    let th = theme();
    let w = area.width.saturating_sub(10).min(85);
    let h = 19;
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let rect = ratatui::prelude::Rect {
        x,
        y,
        width: w,
        height: h,
    };
    f.render_widget(Clear, rect);

    let lines: Vec<Line<'static>> = vec![
        Line::from(Span::styled(
            crate::i18n::t(app, "app.modals.import_help.heading"),
            Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
        )),
        Line::from(""),
        Line::from(Span::styled(
            crate::i18n::t(app, "app.modals.import_help.description"),
            Style::default().fg(th.text),
        )),
        Line::from(""),
        Line::from(Span::styled(
            crate::i18n::t(app, "app.modals.import_help.format_label"),
            Style::default()
                .fg(th.overlay1)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(Span::raw(crate::i18n::t(
            app,
            "app.modals.import_help.format_one_per_line",
        ))),
        Line::from(Span::raw(crate::i18n::t(
            app,
            "app.modals.import_help.format_blank_ignored",
        ))),
        Line::from(Span::raw(crate::i18n::t(
            app,
            "app.modals.import_help.format_comments",
        ))),
        Line::from(""),
        Line::from(Span::styled(
            crate::i18n::t(app, "app.modals.import_help.example_label"),
            Style::default()
                .fg(th.overlay1)
                .add_modifier(Modifier::BOLD),
        )),
        Line::from(Span::raw("  firefox")),
        Line::from(Span::raw(crate::i18n::t(
            app,
            "app.modals.import_help.example_comment",
        ))),
        Line::from(Span::raw("  vim")),
        Line::from(Span::raw("  paru")),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                "[Enter]",
                Style::default().fg(th.text).add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                crate::i18n::t(app, "app.modals.import_help.hint_confirm"),
                Style::default().fg(th.overlay1),
            ),
            Span::raw(""),
            Span::styled(
                "[Esc]",
                Style::default().fg(th.text).add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                crate::i18n::t(app, "app.modals.import_help.hint_cancel"),
                Style::default().fg(th.overlay1),
            ),
        ]),
    ];

    let boxw = Paragraph::new(lines)
        .style(Style::default().fg(th.text).bg(th.mantle))
        .wrap(Wrap { trim: true })
        .block(
            Block::default()
                .title(Span::styled(
                    crate::i18n::t(app, "app.modals.import_help.title"),
                    Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
                ))
                .borders(Borders::ALL)
                .border_type(BorderType::Double)
                .border_style(Style::default().fg(th.mauve))
                .style(Style::default().bg(th.mantle)),
        );
    f.render_widget(boxw, rect);
}

/// What: Render the sudo `timestamp_timeout` setup wizard modal.
///
/// Inputs:
/// - `f`: Frame to render into.
/// - `area`: Full screen area used to center the modal.
/// - `app`: Application state for localized strings.
/// - `setup`: Wizard state (phase + cursor + scroll).
///
/// Output:
/// - Draws the select list or instruction pane with scrolling.
///
/// Details:
/// - Complements key handling in [`crate::events::modals::sudo_timestamp_setup`].
#[allow(clippy::too_many_lines, clippy::many_single_char_names)]
pub fn render_sudo_timestamp_setup(
    f: &mut Frame,
    area: Rect,
    app: &AppState,
    setup: SudoTimestampSetupModalState,
) {
    let th = theme();
    let w = area.width.saturating_sub(8).min(102);
    let h = 22_u16.min(area.height.saturating_sub(4));
    let x = area.x + (area.width.saturating_sub(w)) / 2;
    let y = area.y + (area.height.saturating_sub(h)) / 2;
    let rect = Rect::new(x, y, w, h);
    f.render_widget(Clear, rect);

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

    match setup.phase {
        SudoTimestampSetupPhase::Select => {
            lines.push(Line::from(Span::styled(
                crate::i18n::t(app, "app.modals.sudo_timestamp_setup.select_heading"),
                Style::default().fg(th.text),
            )));
            lines.push(Line::from(""));
            let option_keys = [
                "app.modals.sudo_timestamp_setup.option_10m",
                "app.modals.sudo_timestamp_setup.option_30m",
                "app.modals.sudo_timestamp_setup.option_infinity",
                "app.modals.sudo_timestamp_setup.option_skip",
            ];
            for (idx, key) in option_keys.iter().enumerate() {
                let label = crate::i18n::t(app, key);
                let style = if idx == setup.select_cursor {
                    Style::default()
                        .fg(th.text)
                        .add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
                } else {
                    Style::default().fg(th.subtext1)
                };
                lines.push(Line::from(Span::styled(label, style)));
            }
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                crate::i18n::t(app, "app.modals.sudo_timestamp_setup.select_footer"),
                Style::default().fg(th.overlay1),
            )));
        }
        SudoTimestampSetupPhase::Instructions { choice, scroll } => {
            let body =
                crate::logic::sudo_timestamp_setup::sudo_timestamp_instruction_lines(app, choice);
            let start = (scroll as usize).min(body.len());
            let end = (start
                + crate::logic::sudo_timestamp_setup::SUDO_TIMESTAMP_INSTRUCTION_VIEWPORT_LINES)
                .min(body.len());
            lines.extend(body[start..end].iter().cloned());
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                crate::i18n::t(app, "app.modals.sudo_timestamp_setup.instructions_footer"),
                Style::default().fg(th.overlay1),
            )));
        }
    }

    let boxw = Paragraph::new(lines)
        .style(Style::default().fg(th.text).bg(th.mantle))
        .wrap(Wrap { trim: true })
        .block(
            Block::default()
                .title(Span::styled(
                    crate::i18n::t(app, "app.modals.sudo_timestamp_setup.title"),
                    Style::default().fg(th.mauve).add_modifier(Modifier::BOLD),
                ))
                .borders(Borders::ALL)
                .border_type(BorderType::Double)
                .border_style(Style::default().fg(th.mauve))
                .style(Style::default().bg(th.mantle)),
        );
    f.render_widget(boxw, rect);
}

/// What: Render a simple loading indicator modal.
///
/// Inputs:
/// - `f`: Frame to render into
/// - `area`: Full screen area used to center the modal
/// - `message`: Loading message to display
///
/// Output:
/// - Draws a centered loading modal with the given message.
///
/// Details:
/// - Shows a simple centered box with a loading message and spinner indicator.
pub fn render_loading(f: &mut Frame, area: Rect, message: &str) {
    let th = theme();

    // Small centered modal
    let width = 40_u16.min(area.width.saturating_sub(4));
    let height = 5_u16.min(area.height.saturating_sub(4));
    let x = area.x + (area.width.saturating_sub(width)) / 2;
    let y = area.y + (area.height.saturating_sub(height)) / 2;
    let rect = Rect::new(x, y, width, height);

    f.render_widget(Clear, rect);

    let lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            format!("{message}"),
            Style::default().fg(th.text),
        )),
    ];

    let boxw = Paragraph::new(lines)
        .style(Style::default().fg(th.text).bg(th.mantle))
        .alignment(ratatui::layout::Alignment::Center)
        .block(
            Block::default()
                .title(Span::styled(
                    " Loading ",
                    Style::default().fg(th.yellow).add_modifier(Modifier::BOLD),
                ))
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(Style::default().fg(th.yellow))
                .style(Style::default().bg(th.mantle)),
        );
    f.render_widget(boxw, rect);
}

#[cfg(test)]
mod truncate_and_pad_tests {
    use unicode_width::UnicodeWidthStr;

    use super::{pad_right_display, startup_setup_disabled_suffix_key, truncate_display};
    use crate::logic::privilege::PrivilegeTool;
    use crate::state::modal::StartupSetupTask;

    #[test]
    fn truncate_display_ascii_short_unchanged() {
        assert_eq!(truncate_display("core", 20), "core");
    }

    #[test]
    fn truncate_display_ascii_long_uses_ellipsis_within_width() {
        let s = truncate_display("very-long-repo-section-name-here", 20);
        assert!(s.ends_with(''));
        assert!(s.width() <= 20);
    }

    #[test]
    fn truncate_display_cjk_respects_display_columns() {
        // Each CJK character is typically width 2; 9 chars => 18 columns, fits in 20.
        let narrow = "一二三四五六七八九";
        assert_eq!(truncate_display(narrow, 20), narrow);
        // 11 chars => 22 columns; truncate to <= 20 with ellipsis (width 1) => 9 display cols body.
        let wide = "一二三四五六七八九十甲";
        let t = truncate_display(wide, 20);
        assert!(t.ends_with(''));
        assert!(t.width() <= 20);
    }

    #[test]
    fn pad_right_display_adds_spaces_by_display_width() {
        let s = pad_right_display("ab", 6);
        assert_eq!(s.width(), 6);
        assert_eq!(s, "ab    ");
    }

    #[test]
    fn pad_right_display_wide_prefix() {
        let s = pad_right_display("", 6);
        assert_eq!(s.width(), 6);
        assert_eq!(s, "");
    }

    #[test]
    fn startup_setup_doas_disabled_suffix_requires_doas_when_tool_missing() {
        let suffix =
            startup_setup_disabled_suffix_key(StartupSetupTask::DoasPersistSetup, false, None);
        assert_eq!(
            suffix,
            Some("app.modals.startup_setup_selector.disabled_suffix_requires_doas")
        );
    }

    #[test]
    fn startup_setup_doas_disabled_suffix_none_when_doas_active() {
        let suffix = startup_setup_disabled_suffix_key(
            StartupSetupTask::DoasPersistSetup,
            false,
            Some(PrivilegeTool::Doas),
        );
        assert_eq!(suffix, None);
    }

    #[test]
    fn startup_setup_ssh_suffix_only_marks_already_configured() {
        let suffix = startup_setup_disabled_suffix_key(StartupSetupTask::SshAurSetup, true, None);
        assert_eq!(
            suffix,
            Some("app.modals.startup_setup_selector.disabled_suffix_already_configured")
        );
    }
}