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
use ratatui::{
    prelude::Rect,
    style::{Modifier, Style},
    text::{Line, Span},
};

use crate::i18n;
use crate::state::modal::{FileChangeType, PackageFileInfo};
use crate::state::{AppState, PackageItem};
use crate::theme::theme;
use crate::ui::helpers::ChangeLogger;
use crate::ui::modals::preflight::helpers::format_count_with_indicator;
use std::sync::{Mutex, OnceLock};

/// Type alias for file display item tuple.
///
/// Tuple structure:
/// - Field 0 (bool): Whether the package entry is expanded to show files.
/// - Field 1 (String): Package name.
/// - Field 2 (Option<(`FileChangeType`, String, bool, bool, bool)>): Optional file information.
///   When Some, contains: (`change_type`, `file_path`, `is_new`, `is_changed`, `is_removed`).
type FileDisplayItem = (
    bool,
    String,
    Option<(FileChangeType, String, bool, bool, bool)>,
);

/// Summary of file changes for a single package.
#[derive(Clone, PartialEq, Eq)]
struct FilePackageSummary {
    /// Package name.
    name: String,
    /// Total number of file changes.
    total: usize,
    /// Number of new files.
    new_count: usize,
    /// Number of changed files.
    changed_count: usize,
    /// Number of removed files.
    removed_count: usize,
    /// Number of configuration files.
    config_count: usize,
    /// Total number of file entries.
    file_entries: usize,
}

/// State tracking for files tab logging.
#[derive(Clone, PartialEq, Eq)]
struct FilesLogState {
    /// Number of package items.
    items_len: usize,
    /// Number of file info entries.
    file_info_len: usize,
    /// Currently selected file index.
    file_selected: usize,
    /// Number of expanded tree nodes.
    expanded_len: usize,
    /// Whether preflight file resolution is in progress.
    preflight_resolving: bool,
    /// Whether global file resolution is in progress.
    global_resolving: bool,
    /// Whether an error occurred.
    has_error: bool,
    /// Package summaries for file changes.
    package_summaries: Vec<FilePackageSummary>,
}

/// What: Emit a debug log when the files-tab render snapshot changes.
///
/// Inputs:
/// - `state`: Current files-tab log snapshot used for change detection.
///
/// Output: None.
///
/// Details: Uses a `ChangeLogger` so identical consecutive frames are not logged.
fn log_files_state(state: &FilesLogState) {
    static LOGGER: OnceLock<Mutex<ChangeLogger<FilesLogState>>> = OnceLock::new();
    let mut logger = LOGGER
        .get_or_init(|| Mutex::new(ChangeLogger::new()))
        .lock()
        .expect("Files log state mutex poisoned");

    if logger.should_log(state) {
        let package_text = if state.package_summaries.is_empty() {
            "no file details".to_string()
        } else {
            state
                .package_summaries
                .iter()
                .map(|p| {
                    format!(
                        "{}: total={}, new={}, changed={}, removed={}, config={}, files={}",
                        p.name,
                        p.total,
                        p.new_count,
                        p.changed_count,
                        p.removed_count,
                        p.config_count,
                        p.file_entries
                    )
                })
                .collect::<Vec<_>>()
                .join(" | ")
        };

        tracing::debug!(
            "[UI] render_files_tab: items={}, file_info={}, file_selected={}, expanded={}, resolving={}/{}, error={}, packages=[{}]",
            state.items_len,
            state.file_info_len,
            state.file_selected,
            state.expanded_len,
            state.preflight_resolving,
            state.global_resolving,
            state.has_error,
            package_text
        );
    }
}

/// What: Render loading/resolving state with package headers.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `items`: Packages under review.
/// - `message_key`: i18n key for the message to display.
/// - `message_color`: Color for the message text.
///
/// Output:
/// - Returns a vector of lines to render.
fn render_loading_state(
    app: &AppState,
    items: &[PackageItem],
    message_key: &str,
    message_color: ratatui::style::Color,
) -> Vec<Line<'static>> {
    let th = theme();
    let mut lines = Vec::new();

    for item in items {
        let mut spans = Vec::new();
        spans.push(Span::styled(
            format!("â–¶ {} ", item.name),
            Style::default()
                .fg(th.overlay1)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled("(0 files)", Style::default().fg(th.subtext1)));
        lines.push(Line::from(spans));
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        i18n::t(app, message_key),
        Style::default().fg(message_color),
    )));

    lines
}

