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

use crate::i18n;
use crate::state::{AppState, PackageItem};
use crate::theme::theme;
use crate::ui::helpers::ChangeLogger;
use std::collections::{HashMap, HashSet};
use std::fmt::Write;
use std::sync::{Mutex, OnceLock};

/// What: Type alias for sandbox display items.
///
/// Inputs: None
///
/// Output: None
///
/// Details:
/// - Represents a display item in the sandbox tab.
/// - Format: (`is_header`, `package_name`, `Option<`(`dep_type`, `dep_name`, `dep_info`)`>`)
type SandboxDisplayItem = (
    bool,
    String,
    Option<(
        &'static str, // "depends", "makedepends", "checkdepends", "optdepends"
        String,       // dependency name
        crate::logic::sandbox::DependencyDelta,
    )>,
);

/// What: Context struct grouping Sandbox tab fields to reduce data flow complexity.
///
/// Inputs: None (constructed from parameters).
///
/// Output: Groups related fields together for passing to render functions.
///
/// Details: Reduces individual field extractions and uses, lowering data flow complexity.
pub struct SandboxTabContext<'a> {
    /// Package items for the operation.
    pub items: &'a [PackageItem],
    /// Sandbox information for packages.
    pub sandbox_info: &'a [crate::logic::sandbox::SandboxInfo],
    /// Set of expanded package names in the tree view.
    pub sandbox_tree_expanded: &'a HashSet<String>,
    /// Whether sandbox data has been loaded.
    pub sandbox_loaded: bool,
    /// Optional error message if sandbox loading failed.
    pub sandbox_error: Option<&'a String>,
    /// Selected optional dependencies by package name.
    pub selected_optdepends: &'a HashMap<String, HashSet<String>>,
    /// Content area rectangle for rendering.
    pub content_rect: Rect,
}

/// What: Enum representing the current render state of the sandbox tab.
///
/// Inputs: None
///
/// Output: None
///
/// Details:
/// - Used to determine what should be rendered (error, loading, analyzing, etc.).
/// - Reduces data flow complexity by centralizing state checking logic.
enum SandboxRenderState {
    /// Error state with error message.
    Error(String),
    /// Loading sandbox data.
    Loading,
    /// Analyzing sandbox information.
    Analyzing,
    /// No AUR packages to analyze.
    NoAurPackages,
    /// Ready to display sandbox information.
    Ready,
}

/// What: State tracking for sandbox tab logging.
///
/// Inputs: None (constructed from current state).
///
/// Output: Captures current sandbox state for logging.
///
/// Details: Used to track and log sandbox tab state changes.
#[derive(Clone, PartialEq, Eq)]
struct SandboxLogState {
    /// Number of package items.
    items_len: usize,
    /// Number of sandbox info entries.
    sandbox_info_len: usize,
    /// Whether sandbox data has been loaded.
    sandbox_loaded: bool,
    /// Currently selected sandbox item index.
    sandbox_selected: usize,
    /// Number of expanded items in the tree.
    expanded_len: usize,
    /// Bitmask for tracking which items are being resolved.
    resolving_mask: u8,
    /// Whether there is an error state.
    has_error: bool,
}

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

    if logger.should_log(state) {
        tracing::debug!(
            "[UI] render_sandbox_tab: items={}, sandbox_info={}, sandbox_loaded={}, sandbox_selected={}, expanded={}, resolving={}/{}, error={}",
            state.items_len,
            state.sandbox_info_len,
            state.sandbox_loaded,
            state.sandbox_selected,
            state.expanded_len,
            state.resolving_mask & 1 != 0,
            state.resolving_mask & 2 != 0,
            state.has_error
        );
    }
}

/// What: Pre-computed render data to reduce data flow complexity.
///
/// Inputs: None
///
/// Output: None
///
/// Details:
/// - Groups derived values that are computed once and reused.
/// - Reduces intermediate variable assignments in the main function.
struct SandboxRenderData {
    /// Display items for rendering.
    display_items: Vec<SandboxDisplayItem>,
    /// Viewport (`start_index`, `end_index`).
    viewport: (usize, usize),
    /// Available height for rendering.
    available_height: usize,
    /// Total number of items.
    total_items: usize,
}

/// What: Determine the current render state of the sandbox tab.
///
/// Inputs:
/// - `app`: Application state for checking resolving flags.
/// - `ctx`: Sandbox tab context.
///
/// Output:
/// - Returns `SandboxRenderState` enum indicating what should be rendered.
///
/// Details:
/// - Centralizes state checking logic to reduce data flow complexity.
/// - Checks error, loading, analyzing, and no-AUR-packages states.
fn determine_sandbox_state(app: &AppState, ctx: &SandboxTabContext) -> SandboxRenderState {
    // Check if there are any AUR packages at all
    let has_aur = ctx
        .items
        .iter()
        .any(|i| matches!(i.source, crate::state::Source::Aur));

    if !has_aur {
        return SandboxRenderState::NoAurPackages;
    }

    // Handle error/loading/analyzing states
    if let Some(err) = ctx.sandbox_error {
        return SandboxRenderState::Error(err.clone());
    } else if app.preflight_sandbox_resolving || app.sandbox_resolving {
        return SandboxRenderState::Loading;
    } else if !ctx.sandbox_loaded || ctx.sandbox_info.is_empty() {
        return SandboxRenderState::Analyzing;
    }

    SandboxRenderState::Ready
}

/// What: Pre-compute render data to reduce data flow complexity.
///
/// Inputs:
/// - `ctx`: Sandbox tab context.
/// - `sandbox_selected`: Mutable reference to selected index (for viewport calculation).
///
/// Output:
/// - Returns `SandboxRenderData` with pre-computed values.
///
/// Details:
/// - Computes display items, viewport, and other derived values once.
/// - Reduces intermediate variable assignments in the main function.
fn compute_render_data(ctx: &SandboxTabContext, sandbox_selected: &mut usize) -> SandboxRenderData {
    // Build flat list of display items: package headers + dependencies (only if expanded)
    let display_items = build_display_items(ctx.items, ctx.sandbox_info, ctx.sandbox_tree_expanded);

    // Calculate viewport based on selected index (like Deps/Files tabs)
    // Performance optimization: Only render visible items (viewport-based rendering)
    // This prevents performance issues with large dependency lists
    let available_height = (ctx.content_rect.height as usize).saturating_sub(6);
    let total_items = display_items.len();

    let viewport = calculate_viewport(
        total_items,
        *sandbox_selected,
        available_height,
        sandbox_selected,
    );

    SandboxRenderData {
        display_items,
        viewport,
        available_height,
        total_items,
    }
}

/// What: Render error state for sandbox tab.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `error`: Error message to display.
///
/// Output:
/// - Returns vector of lines for error display.
///
/// Details:
/// - Shows error message and retry hint.
fn render_error_state(app: &AppState, error: &str) -> Vec<Line<'static>> {
    let th = theme();
    let mut lines = Vec::new();
    tracing::warn!("[UI] render_sandbox_tab: Displaying error: {}", error);
    lines.push(Line::from(Span::styled(
        i18n::t_fmt1(app, "app.modals.preflight.sandbox.error", error),
        Style::default().fg(th.red),
    )));
    lines.push(Line::from(Span::styled(
        i18n::t(app, "app.modals.preflight.sandbox.retry_hint"),
        Style::default().fg(th.subtext0),
    )));
    lines.push(Line::from(""));
    lines
}

/// What: Render AUR package headers.
///
/// Inputs:
/// - `items`: Packages to render headers for.
///
/// Output:
/// - Returns vector of lines with package headers.
///
/// Details:
/// - Only renders headers for AUR packages.
fn render_aur_package_headers(items: &[PackageItem]) -> Vec<Line<'static>> {
    let th = theme();
    let mut lines = Vec::new();
    for item in items {
        let is_aur = matches!(item.source, crate::state::Source::Aur);
        if is_aur {
            let item_name = &item.name;
            lines.push(Line::from(Span::styled(
                format!("{item_name} "),
                Style::default()
                    .fg(th.overlay1)
                    .add_modifier(Modifier::BOLD),
            )));
        }
    }
    lines
}