/// What: Render error state with retry hint.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `err_msg`: Error message to display.
///
/// Output:
/// - Returns a vector of lines to render.
fn render_error_state(app: &AppState, err_msg: &str) -> Vec<Line<'static>> {
    let th = theme();
    vec![
        Line::from(Span::styled(
            i18n::t_fmt1(app, "app.modals.preflight.files.error", err_msg),
            Style::default().fg(th.red),
        )),
        Line::from(""),
        Line::from(Span::styled(
            i18n::t(app, "app.modals.preflight.files.retry_hint"),
            Style::default().fg(th.subtext1),
        )),
    ]
}

/// What: Build flat list of display items from file info.
///
/// Inputs:
/// - `items`: All packages under review.
/// - `file_info`: File information.
/// - `file_tree_expanded`: Set of expanded package names.
///
/// Output:
/// - Returns a vector of display items (headers and files).
///
/// Details:
/// - Always shows ALL packages from items, even if they have no files.
/// - This ensures packages that failed to resolve files (e.g., due to conflicts) are still visible.
fn build_display_items(
    items: &[PackageItem],
    file_info: &[PackageFileInfo],
    file_tree_expanded: &std::collections::HashSet<String>,
) -> Vec<FileDisplayItem> {
    use std::collections::HashMap;
    // Create a map for quick lookup of file info by package name
    let file_info_map: HashMap<String, &PackageFileInfo> = file_info
        .iter()
        .map(|info| (info.name.clone(), info))
        .collect();

    let mut display_items = Vec::new();
    // Always show ALL packages from items, even if they have no file info
    for item in items {
        let pkg_name = &item.name;
        let is_expanded = file_tree_expanded.contains(pkg_name);
        display_items.push((true, pkg_name.clone(), None)); // Package header

        if is_expanded {
            // Show files if available
            if let Some(pkg_info) = file_info_map.get(pkg_name) {
                for file in &pkg_info.files {
                    display_items.push((
                        false,
                        String::new(),
                        Some((
                            file.change_type.clone(),
                            file.path.clone(),
                            file.is_config,
                            file.predicted_pacnew,
                            file.predicted_pacsave,
                        )),
                    ));
                }
            }
        }
    }
    display_items
}

/// What: Render sync timestamp line.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `sync_info`: Optional sync info tuple (`age_days`, `date_str`, `color_category`).
///
/// Output:
/// - Returns optional line and number of lines added (0 or 2).
fn render_sync_timestamp(
    app: &AppState,
    sync_info: Option<&(u64, String, u8)>,
) -> (Option<Line<'static>>, usize) {
    let th = theme();
    if let Some((_age_days, date_str, color_category)) = sync_info {
        let (sync_color, sync_text) = match color_category {
            0 => (
                th.green,
                i18n::t_fmt1(app, "app.modals.preflight.files.files_updated_on", date_str),
            ),
            1 => (
                th.yellow,
                i18n::t_fmt1(app, "app.modals.preflight.files.files_updated_on", date_str),
            ),
            _ => (
                th.red,
                i18n::t_fmt1(app, "app.modals.preflight.files.files_updated_on", date_str),
            ),
        };
        (
            Some(Line::from(Span::styled(
                sync_text,
                Style::default().fg(sync_color),
            ))),
            2,
        )
    } else {
        (None, 0)
    }
}