/// What: Render loading state for sandbox tab.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `items`: Packages to show headers for.
///
/// Output:
/// - Returns vector of lines for loading display.
///
/// Details:
/// - Shows AUR package headers and loading message.
fn render_loading_state(app: &AppState, items: &[PackageItem]) -> Vec<Line<'static>> {
    let th = theme();
    let mut lines = render_aur_package_headers(items);
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        i18n::t(app, "app.modals.preflight.sandbox.updating"),
        Style::default().fg(th.yellow),
    )));
    lines
}

/// What: Render analyzing state for sandbox tab.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `items`: Packages to show headers for.
///
/// Output:
/// - Returns vector of lines for analyzing display.
///
/// Details:
/// - Shows AUR package headers and analyzing message.
fn render_analyzing_state(app: &AppState, items: &[PackageItem]) -> Vec<Line<'static>> {
    let th = theme();
    let mut lines = render_aur_package_headers(items);
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        i18n::t(app, "app.modals.preflight.sandbox.analyzing"),
        Style::default().fg(th.subtext0),
    )));
    lines
}

/// What: Render message when all packages are official (no sandbox needed).
///
/// Inputs:
/// - `app`: Application state for i18n.
///
/// Output:
/// - Returns vector of lines for no AUR packages display.
///
/// Details:
/// - Shows informational message that sandbox is only for AUR packages.
fn render_no_aur_packages_state(app: &AppState) -> Vec<Line<'static>> {
    let th = theme();
    vec![
        Line::from(Span::styled(
            i18n::t(app, "app.modals.preflight.sandbox.no_aur_packages"),
            Style::default().fg(th.subtext1),
        )),
        Line::from(""),
        Line::from(Span::styled(
            i18n::t(app, "app.modals.preflight.sandbox.sandbox_only_for_aur"),
            Style::default().fg(th.subtext0),
        )),
    ]
}

/// What: Build flat list of display items from packages and sandbox info.
///
/// Inputs:
/// - `items`: Packages under review.
/// - `sandbox_info`: Sandbox information.
/// - `sandbox_tree_expanded`: Set of expanded package names.
///
/// Output:
/// - Returns vector of display items.
///
/// Details:
/// - Creates flat list with package headers and dependencies (only if expanded).
fn build_display_items(
    items: &[PackageItem],
    sandbox_info: &[crate::logic::sandbox::SandboxInfo],
    sandbox_tree_expanded: &HashSet<String>,
) -> Vec<SandboxDisplayItem> {
    let mut display_items = Vec::new();

    for item in items {
        let is_aur = matches!(item.source, crate::state::Source::Aur);
        let is_expanded = sandbox_tree_expanded.contains(&item.name);

        // Add package header
        display_items.push((true, item.name.clone(), None));

        // Add dependencies only if expanded and AUR
        if is_expanded
            && is_aur
            && let Some(info) = sandbox_info.iter().find(|s| s.package_name == item.name)
        {
            tracing::debug!(
                "[UI] render_sandbox_tab: Expanding package '{}' with {} depends, {} makedepends, {} checkdepends, {} optdepends",
                item.name,
                info.depends.len(),
                info.makedepends.len(),
                info.checkdepends.len(),
                info.optdepends.len()
            );
            // Runtime dependencies (depends)
            for dep in &info.depends {
                display_items.push((
                    false,
                    item.name.clone(),
                    Some(("depends", dep.name.clone(), dep.clone())),
                ));
            }
            // Build dependencies (makedepends)
            for dep in &info.makedepends {
                display_items.push((
                    false,
                    item.name.clone(),
                    Some(("makedepends", dep.name.clone(), dep.clone())),
                ));
            }
            // Test dependencies (checkdepends)
            for dep in &info.checkdepends {
                display_items.push((
                    false,
                    item.name.clone(),
                    Some(("checkdepends", dep.name.clone(), dep.clone())),
                ));
            }
            // Optional dependencies (optdepends)
            for dep in &info.optdepends {
                display_items.push((
                    false,
                    item.name.clone(),
                    Some(("optdepends", dep.name.clone(), dep.clone())),
                ));
            }
        } else if is_aur && is_expanded {
            // AUR package is expanded but no sandbox info found - log warning
            tracing::warn!(
                "[UI] render_sandbox_tab: Package '{}' is AUR and expanded but no sandbox info found",
                item.name
            );
        }
    }

    display_items
}