/// What: Render empty state when no files are found.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `items`: Packages under review.
/// - `file_info`: File information.
/// - `is_stale`: Whether file database is stale.
/// - `sync_info`: Optional sync info.
///
/// Output:
/// - Returns a vector of lines to render.
fn render_empty_state(
    app: &AppState,
    items: &[PackageItem],
    file_info: &[PackageFileInfo],
    is_stale: Option<&bool>,
    sync_info: Option<&(u64, String, u8)>,
) -> Vec<Line<'static>> {
    let th = theme();
    let mut lines = Vec::new();

    let has_aur_packages = items
        .iter()
        .any(|p| matches!(p.source, crate::state::Source::Aur));
    let has_official_packages = items
        .iter()
        .any(|p| matches!(p.source, crate::state::Source::Official { .. }));

    let mut unresolved_packages = Vec::new();
    for pkg_info in file_info {
        if pkg_info.files.is_empty() {
            unresolved_packages.push(pkg_info.name.clone());
        }
    }

    if file_info.is_empty() {
        lines.push(Line::from(Span::styled(
            i18n::t(app, "app.modals.preflight.files.file_resolution_progress"),
            Style::default().fg(th.subtext1),
        )));
    } else if unresolved_packages.is_empty() {
        lines.push(Line::from(Span::styled(
            i18n::t(app, "app.modals.preflight.files.no_file_changes_display"),
            Style::default().fg(th.subtext1),
        )));
    } else {
        lines.push(Line::from(Span::styled(
            i18n::t_fmt1(
                app,
                "app.modals.preflight.files.no_file_changes",
                unresolved_packages.len(),
            ),
            Style::default().fg(th.subtext1),
        )));
        lines.push(Line::from(""));

        if has_official_packages {
            lines.push(Line::from(Span::styled(
                i18n::t(app, "app.modals.preflight.files.file_db_sync_note"),
                Style::default().fg(th.subtext0),
            )));
            lines.push(Line::from(Span::styled(
                i18n::t(app, "app.modals.preflight.files.sync_file_db_hint"),
                Style::default().fg(th.subtext0),
            )));
        }
        if has_aur_packages {
            lines.push(Line::from(Span::styled(
                i18n::t(app, "app.modals.preflight.files.aur_file_note"),
                Style::default().fg(th.subtext0),
            )));
        }
    }

    if matches!(is_stale, Some(true)) {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            i18n::t(app, "app.modals.preflight.files.file_db_stale"),
            Style::default().fg(th.yellow),
        )));
        lines.push(Line::from(Span::styled(
            i18n::t(app, "app.modals.preflight.files.sync_file_db_root"),
            Style::default().fg(th.subtext0),
        )));
    }

    let (sync_line, _) = render_sync_timestamp(app, sync_info);
    if let Some(line) = sync_line {
        lines.push(Line::from(""));
        lines.push(line);
    }

    lines
}

/// What: Render package header line.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `pkg_info`: Package file information.
/// - `pkg_name`: Package name.
/// - `is_expanded`: Whether package is expanded.
/// - `is_selected`: Whether package is selected.
///
/// Output:
/// - Returns a line to render.
fn render_package_header(
    app: &AppState,
    pkg_info: &PackageFileInfo,
    pkg_name: &str,
    is_expanded: bool,
    is_selected: bool,
) -> Line<'static> {
    let th = theme();
    let arrow_symbol = if is_expanded { "â–¼" } else { "â–¶" };
    let header_style = if is_selected {
        Style::default()
            .fg(th.crust)
            .bg(th.lavender)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
            .fg(th.overlay1)
            .add_modifier(Modifier::BOLD)
    };

    let total_count = pkg_info.total_count;
    let mut spans = vec![
        Span::styled(format!("{arrow_symbol} {pkg_name} "), header_style),
        Span::styled(
            format!("({total_count} files"),
            Style::default().fg(th.subtext1),
        ),
    ];

    if pkg_info.new_count > 0 {
        spans.push(Span::styled(
            format!(
                ", {}",
                i18n::t_fmt1(app, "app.modals.preflight.files.new", pkg_info.new_count)
            ),
            Style::default().fg(th.green),
        ));
    }
    if pkg_info.changed_count > 0 {
        let changed_count = pkg_info.changed_count;
        spans.push(Span::styled(
            format!(", {changed_count} changed"),
            Style::default().fg(th.yellow),
        ));
    }
    if pkg_info.removed_count > 0 {
        let removed_count = pkg_info.removed_count;
        spans.push(Span::styled(
            format!(", {removed_count} removed"),
            Style::default().fg(th.red),
        ));
    }
    if pkg_info.config_count > 0 {
        let config_count = pkg_info.config_count;
        spans.push(Span::styled(
            format!(", {config_count} config"),
            Style::default().fg(th.mauve),
        ));
    }
    if pkg_info.pacnew_candidates > 0 {
        let pacnew_candidates = pkg_info.pacnew_candidates;
        spans.push(Span::styled(
            format!(", {pacnew_candidates} pacnew"),
            Style::default().fg(th.yellow),
        ));
    }
    if pkg_info.pacsave_candidates > 0 {
        let pacsave_candidates = pkg_info.pacsave_candidates;
        spans.push(Span::styled(
            format!(", {pacsave_candidates} pacsave"),
            Style::default().fg(th.red),
        ));
    }
    spans.push(Span::styled(")", Style::default().fg(th.subtext1)));

    Line::from(spans)
}

/// What: Aggregated file totals across all packages.
///
/// Details:
/// - Contains sums of all file counts from package file information.
struct FileTotals {
    /// Total number of files.
    files: usize,
    /// Number of new files.
    new: usize,
    /// Number of changed files.
    changed: usize,
    /// Number of removed files.
    removed: usize,
    /// Number of config files.
    config: usize,
    /// Number of .pacnew files.
    pacnew: usize,
    /// Number of .pacsave files.
    pacsave: usize,
}

/// What: Calculate file totals from package file information in a single pass.
///
/// Inputs:
/// - `file_info`: File information for all packages.
///
/// Output:
/// - Returns aggregated file totals.
///
/// Details:
/// - Performs a single iteration over `file_info` to calculate all totals.
fn calculate_file_totals(file_info: &[PackageFileInfo]) -> FileTotals {
    file_info.iter().fold(
        FileTotals {
            files: 0,
            new: 0,
            changed: 0,
            removed: 0,
            config: 0,
            pacnew: 0,
            pacsave: 0,
        },
        |acc, p| FileTotals {
            files: acc.files + p.total_count,
            new: acc.new + p.new_count,
            changed: acc.changed + p.changed_count,
            removed: acc.removed + p.removed_count,
            config: acc.config + p.config_count,
            pacnew: acc.pacnew + p.pacnew_candidates,
            pacsave: acc.pacsave + p.pacsave_candidates,
        },
    )
}

/// What: Build summary parts for file list header.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `totals`: Aggregated file totals.
/// - `items_len`: Number of packages.
/// - `has_incomplete_data`: Whether data is incomplete.
///
/// Output:
/// - Returns vector of formatted summary strings.
///
/// Details:
/// - Formats counts with indicators when data is incomplete.
fn build_summary_parts(
    app: &AppState,
    totals: &FileTotals,
    items_len: usize,
    has_incomplete_data: bool,
) -> Vec<String> {
    let total_files_text =
        format_count_with_indicator(totals.files, items_len * 10, has_incomplete_data);
    let mut summary_parts = vec![i18n::t_fmt1(
        app,
        "app.modals.preflight.files.total",
        total_files_text,
    )];

    if totals.new > 0 {
        let count_text = format_count_with_indicator(totals.new, totals.files, has_incomplete_data);
        summary_parts.push(i18n::t_fmt1(
            app,
            "app.modals.preflight.files.new",
            count_text,
        ));
    }
    if totals.changed > 0 {
        let count_text =
            format_count_with_indicator(totals.changed, totals.files, has_incomplete_data);
        summary_parts.push(i18n::t_fmt1(
            app,
            "app.modals.preflight.files.changed",
            count_text,
        ));
    }
    if totals.removed > 0 {
        let count_text =
            format_count_with_indicator(totals.removed, totals.files, has_incomplete_data);
        summary_parts.push(i18n::t_fmt1(
            app,
            "app.modals.preflight.files.removed",
            count_text,
        ));
    }
    if totals.config > 0 {
        let count_text =
            format_count_with_indicator(totals.config, totals.files, has_incomplete_data);
        summary_parts.push(i18n::t_fmt1(
            app,
            "app.modals.preflight.files.config",
            count_text,
        ));
    }
    if totals.pacnew > 0 {
        summary_parts.push(i18n::t_fmt1(
            app,
            "app.modals.preflight.files.pacnew",
            totals.pacnew,
        ));
    }
    if totals.pacsave > 0 {
        summary_parts.push(i18n::t_fmt1(
            app,
            "app.modals.preflight.files.pacsave",
            totals.pacsave,
        ));
    }

    summary_parts
}