/// What: Calculate viewport range for visible items.
///
/// Inputs:
/// - `total_items`: Total number of display items.
/// - `selected_idx`: Currently selected item index.
/// - `available_height`: Available height for rendering.
/// - `sandbox_selected`: Mutable reference to selected index (for clamping).
///
/// Output:
/// - Returns (`start_idx`, `end_idx`) viewport range.
///
/// Details:
/// - Ensures selected item is always visible.
/// - Accounts for section headers that add extra lines.
fn calculate_viewport(
    total_items: usize,
    selected_idx: usize,
    available_height: usize,
    sandbox_selected: &mut usize,
) -> (usize, usize) {
    // Validate and clamp selected index to prevent out-of-bounds access
    let sandbox_selected_clamped = if total_items > 0 {
        selected_idx.min(total_items.saturating_sub(1))
    } else {
        0
    };
    if *sandbox_selected != sandbox_selected_clamped {
        tracing::warn!(
            "[UI] render_sandbox_tab: Clamping sandbox_selected from {} to {} (total_items={})",
            *sandbox_selected,
            sandbox_selected_clamped,
            total_items
        );
        *sandbox_selected = sandbox_selected_clamped;
    }

    if total_items <= available_height {
        // All items fit on screen
        return (0, total_items);
    }

    // Ensure selected item is always visible - keep it within [start_idx, end_idx)
    // Try to center it, but adjust if needed to keep it visible
    // Reduce available_height slightly to account for section headers that add extra lines
    let effective_height = available_height.saturating_sub(2); // Reserve space for section headers
    let mut start_idx = sandbox_selected_clamped
        .saturating_sub(effective_height / 2)
        .max(0)
        .min(total_items.saturating_sub(effective_height));
    let mut end_idx = (start_idx + effective_height).min(total_items);

    // Ensure selected item is within bounds - adjust if necessary
    if sandbox_selected_clamped < start_idx {
        // Selected item is before start - move start to include it
        start_idx = sandbox_selected_clamped;
        end_idx = (start_idx + effective_height).min(total_items);
    } else if sandbox_selected_clamped >= end_idx {
        // Selected item is at or beyond end - position it at bottom of viewport
        // Make sure to include it even if section headers take up space
        end_idx = (sandbox_selected_clamped + 1).min(total_items);
        start_idx = end_idx.saturating_sub(effective_height).max(0);
        end_idx = (start_idx + effective_height).min(total_items);
        // Final check: ensure selected item is visible
        if sandbox_selected_clamped >= end_idx {
            end_idx = sandbox_selected_clamped + 1;
            start_idx = end_idx.saturating_sub(effective_height).max(0);
        }
    }

    (start_idx, end_idx)
}

/// What: Get dependency status icon based on dependency state.
///
/// Inputs:
/// - `dep`: Dependency delta information.
/// - `dep_type`: Type of dependency.
/// - `is_optdep_selected`: Whether optional dependency is selected.
///
/// Output:
/// - Returns status icon string.
///
/// Details:
/// - Returns appropriate icon based on installation and version status.
fn get_dependency_status_icon(
    dep: &crate::logic::sandbox::DependencyDelta,
    dep_type: &str,
    is_optdep_selected: bool,
) -> &'static str {
    if dep.is_installed {
        if dep.version_satisfied { "" } else { "" }
    } else {
        match dep_type {
            "optdepends" => {
                if is_optdep_selected {
                    "" // Checkbox checked
                } else {
                    "" // Checkbox unchecked
                }
            }
            "checkdepends" => "",
            _ => "",
        }
    }
}

/// What: Get dependency status color based on dependency state.
///
/// Inputs:
/// - `dep`: Dependency delta information.
/// - `dep_type`: Type of dependency.
/// - `is_optdep_selected`: Whether optional dependency is selected.
///
/// Output:
/// - Returns color from theme.
///
/// Details:
/// - Returns appropriate color based on installation and version status.
fn get_dependency_status_color(
    dep: &crate::logic::sandbox::DependencyDelta,
    dep_type: &str,
    is_optdep_selected: bool,
) -> ratatui::style::Color {
    let th = theme();
    if dep.is_installed {
        if dep.version_satisfied {
            th.green
        } else {
            th.yellow
        }
    } else {
        match dep_type {
            "optdepends" => {
                if is_optdep_selected {
                    th.sapphire // Highlight selected optdepends
                } else {
                    th.subtext0
                }
            }
            "checkdepends" => th.subtext0,
            _ => th.red,
        }
    }
}