/// What: Calculate viewport range for scrolling file list.
///
/// Inputs:
/// - `total_items`: Total number of display items.
/// - `available_height`: Available height in lines.
/// - `file_selected`: Currently selected file index (mutable, will be clamped).
///
/// Output:
/// - Returns tuple of (`start_idx`, `end_idx`) for visible range.
///
/// Details:
/// - Centers selected item when possible.
/// - Ensures selected item is always visible.
/// - Clamps `file_selected` to valid range.
fn calculate_viewport(
    total_items: usize,
    available_height: usize,
    file_selected: &mut usize,
) -> (usize, usize) {
    let file_selected_clamped = (*file_selected).min(total_items.saturating_sub(1));
    if *file_selected != file_selected_clamped {
        *file_selected = file_selected_clamped;
    }

    if total_items <= available_height {
        // All items fit on screen
        (0, total_items)
    } else {
        // Try to center the selected item
        let start = file_selected_clamped
            .saturating_sub(available_height / 2)
            .min(total_items.saturating_sub(available_height));
        let end = (start + available_height).min(total_items);

        // Safety check: ensure selected item is always visible
        if file_selected_clamped < start {
            // Selected is before start - adjust to include it
            (
                file_selected_clamped,
                (file_selected_clamped + available_height).min(total_items),
            )
        } else if file_selected_clamped >= end {
            // Selected is at or beyond end - position it at bottom
            let new_end = (file_selected_clamped + 1).min(total_items);
            (new_end.saturating_sub(available_height).max(0), new_end)
        } else {
            (start, end)
        }
    }
}

/// What: Render header for package with no file info.
///
/// Inputs:
/// - `pkg_name`: Package name.
/// - `is_expanded`: Whether package is expanded.
/// - `is_selected`: Whether package is selected.
///
/// Output:
/// - Returns a line to render.
///
/// Details:
/// - Used when package file info is not yet available.
fn render_missing_package_header(
    pkg_name: &str,
    is_expanded: bool,
    is_selected: bool,
) -> Line<'static> {
    let th = theme();
    let arrow_symbol = if is_expanded { "â–¼" } else { "â–¶" };
    let header_style = if is_selected {
        Style::default()
            .fg(th.crust)
            .bg(th.lavender)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
            .fg(th.overlay1)
            .add_modifier(Modifier::BOLD)
    };
    let spans = vec![
        Span::styled(format!("{arrow_symbol} {pkg_name} "), header_style),
        Span::styled("(0 files)", Style::default().fg(th.subtext1)),
    ];
    Line::from(spans)
}

/// What: Render display items within viewport range.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `display_items`: Flat list of display items.
/// - `file_info`: File information for packages.
/// - `file_tree_expanded`: Set of expanded package names.
/// - `file_selected`: Currently selected file index.
/// - `start_idx`: Start index of viewport.
/// - `end_idx`: End index of viewport.
///
/// Output:
/// - Returns a vector of lines to render.
///
/// Details:
/// - Renders only items within the viewport range.
/// - Handles both package headers and file entries.
fn render_display_items(
    app: &AppState,
    display_items: &[FileDisplayItem],
    file_info: &[PackageFileInfo],
    file_tree_expanded: &std::collections::HashSet<String>,
    file_selected: usize,
    start_idx: usize,
    end_idx: usize,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();

    for (display_idx, (is_header, pkg_name, file_opt)) in display_items
        .iter()
        .enumerate()
        .skip(start_idx)
        .take(end_idx - start_idx)
    {
        let is_selected = display_idx == file_selected;
        if *is_header {
            let is_expanded = file_tree_expanded.contains(pkg_name);
            // Handle packages that may not have file info yet
            if let Some(pkg_info) = file_info.iter().find(|p| p.name == *pkg_name) {
                lines.push(render_package_header(
                    app,
                    pkg_info,
                    pkg_name,
                    is_expanded,
                    is_selected,
                ));
            } else {
                lines.push(render_missing_package_header(
                    pkg_name,
                    is_expanded,
                    is_selected,
                ));
            }
        } else if let Some((change_type, path, is_config, predicted_pacnew, predicted_pacsave)) =
            file_opt
        {
            lines.push(render_file_entry(
                app,
                change_type,
                path,
                *is_config,
                *predicted_pacnew,
                *predicted_pacsave,
                is_selected,
            ));
        }
    }

    lines
}

/// What: Context for rendering file list.
///
/// Details:
/// - Groups related parameters to reduce function signature complexity.
struct FileListContext<'a> {
    /// Package file information.
    file_info: &'a [PackageFileInfo],
    /// Package items.
    items: &'a [PackageItem],
    /// Display items for rendering.
    display_items: &'a [FileDisplayItem],
    /// Set of expanded package names in the tree view.
    file_tree_expanded: &'a std::collections::HashSet<String>,
    /// Optional sync information tuple: (`download_size`, `package_name`, `risk_level`).
    sync_info: &'a Option<(u64, String, u8)>,
}

/// What: Render file entry line.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `change_type`: Type of file change.
/// - `path`: File path.
/// - `is_config`: Whether file is a config file.
/// - `predicted_pacnew`: Whether pacnew is predicted.
/// - `predicted_pacsave`: Whether pacsave is predicted.
/// - `is_selected`: Whether file is selected.
///
/// Output:
/// - Returns a line to render.
#[allow(clippy::fn_params_excessive_bools)]
fn render_file_entry(
    app: &AppState,
    change_type: &FileChangeType,
    path: &str,
    is_config: bool,
    predicted_pacnew: bool,
    predicted_pacsave: bool,
    is_selected: bool,
) -> Line<'static> {
    let th = theme();
    let (icon, color) = match change_type {
        FileChangeType::New => ("+", th.green),
        FileChangeType::Changed => ("~", th.yellow),
        FileChangeType::Removed => ("-", th.red),
    };

    let highlight_bg = if is_selected { Some(th.lavender) } else { None };
    let icon_style = highlight_bg.map_or_else(
        || Style::default().fg(color),
        |bg| Style::default().fg(color).bg(bg),
    );
    let mut spans = vec![Span::styled(format!("  {icon} "), icon_style)];

    if is_config {
        let cfg_style = highlight_bg.map_or_else(
            || Style::default().fg(th.mauve),
            |bg| Style::default().fg(th.mauve).bg(bg),
        );
        spans.push(Span::styled("âš™ ", cfg_style));
    }

    if predicted_pacnew {
        let pacnew_style = highlight_bg.map_or_else(
            || Style::default().fg(th.yellow),
            |bg| Style::default().fg(th.yellow).bg(bg),
        );
        spans.push(Span::styled(
            i18n::t(app, "app.modals.preflight.files.pacnew_label"),
            pacnew_style,
        ));
    }
    if predicted_pacsave {
        let pacsave_style = highlight_bg.map_or_else(
            || Style::default().fg(th.red),
            |bg| Style::default().fg(th.red).bg(bg),
        );
        spans.push(Span::styled(
            i18n::t(app, "app.modals.preflight.files.pacsave_label"),
            pacsave_style,
        ));
    }

    let path_style = highlight_bg.map_or_else(
        || Style::default().fg(th.text),
        |bg| {
            Style::default()
                .fg(th.crust)
                .bg(bg)
                .add_modifier(Modifier::BOLD)
        },
    );

    spans.push(Span::styled(path.to_string(), path_style));

    Line::from(spans)
}