/// What: Render package header line.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `item`: Package item to render.
/// - `is_expanded`: Whether package is expanded.
/// - `is_selected`: Whether package is selected.
///
/// Output:
/// - Returns line for package header.
///
/// Details:
/// - Formats package header with source and expansion indicator.
fn render_package_header(
    app: &AppState,
    item: &PackageItem,
    is_expanded: bool,
    is_selected: bool,
) -> Line<'static> {
    let th = theme();
    let is_aur = matches!(item.source, crate::state::Source::Aur);
    let arrow_symbol = if is_aur && is_expanded {
        ""
    } else if is_aur {
        ""
    } else {
        ""
    };

    let header_style = if is_selected {
        Style::default()
            .fg(th.crust)
            .bg(th.sapphire)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default()
            .fg(th.sapphire)
            .add_modifier(Modifier::BOLD)
    };

    let source_str = match &item.source {
        crate::state::Source::Aur => "AUR".to_string(),
        crate::state::Source::Official { repo, .. } => repo.clone(),
    };
    let mut header_text = i18n::t_fmt(
        app,
        "app.modals.preflight.sandbox.package_label",
        &[&item.name, &source_str],
    );
    if !arrow_symbol.is_empty() {
        header_text = format!("{arrow_symbol} {header_text}");
    }

    Line::from(Span::styled(header_text, header_style))
}

/// What: Render package header details (messages for official/collapsed packages).
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `pkg_name`: Package name.
/// - `is_aur`: Whether package is from AUR.
/// - `is_expanded`: Whether package is expanded.
/// - `sandbox_info`: Sandbox information to get dependency counts.
///
/// Output:
/// - Returns vector of lines for package details.
///
/// Details:
/// - Shows message for official packages or dependency count for collapsed AUR packages.
fn render_package_header_details(
    app: &AppState,
    pkg_name: &str,
    is_aur: bool,
    is_expanded: bool,
    sandbox_info: &[crate::logic::sandbox::SandboxInfo],
) -> Vec<Line<'static>> {
    let th = theme();
    let mut lines = Vec::new();

    // Show message for official packages or collapsed AUR packages
    if !is_aur {
        lines.push(Line::from(Span::styled(
            format!(
                "  {}",
                i18n::t(
                    app,
                    "app.modals.preflight.sandbox.official_packages_prebuilt"
                )
            ),
            Style::default().fg(th.subtext0),
        )));
    } else if !is_expanded {
        // Show dependency count for collapsed AUR packages
        if let Some(info) = sandbox_info.iter().find(|s| s.package_name == pkg_name) {
            let dep_count = info.depends.len()
                + info.makedepends.len()
                + info.checkdepends.len()
                + info.optdepends.len();
            if dep_count > 0 {
                lines.push(Line::from(Span::styled(
                    format!(
                        "  {}",
                        i18n::t_fmt1(
                            app,
                            "app.modals.preflight.sandbox.dependencies_expand_hint",
                            dep_count.to_string()
                        )
                    ),
                    Style::default().fg(th.subtext1),
                )));
            } else {
                lines.push(Line::from(Span::styled(
                    format!(
                        "  {}",
                        i18n::t(app, "app.modals.preflight.sandbox.no_build_dependencies")
                    ),
                    Style::default().fg(th.green),
                )));
            }
        } else {
            // AUR package but no sandbox info - this shouldn't happen but handle gracefully
            tracing::debug!(
                "[UI] render_sandbox_tab: AUR package '{}' collapsed but no sandbox info found",
                pkg_name
            );
        }
    }

    lines
}

/// What: Render dependency section header when dependency type changes.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `dep_type`: Type of dependency.
///
/// Output:
/// - Returns optional line for section header.
///
/// Details:
/// - Returns section header line if `dep_type` is valid.
fn render_dependency_section_header(app: &AppState, dep_type: &str) -> Option<Line<'static>> {
    let th = theme();
    let section_name = match dep_type {
        "depends" => i18n::t(app, "app.modals.preflight.sandbox.runtime_dependencies"),
        "makedepends" => i18n::t(app, "app.modals.preflight.sandbox.build_dependencies"),
        "checkdepends" => i18n::t(app, "app.modals.preflight.sandbox.test_dependencies"),
        "optdepends" => i18n::t(app, "app.modals.preflight.sandbox.optional_dependencies"),
        _ => return None,
    };
    Some(Line::from(Span::styled(
        section_name,
        Style::default()
            .fg(th.sapphire)
            .add_modifier(Modifier::BOLD),
    )))
}