/// What: Render file list with summary and scrolling.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `ctx`: File list context containing related parameters.
/// - `file_selected`: Currently selected file index (mutable).
/// - `content_rect`: Content area rectangle.
///
/// Output:
/// - Returns a vector of lines to render.
fn render_file_list(
    app: &AppState,
    ctx: &FileListContext,
    file_selected: &mut usize,
    content_rect: Rect,
) -> Vec<Line<'static>> {
    let th = theme();
    let mut lines = Vec::new();

    // Option 1: Single-pass aggregation
    let totals = calculate_file_totals(ctx.file_info);

    // Option 6: Simplify incomplete data check
    let has_incomplete_data = ctx.file_info.len() < ctx.items.len();

    // Option 2: Extract summary building
    let summary_parts = build_summary_parts(app, &totals, ctx.items.len(), has_incomplete_data);

    lines.push(Line::from(Span::styled(
        i18n::t_fmt1(
            app,
            "app.modals.preflight.files.files_label",
            summary_parts.join(", "),
        ),
        Style::default()
            .fg(th.overlay1)
            .add_modifier(Modifier::BOLD),
    )));
    lines.push(Line::from(""));

    let (sync_line, sync_timestamp_lines) = render_sync_timestamp(app, ctx.sync_info.as_ref());
    if let Some(line) = sync_line {
        lines.push(line);
        lines.push(Line::from(""));
    }

    let header_lines = 4 + sync_timestamp_lines;
    let available_height = (content_rect.height.saturating_sub(1) as usize)
        .saturating_sub(header_lines)
        .max(1);

    let total_items = ctx.display_items.len();

    // Option 3: Extract viewport calculation
    let (start_idx, end_idx) = calculate_viewport(total_items, available_height, file_selected);

    // Option 4: Extract rendering loop
    let mut item_lines = render_display_items(
        app,
        ctx.display_items,
        ctx.file_info,
        ctx.file_tree_expanded,
        *file_selected,
        start_idx,
        end_idx,
    );
    lines.append(&mut item_lines);

    if total_items > available_height {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            i18n::t_fmt(
                app,
                "app.modals.preflight.files.showing_range_items",
                &[
                    &(start_idx + 1).to_string(),
                    &end_idx.to_string(),
                    &total_items.to_string(),
                ],
            ),
            Style::default().fg(th.subtext1),
        )));
    }

    lines
}

/// What: Render the Files tab content for the preflight modal.
///
/// Inputs:
/// - `app`: Application state for i18n and data access.
/// - `items`: Packages under review.
/// - `file_info`: File information.
/// - `file_selected`: Currently selected file index (mutable).
/// - `file_tree_expanded`: Set of expanded package names.
/// - `files_error`: Optional error message.
/// - `content_rect`: Content area rectangle.
///
/// Output:
/// - Returns a vector of lines to render.
///
/// Details:
/// - Shows file changes grouped by package with expand/collapse.
/// - Supports viewport-based rendering for large file lists.
#[allow(clippy::too_many_arguments)]
pub fn render_files_tab(
    app: &AppState,
    items: &[PackageItem],
    file_info: &[PackageFileInfo],
    file_selected: &mut usize,
    file_tree_expanded: &std::collections::HashSet<String>,
    files_error: Option<&String>,
    content_rect: Rect,
) -> Vec<Line<'static>> {
    const STALE_THRESHOLD_DAYS: u64 = 7;
    let is_resolving = app.preflight_files_resolving || app.files_resolving;

    let package_summaries = file_info
        .iter()
        .map(|pkg| FilePackageSummary {
            name: pkg.name.clone(),
            total: pkg.total_count,
            new_count: pkg.new_count,
            changed_count: pkg.changed_count,
            removed_count: pkg.removed_count,
            config_count: pkg.config_count,
            file_entries: pkg.files.len(),
        })
        .collect();

    log_files_state(&FilesLogState {
        items_len: items.len(),
        file_info_len: file_info.len(),
        file_selected: *file_selected,
        expanded_len: file_tree_expanded.len(),
        preflight_resolving: app.preflight_files_resolving,
        global_resolving: app.files_resolving,
        has_error: files_error.is_some(),
        package_summaries,
    });

    if is_resolving {
        let th = theme();
        return render_loading_state(app, items, "app.modals.preflight.files.updating", th.yellow);
    }

    if let Some(err_msg) = files_error {
        return render_error_state(app, err_msg);
    }

    if file_info.is_empty() {
        let th = theme();
        return render_loading_state(
            app,
            items,
            "app.modals.preflight.files.resolving",
            th.subtext1,
        );
    }

    let display_items = build_display_items(items, file_info, file_tree_expanded);
    let sync_info = crate::logic::files::get_file_db_sync_info();
    let is_stale = crate::logic::files::is_file_db_stale(STALE_THRESHOLD_DAYS);

    if display_items.is_empty() {
        render_empty_state(app, items, file_info, is_stale.as_ref(), sync_info.as_ref())
    } else {
        let ctx = FileListContext {
            file_info,
            items,
            display_items: &display_items,
            file_tree_expanded,
            sync_info: &sync_info,
        };
        render_file_list(app, &ctx, file_selected, content_rect)
    }
}