/// What: Render dependency line.
///
/// Inputs:
/// - `dep_name`: Dependency name.
/// - `dep`: Dependency delta information.
/// - `dep_type`: Type of dependency.
/// - `is_optdep_selected`: Whether optional dependency is selected.
/// - `is_selected`: Whether dependency is selected.
///
/// Output:
/// - Returns line for dependency.
///
/// Details:
/// - Formats dependency line with status icon and version info.
fn render_dependency_line(
    dep_name: &str,
    dep: &crate::logic::sandbox::DependencyDelta,
    dep_type: &str,
    is_optdep_selected: bool,
    is_selected: bool,
) -> Line<'static> {
    let th = theme();
    let status_icon = get_dependency_status_icon(dep, dep_type, is_optdep_selected);
    let status_color = get_dependency_status_color(dep, dep_type, is_optdep_selected);

    let dep_style = if is_selected {
        Style::default()
            .fg(th.crust)
            .bg(th.sapphire)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(status_color)
    };

    let mut dep_line = format!("  {status_icon} {dep_name}");
    if let Some(ref version) = dep.installed_version {
        let _ = write!(dep_line, " (installed: {version})");
    }
    if dep_type == "optdepends" && is_optdep_selected {
        dep_line.push_str(" [selected]");
    }
    Line::from(Span::styled(dep_line, dep_style))
}

/// What: Render visible display items in the viewport.
///
/// Inputs:
/// - `app`: Application state for i18n.
/// - `ctx`: Sandbox tab context.
/// - `render_data`: Pre-computed render data.
/// - `selected_idx`: Currently selected item index.
///
/// Output:
/// - Returns vector of lines for visible items.
///
/// Details:
/// - Renders only items within the viewport range.
/// - Handles package headers and dependency items.
/// - Tracks dependency section headers.
fn render_display_items(
    app: &AppState,
    ctx: &SandboxTabContext,
    render_data: &SandboxRenderData,
    selected_idx: usize,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    let (start_idx, end_idx) = render_data.viewport;

    // Track which packages we've seen to group dependencies properly
    let mut last_dep_type: Option<&str> = None;

    // Render visible items
    for (idx, (is_header, pkg_name, dep_opt)) in render_data
        .display_items
        .iter()
        .enumerate()
        .skip(start_idx)
        .take(end_idx - start_idx)
    {
        let is_selected = idx == selected_idx;

        if *is_header {
            // Package header
            let Some(item) = ctx.items.iter().find(|p| p.name == *pkg_name) else {
                tracing::warn!(
                    "[UI] render_sandbox_tab: Package '{}' not found in items list, skipping",
                    pkg_name
                );
                continue;
            };
            let is_aur = matches!(item.source, crate::state::Source::Aur);
            let is_expanded = ctx.sandbox_tree_expanded.contains(pkg_name);

            lines.push(render_package_header(app, item, is_expanded, is_selected));
            last_dep_type = None;

            // Show message for official packages or collapsed AUR packages
            lines.extend(render_package_header_details(
                app,
                pkg_name,
                is_aur,
                is_expanded,
                ctx.sandbox_info,
            ));
        } else if let Some((dep_type, dep_name, dep)) = dep_opt {
            // Dependency item (indented)
            // Show section header when dep_type changes
            if last_dep_type != Some(dep_type) {
                if let Some(header_line) = render_dependency_section_header(app, dep_type) {
                    lines.push(header_line);
                }
                last_dep_type = Some(dep_type);
            }

            // Check if this is a selected optional dependency
            let is_optdep_selected = if *dep_type == "optdepends" {
                ctx.selected_optdepends.get(pkg_name).is_some_and(|set| {
                    // Extract package name from dependency spec (may include version or description)
                    let pkg_name_from_dep = crate::logic::sandbox::extract_package_name(dep_name);
                    set.contains(dep_name) || set.contains(&pkg_name_from_dep)
                })
            } else {
                false
            };

            lines.push(render_dependency_line(
                dep_name,
                dep,
                dep_type,
                is_optdep_selected,
                is_selected,
            ));
        }
    }

    lines
}

/// What: Render the Sandbox tab content for the preflight modal.
///
/// Inputs:
/// - `app`: Application state for i18n and data access.
/// - `ctx`: Sandbox tab context containing all render parameters.
/// - `sandbox_selected`: Currently selected sandbox item index (mutable).
///
/// Output:
/// - Returns a vector of lines to render.
///
/// Details:
/// - Shows sandbox dependency analysis for AUR packages.
/// - Supports viewport-based rendering for large dependency lists.
/// - Uses context struct to reduce data flow complexity.
pub fn render_sandbox_tab(
    app: &AppState,
    ctx: &SandboxTabContext,
    sandbox_selected: &mut usize,
) -> Vec<Line<'static>> {
    let th = theme();
    let resolving_mask =
        u8::from(app.preflight_sandbox_resolving) | (u8::from(app.sandbox_resolving) << 1);

    log_sandbox_state(&SandboxLogState {
        items_len: ctx.items.len(),
        sandbox_info_len: ctx.sandbox_info.len(),
        sandbox_loaded: ctx.sandbox_loaded,
        sandbox_selected: *sandbox_selected,
        expanded_len: ctx.sandbox_tree_expanded.len(),
        resolving_mask,
        has_error: ctx.sandbox_error.is_some(),
    });

    // Determine render state (reduces data flow complexity by centralizing state checks)
    let render_state = determine_sandbox_state(app, ctx);

    // Handle early return states
    match render_state {
        SandboxRenderState::NoAurPackages => {
            tracing::debug!(
                "[UI] render_sandbox_tab: No AUR packages in list (all {} packages are official), showing info message",
                ctx.items.len()
            );
            return render_no_aur_packages_state(app);
        }
        SandboxRenderState::Error(err) => {
            return render_error_state(app, &err);
        }
        SandboxRenderState::Loading => {
            let aur_count = ctx
                .items
                .iter()
                .filter(|i| matches!(i.source, crate::state::Source::Aur))
                .count();
            tracing::debug!(
                "[UI] render_sandbox_tab: Showing loading state (resolving={}/{}, {} AUR packages)",
                app.preflight_sandbox_resolving,
                app.sandbox_resolving,
                aur_count
            );
            return render_loading_state(app, ctx.items);
        }
        SandboxRenderState::Analyzing => {
            tracing::debug!(
                "[UI] render_sandbox_tab: Not loaded or empty (loaded={}, info_len={}), showing analyzing message",
                ctx.sandbox_loaded,
                ctx.sandbox_info.len()
            );
            return render_analyzing_state(app, ctx.items);
        }
        SandboxRenderState::Ready => {
            // Continue with normal rendering
        }
    }

    // Pre-compute render data (reduces data flow complexity)
    let render_data = compute_render_data(ctx, sandbox_selected);

    tracing::debug!(
        "[UI] render_sandbox_tab: Rendering data - total_items={}, sandbox_selected={}, items={}, sandbox_info={}, expanded_count={}, available_height={}",
        render_data.total_items,
        *sandbox_selected,
        ctx.items.len(),
        ctx.sandbox_info.len(),
        ctx.sandbox_tree_expanded.len(),
        render_data.available_height
    );

    // Render visible items (extracted to reduce complexity)
    let mut lines = render_display_items(app, ctx, &render_data, *sandbox_selected);

    // Show indicator if there are more items below
    let (_, end_idx) = render_data.viewport;
    if end_idx < render_data.total_items {
        lines.push(Line::from(Span::styled(
            format!(
                "{} more item{}",
                render_data.total_items - end_idx,
                if render_data.total_items - end_idx == 1 {
                    ""
                } else {
                    "s"
                }
            ),
            Style::default().fg(th.subtext1),
        )));
    }

    // If no packages at all
    if ctx.items.is_empty() {
        lines.push(Line::from(Span::styled(
            i18n::t(app, "app.modals.preflight.sandbox.no_packages"),
            Style::default().fg(th.subtext0),
        )));
    }

    lines
}